Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(identity-access-token): close use-limit gaps from the shorter counter TTL

Scott Wilsonac9f32b20a12
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.ts
index 09e0c8d552..7d1c649129 100644
--- a/backend/e2e-test/mocks/keystore.ts
+++ b/backend/e2e-test/mocks/keystore.ts
@@ -106,6 +106,14 @@ export const mockKeyStore = (): TKeyStoreFactory => {
store[chosen] = String(current + 1);
return bestIdx;
},
+ decrementIfExists: async (key) => {
+ if (typeof store[key] !== "string") {
+ return null;
+ }
+ const next = parseInt(store[key] as string, 10) - 1;
+ store[key] = String(next);
+ return next;
+ },
decrementByOrDelete: async (key) => {
const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
const next = current - 1;
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index c78303d43f..865259eda8 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -355,6 +355,7 @@ export type TKeyStoreFactory = {
incrementBy: (key: string, value: number) => Promise<number>;
incrementByAndRefreshExpiryIfUnderLimit: (key: string, limit: number, expiryInSeconds: number) => Promise<number>;
decrementByOrDelete: (key: string) => Promise<number>;
+ decrementIfExists: (key: string) => Promise<number | null>;
claimLeastLoaded: (keys: string[], baseOccupancies: number[], expiryInSeconds: number) => Promise<number>;
incrementByWithExpiry: (key: string, value: number, expiryInSeconds: number) => Promise<number>;
probeDistinctMember: (key: string, member: string, expiryInSeconds: number) => Promise<boolean>;
@@ -543,6 +544,14 @@ export const keyStoreFactory = (
return redis.call("DECR", KEYS[1])
`;
+ // A plain DECR on a missing key creates it at -1 with no TTL, which then lives forever.
+ const DECREMENT_IF_EXISTS_SCRIPT = `
+ if redis.call("EXISTS", KEYS[1]) == 0 then
+ return false
+ end
+ return redis.call("DECR", KEYS[1])
+ `;
+
const incrementByAndRefreshExpiryIfUnderLimit = async (
key: string,
limit: number,
@@ -563,6 +572,12 @@ export const keyStoreFactory = (
return Number(result);
};
+ // Returns null when the key does not exist, leaving it absent.
+ const decrementIfExists = async (key: string): Promise<number | null> => {
+ const result = await primaryRedis.eval(DECREMENT_IF_EXISTS_SCRIPT, 1, key);
+ return result === null ? null : Number(result);
+ };
+
// Choosing and claiming has to be one round trip. Done as separate read and write calls, every
// concurrent selection reads the same minimum before any of them claims it and they all pile onto
// the same gateway, which is the stampede the reservation exists to prevent.
@@ -883,6 +898,7 @@ export const keyStoreFactory = (
incrementBy,
incrementByAndRefreshExpiryIfUnderLimit,
decrementByOrDelete,
+ decrementIfExists,
claimLeastLoaded,
incrementByWithExpiry,
probeDistinctMember,
diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.ts
index 350c146f33..d490bfc30c 100644
--- a/backend/src/keystore/memory.ts
+++ b/backend/src/keystore/memory.ts
@@ -157,6 +157,14 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {
store[chosen] = String(current + 1);
return bestIdx;
},
+ decrementIfExists: async (key) => {
+ if (typeof store[key] !== "string") {
+ return null;
+ }
+ const next = parseInt(store[key] as string, 10) - 1;
+ store[key] = String(next);
+ return next;
+ },
decrementByOrDelete: async (key) => {
const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;
const next = current - 1;
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.ts
index 80ec6f2842..ba865ec3de 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
@@ -3,11 +3,13 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import {
computeIssuedTtl,
computePerTokenMarkerExpiry,
+ computeReseededUsesRemainingTtl,
computeRevocationVerdictFingerprint,
computeSingleIssuanceTtlCap,
computeTokenAuthRevokeMarkerExpiry,
computeUsesRemainingTtl,
evaluateRevocationMarkers,
+ hasJwtExpired,
hasLegacyTokenWithoutExpExceededMaxAge,
IDENTITY_REVOCATION_MARKER_SKEW_SECONDS,
isMembershipDenyReason
@@ -177,20 +179,45 @@ describe("computeSingleIssuanceTtlCap", () => {
});
describe("computeUsesRemainingTtl", () => {
- test("lives exactly as long as the JWT has left", () => {
- expect(computeUsesRemainingTtl({ exp: NOW + 3600, nowSeconds: NOW })).toBe(3600);
+ test("outlives the JWT by the skew so an in-flight request still finds its counter", () => {
+ expect(computeUsesRemainingTtl(3600)).toBe(3600 + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS);
+ });
+});
+
+describe("computeReseededUsesRemainingTtl", () => {
+ test("lasts until the token's maxTTL budget runs out, covering any renewed JWT", () => {
+ expect(
+ computeReseededUsesRemainingTtl({ accessTokenMaxTTL: 7200, creationEpoch: NOW - 1800, nowSeconds: NOW })
+ ).toBe(5400 + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS);
+ });
+
+ test("falls back to the ceiling when the token has no maxTTL", () => {
+ expect(computeReseededUsesRemainingTtl({ accessTokenMaxTTL: 0, creationEpoch: NOW, nowSeconds: NOW })).toBe(
+ MAX_AGE + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS
+ );
+ });
+
+ test("never exceeds the ceiling even with a larger maxTTL budget", () => {
+ expect(
+ computeReseededUsesRemainingTtl({ accessTokenMaxTTL: MAX_AGE * 2, creationEpoch: NOW, nowSeconds: NOW })
+ ).toBe(MAX_AGE + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS);
});
- test("never outlives the ceiling", () => {
- expect(computeUsesRemainingTtl({ exp: NOW + MAX_AGE + 10_000, nowSeconds: NOW })).toBe(MAX_AGE);
+ test("stays positive once the maxTTL budget is spent", () => {
+ expect(computeReseededUsesRemainingTtl({ accessTokenMaxTTL: 600, creationEpoch: NOW - 900, nowSeconds: NOW })).toBe(
+ 1 + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS
+ );
});
+});
- test("stays positive for a JWT that expires this second", () => {
- expect(computeUsesRemainingTtl({ exp: NOW, nowSeconds: NOW })).toBe(1);
+describe("hasJwtExpired", () => {
+ test("is true from the exp second onward", () => {
+ expect(hasJwtExpired({ exp: NOW, nowSeconds: NOW })).toBe(true);
+ expect(hasJwtExpired({ exp: NOW + 1, nowSeconds: NOW })).toBe(false);
});
- test("falls back to the ceiling for a legacy JWT with no exp", () => {
- expect(computeUsesRemainingTtl({ nowSeconds: NOW })).toBe(MAX_AGE);
+ test("is false for a legacy JWT with no exp", () => {
+ expect(hasJwtExpired({ nowSeconds: NOW })).toBe(false);
});
});
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.ts
index f6d96e1ded..52c110b8af 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,28 +143,44 @@ 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 = ({
+// 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.
+export const IDENTITY_REVOCATION_MARKER_SKEW_SECONDS = 300;
+
+export const hasJwtExpired = ({
exp,
nowSeconds = Math.floor(Date.now() / 1000)
}: {
exp?: number;
nowSeconds?: number;
+}): boolean => typeof exp === "number" && nowSeconds >= exp;
+
+// The uses-remaining counter is read after the JWT is verified, so it has to outlive the JWT by
+// enough to cover a request in flight. A counter that vanishes mid-request reads as lost, and a lost
+// counter is reseeded with a fresh budget.
+export const computeUsesRemainingTtl = (jwtTtlSeconds: number): number =>
+ jwtTtlSeconds + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS;
+
+// A reseed rebuilds the one counter that every JWT for the token id shares (renewal keeps the id), so
+// it has to last until the latest of them could expire, not just the one being presented. No JWT
+// outlives creationEpoch + maxTTL, and none outlives now + ceiling since each is issued no later than
+// now with at most the ceiling.
+export const computeReseededUsesRemainingTtl = ({
+ accessTokenMaxTTL,
+ creationEpoch,
+ nowSeconds = Math.floor(Date.now() / 1000)
+}: {
+ accessTokenMaxTTL: number;
+ creationEpoch: 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);
+ const latestJwtExpiry =
+ accessTokenMaxTTL > 0 ? Math.min(creationEpoch + accessTokenMaxTTL - nowSeconds, ceiling) : ceiling;
+ return computeUsesRemainingTtl(Math.max(latestJwtExpiry, 1));
};
-// 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.
-export const IDENTITY_REVOCATION_MARKER_SKEW_SECONDS = 300;
-
// Longest lifetime (seconds) a single token can be handed out with the
// requested lifetime, but never above the configured maximum. Periodic tokens
// use their period as the lifetime.
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.ts
index 727c193f94..d04270b269 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
@@ -54,7 +54,7 @@ const createService = ({
const keyStore = {
getItem: vi.fn().mockResolvedValue(null),
getItemPrimary: vi.fn(),
- incrementBy: vi.fn(),
+ decrementIfExists: vi.fn(),
setItemWithExpiry: vi.fn(),
setItemWithExpiryNX: vi.fn().mockResolvedValue("OK"),
incrementSeededWithExpiry: vi.fn().mockResolvedValue(1),
@@ -331,14 +331,14 @@ describe("identityAccessTokenServiceFactory", () => {
test("keeps usage counters in Redis", async () => {
const { service, keyStore } = createService();
keyStore.getItem.mockResolvedValue("1");
- keyStore.incrementBy.mockResolvedValue(0);
+ keyStore.decrementIfExists.mockResolvedValue(0);
await expect(
service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3 }), "10.0.0.1")
).resolves.toMatchObject({
identityId: "identity-id"
});
- expect(keyStore.incrementBy).toHaveBeenCalledWith("identity-token-uses-remaining:identity-id:token-id", -1);
+ expect(keyStore.decrementIfExists).toHaveBeenCalledWith("identity-token-uses-remaining:identity-id:token-id");
});
test("reseeds a lost Redis usage counter from JWT claims", async () => {
@@ -352,24 +352,69 @@ describe("identityAccessTokenServiceFactory", () => {
});
expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
"identity-token-uses-remaining:identity-id:token-id",
- 3600,
+ MAX_AGE + MARKER_SKEW_SECONDS,
2
);
- expect(keyStore.incrementBy).not.toHaveBeenCalled();
+ expect(keyStore.decrementIfExists).not.toHaveBeenCalled();
});
- test("reseeds a lost counter for a legacy JWT with no exp using the ceiling", async () => {
+ test("reseeds a lost counter to outlive every renewed JWT, not just the one presented", async () => {
const { service, keyStore } = createService();
keyStore.getItem.mockResolvedValue(null);
- await service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3, exp: undefined }), "10.0.0.1");
+ // The presented JWT has 10 minutes left, but the token's maxTTL budget allows renewed JWTs for
+ // another 90 minutes, and they all share this counter.
+ await service.fnValidateIdentityAccessTokenFast(
+ createTokenClaims({
+ numUsesLimit: 3,
+ exp: NOW_SECONDS + 600,
+ accessTokenTTL: 3600,
+ accessTokenMaxTTL: 7200,
+ creationEpoch: NOW_SECONDS - 1800
+ }),
+ "10.0.0.1"
+ );
expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
"identity-token-uses-remaining:identity-id:token-id",
- MAX_AGE,
+ 5400 + MARKER_SKEW_SECONDS,
2
);
});
+ test("does not reseed a lost counter for a JWT that expired after it was verified", async () => {
+ const { service, keyStore } = createService();
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-token-uses-remaining:")) {
+ vi.setSystemTime(new Date((NOW_SECONDS + 3600) * 1000));
+ }
+ return null;
+ });
+
+ await expect(
+ service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3 }), "10.0.0.1")
+ ).rejects.toThrow("has expired");
+ expect(keyStore.setItemWithExpiry).not.toHaveBeenCalledWith(
+ expect.stringContaining("identity-token-uses-remaining:"),
+ expect.anything(),
+ expect.anything()
+ );
+ });
+
+ test("rejects without recreating a counter that expired between the read and the decrement", async () => {
+ const { service, keyStore } = createService();
+ keyStore.getItem.mockResolvedValue("2");
+ keyStore.decrementIfExists.mockResolvedValue(null);
+
+ await expect(
+ service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3 }), "10.0.0.1")
+ ).rejects.toThrow("could not be recorded");
+ expect(keyStore.setItemWithExpiry).not.toHaveBeenCalledWith(
+ expect.stringContaining("identity-token-uses-remaining:"),
+ expect.anything(),
+ expect.anything()
+ );
+ });
+
test("seeds the usage counter at issuance to expire with the token, not the ceiling", async () => {
const { service, keyStore } = createService();
@@ -390,7 +435,7 @@ describe("identityAccessTokenServiceFactory", () => {
expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
expect.stringMatching(/^identity-token-uses-remaining:identity-id:/),
- 600,
+ 600 + MARKER_SKEW_SECONDS,
1
);
});
@@ -421,11 +466,46 @@ describe("identityAccessTokenServiceFactory", () => {
expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
"identity-token-uses-remaining:identity-id:token-id",
- 3600,
+ 3600 + MARKER_SKEW_SECONDS,
1
);
});
+ test("does not renew with a fresh budget when the JWT expired after it was verified", 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.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-token-uses-remaining:")) {
+ vi.setSystemTime(new Date((NOW_SECONDS + 3600) * 1000));
+ }
+ return null;
+ });
+
+ await expect(service.renewAccessToken({ accessToken })).rejects.toThrow("has expired");
+ expect(keyStore.setItemWithExpiry).not.toHaveBeenCalledWith(
+ expect.stringContaining("identity-token-uses-remaining:"),
+ expect.anything(),
+ expect.anything()
+ );
+ });
+
test("does not require Redis counters for unlimited-use tokens", async () => {
const { service, keyStore } = createService();
@@ -437,7 +517,7 @@ describe("identityAccessTokenServiceFactory", () => {
expect.anything(),
expect.anything()
);
- expect(keyStore.incrementBy).not.toHaveBeenCalled();
+ expect(keyStore.decrementIfExists).not.toHaveBeenCalled();
expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
"identity-trusted-ips:identity-id:universal-auth",
300,
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.ts
index 1b9c545eaf..fcfe86b692 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
@@ -21,10 +21,12 @@ import {
assertRevocableClaims,
computeIssuedTtl,
computePerTokenMarkerExpiry,
+ computeReseededUsesRemainingTtl,
computeRevocationVerdictFingerprint,
computeUsesRemainingTtl,
evaluateRevocationMarkers,
hasFullRenewClaims,
+ hasJwtExpired,
hasLegacyTokenWithoutExpExceededMaxAge,
hasNonWildcardTrustedIps,
isMembershipDenyReason,
@@ -85,7 +87,7 @@ type TIdentityAccessTokenServiceFactoryDep = {
TKeyStoreFactory,
| "getItem"
| "getItemPrimary"
- | "incrementBy"
+ | "decrementIfExists"
| "setItemWithExpiry"
| "setItemWithExpiryNX"
| "incrementSeededWithExpiry"
@@ -390,7 +392,7 @@ export const identityAccessTokenServiceFactory = ({
});
if (numUsesLimit > 0) {
- await setUsesRemaining(input.identityId, identityAccessToken.id, numUsesLimit, ttl);
+ await setUsesRemaining(input.identityId, identityAccessToken.id, numUsesLimit, computeUsesRemainingTtl(ttl));
}
return { accessToken, identityAccessToken };
@@ -492,17 +494,31 @@ 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.
+ // The JWT was verified before the read, so recheck it: a token that expired in
+ // between must not be handed a fresh budget.
+ if (hasJwtExpired({ exp: token.exp })) {
+ throw new UnauthorizedError({
+ message: "Failed to authorize: identity access token has expired, please re-authenticate"
+ });
+ }
await setUsesRemaining(
token.identityId,
tokenId,
numUsesLimit - 1,
- computeUsesRemainingTtl({ exp: token.exp })
+ computeReseededUsesRemainingTtl({
+ accessTokenMaxTTL: source.accessTokenMaxTTL,
+ creationEpoch: source.creationEpoch
+ })
);
} else {
- const remaining = await keyStore.incrementBy(
- KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, tokenId),
- -1
+ const remaining = await keyStore.decrementIfExists(
+ KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, tokenId)
);
+ if (remaining === null) {
+ throw new UnauthorizedError({
+ message: "Failed to authorize: token usage could not be recorded, please retry the request"
+ });
+ }
if (remaining < 0) {
throw new UnauthorizedError({ message: "Failed to authorize: token usage limit reached" });
}
@@ -613,6 +629,9 @@ export const identityAccessTokenServiceFactory = ({
}
const numUsesLimit = decodedToken.numUsesLimit ?? source.numUsesLimit;
+ if (numUsesLimit > 0 && existingRemaining === null && hasJwtExpired({ exp: decodedToken.exp, nowSeconds })) {
+ throw new UnauthorizedError({ message: "Cannot renew: identity access token has expired" });
+ }
const ipRestrictionEnabled = Boolean(decodedToken.ipRestrictionEnabled);
const { accessToken: renewedToken } = signIdentityAccessToken({
@@ -638,7 +657,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, ttl);
+ await setUsesRemaining(decodedToken.identityId, tokenId, remainingUses, computeUsesRemainingTtl(ttl));
}
return {