Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(identity-access-token): expire the uses-remaining counter with its token
Scott Wilson0f23806c2e9d
diff --git a/backend/src/services/identity-access-token/identity-access-token-fns.test.ts b/backend/src/services/identity-access-token/identity-access-token-fns.test.tsindex 1efd62378a..80ec6f2842 100644--- a/backend/src/services/identity-access-token/identity-access-token-fns.test.ts+++ b/backend/src/services/identity-access-token/identity-access-token-fns.test.ts@@ -6,6 +6,7 @@ import {computeRevocationVerdictFingerprint,computeSingleIssuanceTtlCap,computeTokenAuthRevokeMarkerExpiry,+ computeUsesRemainingTtl,evaluateRevocationMarkers,hasLegacyTokenWithoutExpExceededMaxAge,IDENTITY_REVOCATION_MARKER_SKEW_SECONDS,@@ -175,6 +176,24 @@ describe("computeSingleIssuanceTtlCap", () => {});});+describe("computeUsesRemainingTtl", () => {+ test("lives exactly as long as the JWT has left", () => {+ expect(computeUsesRemainingTtl({ exp: NOW + 3600, nowSeconds: NOW })).toBe(3600);+ });++ test("never outlives the ceiling", () => {+ expect(computeUsesRemainingTtl({ exp: NOW + MAX_AGE + 10_000, nowSeconds: NOW })).toBe(MAX_AGE);+ });++ test("stays positive for a JWT that expires this second", () => {+ expect(computeUsesRemainingTtl({ exp: NOW, nowSeconds: NOW })).toBe(1);+ });++ test("falls back to the ceiling for a legacy JWT with no exp", () => {+ expect(computeUsesRemainingTtl({ nowSeconds: NOW })).toBe(MAX_AGE);+ });+});+describe("computePerTokenMarkerExpiry", () => {test("tightens a short-TTL / large-maxTTL token to exp + one issuance TTL + skew", () => {const twoHours = 7200;diff --git a/backend/src/services/identity-access-token/identity-access-token-fns.ts b/backend/src/services/identity-access-token/identity-access-token-fns.tsindex d4a4494137..f6d96e1ded 100644--- a/backend/src/services/identity-access-token/identity-access-token-fns.ts+++ b/backend/src/services/identity-access-token/identity-access-token-fns.ts@@ -143,6 +143,23 @@ export const computeIssuedTtl = ({return Math.min(requestedCap, remainingBudget, ceiling);};+// How long the uses-remaining counter must live: as long as the JWT it counts against can still be+// presented. An expired JWT is rejected before the counter is read, so keeping the key longer only+// leaves a dead key in Redis. A JWT with no exp (legacy) falls back to the configured ceiling.+export const computeUsesRemainingTtl = ({+ exp,+ nowSeconds = Math.floor(Date.now() / 1000)+}: {+ exp?: number;+ nowSeconds?: number;+}): number => {+ const { MAX_MACHINE_IDENTITY_TOKEN_AGE: ceiling } = getConfig();+ if (typeof exp !== "number") {+ return ceiling;+ }+ return Math.min(Math.max(exp - nowSeconds, 1), ceiling);+};+// Extra 5 minutes added to when a revocation record expires. Guards against// small clock differences between servers and a slightly stale database replica// so a revoked token can't slip through by dropping the record too early.diff --git a/backend/src/services/identity-access-token/identity-access-token-service.test.ts b/backend/src/services/identity-access-token/identity-access-token-service.test.tsindex e7ba1477a5..727c193f94 100644--- a/backend/src/services/identity-access-token/identity-access-token-service.test.ts+++ b/backend/src/services/identity-access-token/identity-access-token-service.test.ts@@ -352,12 +352,80 @@ describe("identityAccessTokenServiceFactory", () => {});expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith("identity-token-uses-remaining:identity-id:token-id",- MAX_AGE,+ 3600,2);expect(keyStore.incrementBy).not.toHaveBeenCalled();});+ test("reseeds a lost counter for a legacy JWT with no exp using the ceiling", async () => {+ const { service, keyStore } = createService();+ keyStore.getItem.mockResolvedValue(null);++ await service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3, exp: undefined }), "10.0.0.1");+ expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(+ "identity-token-uses-remaining:identity-id:token-id",+ MAX_AGE,+ 2+ );+ });++ test("seeds the usage counter at issuance to expire with the token, not the ceiling", async () => {+ const { service, keyStore } = createService();++ await service.issueIdentityAccessToken({+ identityId: "identity-id",+ identityName: "identity-name",+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ orgId: "org-id",+ rootOrgId: "root-org-id",+ parentOrgId: "parent-org-id",+ subOrganizationId: null,+ accessTokenTTL: 600,+ accessTokenMaxTTL: 0,+ accessTokenNumUsesLimit: 1,+ accessTokenPeriod: 0,+ accessTokenTrustedIps: []+ });++ expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(+ expect.stringMatching(/^identity-token-uses-remaining:identity-id:/),+ 600,+ 1+ );+ });++ test("reseeds the usage counter on renewal to expire with the renewed token", async () => {+ const { accessToken } = signIdentityAccessToken({+ identityAccessTokenId: "token-id",+ identityId: "identity-id",+ identityName: "identity-name",+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ orgId: "org-id",+ rootOrgId: "root-org-id",+ parentOrgId: "parent-org-id",+ clientSecretId: "",+ numUsesLimit: 2,+ ipRestrictionEnabled: false,+ ttlSeconds: 3600,+ accessTokenTTL: 3600,+ accessTokenMaxTTL: 7200,+ accessTokenPeriod: 0,+ creationEpoch: NOW_SECONDS,+ identityAuth: {}+ });+ const { service, keyStore } = createService();+ keyStore.getItem.mockResolvedValue("1");++ await service.renewAccessToken({ accessToken });++ expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(+ "identity-token-uses-remaining:identity-id:token-id",+ 3600,+ 1+ );+ });+test("does not require Redis counters for unlimited-use tokens", async () => {const { service, keyStore } = createService();diff --git a/backend/src/services/identity-access-token/identity-access-token-service.ts b/backend/src/services/identity-access-token/identity-access-token-service.tsindex d2e4cd379a..1b9c545eaf 100644--- a/backend/src/services/identity-access-token/identity-access-token-service.ts+++ b/backend/src/services/identity-access-token/identity-access-token-service.ts@@ -22,6 +22,7 @@ import {computeIssuedTtl,computePerTokenMarkerExpiry,computeRevocationVerdictFingerprint,+ computeUsesRemainingTtl,evaluateRevocationMarkers,hasFullRenewClaims,hasLegacyTokenWithoutExpExceededMaxAge,@@ -320,7 +321,6 @@ export const identityAccessTokenServiceFactory = ({const issueIdentityAccessToken = async (input: TIssueIdentityAccessTokenInput): Promise<TIssueIdentityAccessTokenOutput> => {- const appCfg = getConfig();const issuedAt = new Date();const period = Number(input.accessTokenPeriod) || 0;@@ -390,12 +390,7 @@ export const identityAccessTokenServiceFactory = ({});if (numUsesLimit > 0) {- await setUsesRemaining(- input.identityId,- identityAccessToken.id,- numUsesLimit,- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );+ await setUsesRemaining(input.identityId, identityAccessToken.id, numUsesLimit, ttl);}return { accessToken, identityAccessToken };@@ -497,7 +492,12 @@ export const identityAccessTokenServiceFactory = ({if (remainingFromState === null) {// Counter was lost (Redis flush). Re-seed from the JWT's numUsesLimit claim// and allow this request; subsequent requests decrement the live counter.- await setUsesRemaining(token.identityId, tokenId, numUsesLimit - 1, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);+ await setUsesRemaining(+ token.identityId,+ tokenId,+ numUsesLimit - 1,+ computeUsesRemainingTtl({ exp: token.exp })+ );} else {const remaining = await keyStore.incrementBy(KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, tokenId),@@ -638,7 +638,7 @@ export const identityAccessTokenServiceFactory = ({// the Redis counter to the current remaining budget.if (numUsesLimit > 0) {const remainingUses = existingRemaining === null ? numUsesLimit : Math.max(0, existingRemaining);- await setUsesRemaining(decodedToken.identityId, tokenId, remainingUses, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);+ await setUsesRemaining(decodedToken.identityId, tokenId, remainingUses, ttl);}return {