Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions credentials/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { TelemetryAttributes } from "../telemetry/attributes";
import { TelemetryCounters } from "../telemetry/counters";
import { TelemetryConfiguration } from "../telemetry/configuration";
import { randomUUID } from "crypto";
import SdkConstants from "../constants";
Copy link

Copilot AI Feb 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file header states it is auto-generated (“DO NOT EDIT”), but this change introduces a new import. If this file is regenerated as part of the build/release process, these edits may be overwritten; consider updating the generator template/source or adjusting the generation settings/header so the change persists reliably.

Copilot uses AI. Check for mistakes.

interface ClientSecretRequest {
client_id: string;
Expand All @@ -45,6 +46,7 @@ export const DEFAULT_TOKEN_ENDPOINT_PATH = "oauth/token";
export class Credentials {
private accessToken?: string;
private accessTokenExpiryDate?: Date;
private accessTokenExpiryBufferInMs = 0;

public static init(configuration: { credentials: AuthCredentialsConfig, telemetry: TelemetryConfiguration, baseOptions?: any }, axios: AxiosInstance = globalAxios): Credentials {
return new Credentials(configuration.credentials, axios, configuration.telemetry, configuration.baseOptions);
Expand Down Expand Up @@ -136,13 +138,17 @@ export class Credentials {
return;
case CredentialsMethod.ApiToken:
return this.authConfig.config.token;
case CredentialsMethod.ClientCredentials:
if (this.accessToken && (!this.accessTokenExpiryDate || this.accessTokenExpiryDate > new Date())) {
case CredentialsMethod.ClientCredentials: {
const tokenIsValid = !this.accessTokenExpiryDate || (
this.accessTokenExpiryDate.getTime() - Date.now() > this.accessTokenExpiryBufferInMs
);
if (this.accessToken && tokenIsValid) {
return this.accessToken;
}

return this.refreshAccessToken();
}
}
}

/**
Expand Down Expand Up @@ -208,6 +214,10 @@ export class Credentials {
if (response) {
this.accessToken = response.data.access_token;
this.accessTokenExpiryDate = new Date(Date.now() + response.data.expires_in * 1000);
this.accessTokenExpiryBufferInMs = (
SdkConstants.TokenExpiryThresholdBufferInSec +
(Math.random() * SdkConstants.TokenExpiryJitterInSec)
) * 1000;
}

if (this.telemetryConfig?.metrics?.counterCredentialsRequest?.attributes) {
Expand Down
49 changes: 49 additions & 0 deletions tests/credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as jose from "jose";
import { Credentials, CredentialsMethod, DEFAULT_TOKEN_ENDPOINT_PATH } from "../credentials";
import { AuthCredentialsConfig } from "../credentials/types";
import { TelemetryConfiguration } from "../telemetry/configuration";
import SdkConstants from "../constants";
import {
OPENFGA_API_AUDIENCE,
OPENFGA_CLIENT_ASSERTION_SIGNING_KEY,
Expand Down Expand Up @@ -537,5 +538,53 @@ describe("Credentials", () => {

expect(scope.isDone()).toBe(true);
});

test("should refresh cached token when it is close to expiration", async () => {
const apiTokenIssuer = "issuer.fga.example";
const expectedBaseUrl = "https://issuer.fga.example";
const expectedPath = `/${DEFAULT_TOKEN_ENDPOINT_PATH}`;
const randomSpy = jest.spyOn(Math, "random").mockReturnValue(0);
const shortLivedTokenInSec = Math.max(
1,
SdkConstants.TokenExpiryThresholdBufferInSec - 1
);

const scope = nock(expectedBaseUrl)
.post(expectedPath)
.reply(200, {
access_token: "short-lived-token",
expires_in: shortLivedTokenInSec,
})
Comment on lines 554 to 557
Copy link

Copilot AI Feb 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test hardcodes expires_in: 120, which is only “close to expiration” relative to the current buffer/jitter constants. To keep the test resilient if TokenExpiryThresholdBufferInSec/TokenExpiryJitterInSec change, consider stubbing Math.random() and deriving expires_in from the exported constants so the token is guaranteed to fall within the buffer window.

Copilot uses AI. Check for mistakes.
.post(expectedPath)
.reply(200, {
access_token: "refreshed-token",
expires_in: 3600,
});

const credentials = new Credentials(
{
method: CredentialsMethod.ClientCredentials,
config: {
apiTokenIssuer,
apiAudience: OPENFGA_API_AUDIENCE,
clientId: OPENFGA_CLIENT_ID,
clientSecret: OPENFGA_CLIENT_SECRET,
},
} as AuthCredentialsConfig,
undefined,
mockTelemetryConfig,
);

try {
const header1 = await credentials.getAccessTokenHeader();
const header2 = await credentials.getAccessTokenHeader();

expect(header1?.value).toBe("Bearer short-lived-token");
expect(header2?.value).toBe("Bearer refreshed-token");
expect(scope.isDone()).toBe(true);
} finally {
randomSpy.mockRestore();
}
});
});
});
4 changes: 3 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ describe("OpenFGA SDK", function () {
});

it("should cache the bearer token and not issue a network call to get the token at the second request", async () => {
let scope = nocks.tokenExchange(OPENFGA_API_TOKEN_ISSUER);
// Use a long-lived token so this test validates caching behavior
// independently from proactive near-expiry refresh logic.
let scope = nocks.tokenExchange(OPENFGA_API_TOKEN_ISSUER, "test-token", 3600);
nocks.readAuthorizationModels(baseConfig.storeId!);

const fgaApi = new OpenFgaApi(baseConfig);
Expand Down
Loading