Skip to content

Commit f85a026

Browse files
committed
fix: update MetadataCredentialsToken structure and adjust token retrieval logic
Signed-off-by: Vladislav Polyakov <[email protected]>
1 parent 7f7743b commit f85a026

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

packages/auth/src/metadata.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import { CredentialsProvider } from "./index.js";
55
import { dbg } from "./dbg.js";
66

77
export type MetadataCredentialsToken = {
8-
access_token: string
9-
expires_in: number
8+
value: string
9+
expired_at: number
1010
}
1111

1212
export type MetadataCredentials = {
@@ -30,6 +30,13 @@ export class MetadataCredentialsProvider extends CredentialsProvider {
3030
#flavor: string = 'Google'
3131
#endpoint: string = 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token'
3232

33+
/**
34+
* Creates an instance of `MetadataCredentialsProvider`.
35+
*
36+
* @param credentials - An optional object containing metadata credentials.
37+
* @param credentials.flavor - The metadata flavor (default: 'Google').
38+
* @param credentials.endpoint - The metadata endpoint URL (default: 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token').
39+
*/
3340
constructor(credentials: MetadataCredentials = {}) {
3441
super()
3542
if (credentials.flavor) {
@@ -52,8 +59,8 @@ export class MetadataCredentialsProvider extends CredentialsProvider {
5259
* @throws Will throw an error if the token fetch fails, the response is not OK, or the content type is incorrect.
5360
*/
5461
async getToken(force?: boolean, signal?: AbortSignal): Promise<string> {
55-
if (!force && this.#token && this.#token.expires_in > Date.now() / 1000) {
56-
return this.#token.access_token
62+
if (!force && this.#token && this.#token.expired_at > Date.now()) {
63+
return this.#token.value
5764
}
5865

5966
if (this.#promise) {
@@ -81,14 +88,18 @@ export class MetadataCredentialsProvider extends CredentialsProvider {
8188
throw new Error(`Failed to fetch token: ${response.status} ${response.statusText}`)
8289
}
8390

84-
this.#token = JSON.parse(await response.text())
85-
86-
if (!this.#token!.access_token) {
87-
dbg('missing token in response, response=%O', this.#token)
91+
let token = JSON.parse(await response.text()) as { access_token?: string, expires_in?: number }
92+
if (!token.access_token) {
93+
dbg('missing access token in response, response=%O', token)
8894
throw new Error('No access token exists in response');
8995
}
9096

91-
return this.#token!.access_token
97+
this.#token = {
98+
value: token.access_token,
99+
expired_at: Date.now() + (token.expires_in ?? 3600) * 1000,
100+
}
101+
102+
return this.#token.value
92103
}).finally(() => {
93104
this.#promise = null
94105
})

0 commit comments

Comments
 (0)