Skip to content

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

Implement identity revocation versioning and enhance revocation marker handling

Victor Hugo dos Santos5122f64d846d
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.ts
index 4501838cab..16bad4cf72 100644
--- a/backend/e2e-test/mocks/keystore.ts
+++ b/backend/e2e-test/mocks/keystore.ts
@@ -79,6 +79,17 @@ export const mockKeyStore = (): TKeyStoreFactory => {
store[key] = String(next);
return next;
},
+ incrementSeededWithExpiry: async (key, seed) => {
+ const existing = store[key];
+ if (existing === undefined) {
+ const seeded = 1 + seed;
+ store[key] = String(seeded);
+ return seeded;
+ }
+ const next = (typeof existing === "string" ? parseInt(existing, 10) : 0) + 1;
+ store[key] = String(next);
+ return next;
+ },
pgGetIntItem: async (key) => {
const value = store[key];
if (typeof value === "number") {
diff --git a/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts b/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts
index 72acb55297..12c6badc56 100644
--- a/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts
+++ b/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts
@@ -441,8 +441,12 @@ describe("Identity Access Token — redesigned JWT flow", () => {
const revocation = await waitForRevocationRow(decoded!.identityAccessTokenId);
const expectedExpiresAtMs = decoded!.exp * 1000;
+ // maxTTL=0/TTL=0 keeps a ~90d marker; it must cover the JWT exp and lands at
+ // exp plus the skew buffer.
+ const markerSkewMs = 300 * 1000;
expect(revocation.expiresAt.getTime()).toBeGreaterThan(Date.now());
- expect(Math.abs(revocation.expiresAt.getTime() - expectedExpiresAtMs)).toBeLessThanOrEqual(2_000);
+ expect(revocation.expiresAt.getTime()).toBeGreaterThanOrEqual(expectedExpiresAtMs - 2_000);
+ expect(revocation.expiresAt.getTime()).toBeLessThanOrEqual(expectedExpiresAtMs + markerSkewMs + 2_000);
await testRedis.flushdb("SYNC");
@@ -451,4 +455,37 @@ describe("Identity Access Token — redesigned JWT flow", () => {
await cleanupIdentityDirect(identityId);
}
});
+
+ // -------------------------------------------------------------------------
+ // 9. Version-counter churn from revokes doesn't wedge freshly issued tokens
+ // -------------------------------------------------------------------------
+ test("revoking a token invalidates it but a re-login still authenticates", async () => {
+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-version-churn");
+
+ try {
+ const tokenA = await loginWithUa(clientId, clientSecret);
+
+ // Two calls: the second exercises a warmed verdict cache for tokenA.
+ expect((await callDetailsEndpoint(tokenA)).statusCode).toBe(200);
+ expect((await callDetailsEndpoint(tokenA)).statusCode).toBe(200);
+
+ // Revoke bumps the per-identity version, so the cached allow for tokenA
+ // no longer matches and it is rejected.
+ const revokeRes = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/auth/token/revoke",
+ body: { accessToken: tokenA }
+ });
+ expect(revokeRes.statusCode).toBe(200);
+ expect((await callDetailsEndpoint(tokenA)).statusCode).toBe(401);
+
+ // A freshly issued token for the same identity is a new tuple, so the
+ // version churn must not wedge it.
+ const tokenB = await loginWithUa(clientId, clientSecret);
+ expect((await callDetailsEndpoint(tokenB)).statusCode).toBe(200);
+ expect((await callDetailsEndpoint(tokenB)).statusCode).toBe(200);
+ } finally {
+ await deleteIdentity(identityId);
+ }
+ });
});
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a7030f2c9b..3abb0573e7 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -69,6 +69,9 @@ export const KeyStorePrefixes = {
`identity-access-token-status:${identityAccessTokenId}`,
IdentityTokenUsesRemaining: (identityId: string, jti: string) =>
`identity-token-uses-remaining:${identityId}:${jti}` as const,
+ IdentityRevocationVersion: (identityId: string) => `identity-revocation-version:${identityId}` as const,
+ IdentityRevocationVerdict: (identityId: string, fingerprint: string) =>
+ `identity-revocation-verdict:${identityId}:${fingerprint}` as const,
IdentityUaClientSecretUsageDebounce: (clientSecretId: string) =>
`identity-ua-client-secret-usage-debounce:${clientSecretId}` as const,
ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`,
@@ -156,6 +159,9 @@ export const KeyStoreTtls = {
SetSyncSecretIntegrationLastRunTimestampInSeconds: 60,
SetSecretSyncLastRunTimestampInSeconds: 60,
AccessTokenStatusUpdateInSeconds: 120,
+ IdentityRevocationVerdictBaseInSeconds: 600, // 10 minutes
+ IdentityRevocationVerdictJitterInSeconds: 120, // +/- 2 minutes
+ IdentityRevocationVersionInSeconds: 604800, // 7 days
ProjectPermissionMarkerTtlSeconds: 10, // 10 seconds - short-lived marker for fingerprint validation
ProjectPermissionDataTtlSeconds: 600, // 10 minutes - longer-lived data payload
MfaSessionInSeconds: 300, // 5 minutes
@@ -230,6 +236,7 @@ export type TKeyStoreFactory = {
incrementByAndRefreshExpiryIfUnderLimit: (key: string, limit: number, expiryInSeconds: number) => Promise<number>;
decrementByOrDelete: (key: string) => Promise<number>;
incrementByWithExpiry: (key: string, value: number, expiryInSeconds: number) => Promise<number>;
+ incrementSeededWithExpiry: (key: string, seed: number, expiryInSeconds: number) => Promise<number>;
getKeysByPattern: (pattern: string, limit?: number) => Promise<string[]>;
// list operations
listPush: (key: string, value: string) => Promise<number>;
@@ -412,6 +419,24 @@ export const keyStoreFactory = (
return result as number;
};
+ // Timestamp-seeded INCR. When the key is missing (INCR returns 1) it rebases
+ // the counter by `seed` (a caller-supplied Date.now()), so a resurrected key
+ // restarts above any value it held before and a stale cached allow stamped
+ // with an old version can never match again.
+ const INCREMENT_SEEDED_WITH_EXPIRY = `
+ local v = redis.call('INCR', KEYS[1])
+ if v == 1 then
+ v = redis.call('INCRBY', KEYS[1], ARGV[1])
+ end
+ redis.call('EXPIRE', KEYS[1], ARGV[2])
+ return v
+ `;
+
+ const incrementSeededWithExpiry = async (key: string, seed: number, expiryInSeconds: number): Promise<number> => {
+ const result = await primaryRedis.eval(INCREMENT_SEEDED_WITH_EXPIRY, 1, key, String(seed), String(expiryInSeconds));
+ return Number(result);
+ };
+
const setExpiry = async (key: string, expiryInSeconds: number) => primaryRedis.expire(key, expiryInSeconds);
const ttl = async (key: string) => primaryRedis.ttl(key);
@@ -544,6 +569,7 @@ export const keyStoreFactory = (
incrementByAndRefreshExpiryIfUnderLimit,
decrementByOrDelete,
incrementByWithExpiry,
+ incrementSeededWithExpiry,
acquireLock(resources: string[], duration: number, settings?: Partial<Settings>) {
return redisLock.acquire(resources, duration, settings);
},
diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.ts
index 6448fc26ea..31f4f08f7d 100644
--- a/backend/src/keystore/memory.ts
+++ b/backend/src/keystore/memory.ts
@@ -97,6 +97,17 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {
store[key] = String(next);
return next;
},
+ incrementSeededWithExpiry: async (key, seed) => {
+ const existing = store[key];
+ if (existing === undefined) {
+ const seeded = 1 + seed;
+ store[key] = String(seeded);
+ return seeded;
+ }
+ const next = (typeof existing === "string" ? parseInt(existing, 10) : 0) + 1;
+ store[key] = String(next);
+ return next;
+ },
acquireLock: () => {
return Promise.resolve({
release: () => {}
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 4b5d5aec53..9fe7a402ff 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
@@ -1,6 +1,15 @@
import { afterEach, describe, expect, test, vi } from "vitest";
-import { computeIssuedTtl, hasLegacyTokenWithoutExpExceededMaxAge } from "./identity-access-token-fns";
+import {
+ computeIssuedTtl,
+ computePerTokenMarkerExpiry,
+ computeRevocationVerdictFingerprint,
+ computeSingleIssuanceTtlCap,
+ computeTokenAuthRevokeMarkerExpiry,
+ evaluateRevocationMarkers,
+ hasLegacyTokenWithoutExpExceededMaxAge,
+ IDENTITY_REVOCATION_MARKER_SKEW_SECONDS
+} from "./identity-access-token-fns";
const MAX_AGE = 7_776_000;
const NOW = 1_700_000_000;
@@ -146,3 +155,176 @@ describe("hasLegacyTokenWithoutExpExceededMaxAge", () => {
).toBe(true);
});
});
+
+describe("computeSingleIssuanceTtlCap", () => {
+ test("returns the requested TTL when below the ceiling", () => {
+ expect(computeSingleIssuanceTtlCap({ requestedTTL: 3600, accessTokenPeriod: 0 })).toBe(3600);
+ });
+
+ test("caps the requested TTL at the ceiling", () => {
+ expect(computeSingleIssuanceTtlCap({ requestedTTL: MAX_AGE + 10_000, accessTokenPeriod: 0 })).toBe(MAX_AGE);
+ });
+
+ test("falls back to the ceiling when TTL is unset (the true worst case)", () => {
+ expect(computeSingleIssuanceTtlCap({ requestedTTL: 0, accessTokenPeriod: 0 })).toBe(MAX_AGE);
+ });
+
+ test("periodic mode uses period as the effective TTL", () => {
+ expect(computeSingleIssuanceTtlCap({ requestedTTL: 0, accessTokenPeriod: 900 })).toBe(900);
+ });
+});
+
+describe("computePerTokenMarkerExpiry", () => {
+ test("tightens a short-TTL / large-maxTTL token to exp + one issuance TTL + skew", () => {
+ const twoHours = 7200;
+ const thirtyDays = 2_592_000;
+ const exp = NOW + twoHours;
+ const result = computePerTokenMarkerExpiry({
+ exp,
+ requestedTTL: twoHours,
+ accessTokenMaxTTL: thirtyDays,
+ accessTokenPeriod: 0,
+ creationEpoch: NOW,
+ nowSeconds: NOW
+ });
+ // min(exp + 2h, creationEpoch + 30d) = exp + 2h; plus skew.
+ expect(result).toEqual(new Date((exp + twoHours + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000));
+ });
+
+ test("clamps to the legacy creationEpoch+maxTTL upper bound plus skew", () => {
+ const oneHour = 3600;
+ const exp = NOW + oneHour;
+ const result = computePerTokenMarkerExpiry({
+ exp,
+ // A huge requested TTL would push exp+cap past the maxTTL budget; the clamp wins.
+ requestedTTL: MAX_AGE,
+ accessTokenMaxTTL: oneHour + 60,
+ accessTokenPeriod: 0,
+ creationEpoch: NOW,
+ nowSeconds: NOW
+ });
+ expect(result).toEqual(new Date((NOW + oneHour + 60 + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000));
+ });
+
+ test("keeps the ~90d marker for maxTTL=0/TTL=0 tokens (irreducible)", () => {
+ const exp = NOW + MAX_AGE;
+ const result = computePerTokenMarkerExpiry({
+ exp,
+ requestedTTL: 0,
+ accessTokenMaxTTL: 0,
+ accessTokenPeriod: 0,
+ creationEpoch: NOW,
+ nowSeconds: NOW
+ });
+ // min(exp + ceiling, now + ceiling) = now + ceiling; plus skew.
+ expect(result).toEqual(new Date((NOW + MAX_AGE + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000));
+ });
+
+ test("falls back to the legacy bound (no skew) when exp is absent", () => {
+ const result = computePerTokenMarkerExpiry({
+ exp: undefined,
+ requestedTTL: 3600,
+ accessTokenMaxTTL: 7200,
+ accessTokenPeriod: 0,
+ creationEpoch: NOW,
+ nowSeconds: NOW
+ });
+ expect(result).toEqual(new Date((NOW + 7200) * 1000));
+ });
+});
+
+describe("computeTokenAuthRevokeMarkerExpiry", () => {
+ test("anchors on now + single-issuance cap when maxTTL=0", () => {
+ const result = computeTokenAuthRevokeMarkerExpiry({
+ accessTokenTTL: 3600,
+ accessTokenMaxTTL: 0,
+ accessTokenPeriod: 0,
+ createdAtMs: (NOW - 100) * 1000,
+ nowSeconds: NOW
+ });
+ expect(result).toEqual(new Date((NOW + 3600 + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000));
+ });
+
+ test("clamps to createdAt+maxTTL when that is sooner than now + cap", () => {
+ const createdAt = NOW - 1000;
+ const result = computeTokenAuthRevokeMarkerExpiry({
+ accessTokenTTL: MAX_AGE,
+ accessTokenMaxTTL: 2000,
+ accessTokenPeriod: 0,
+ createdAtMs: createdAt * 1000,
+ nowSeconds: NOW
+ });
+ // min(createdAt + 2000, now + MAX_AGE) = createdAt + 2000; plus skew.
+ expect(result).toEqual(new Date((createdAt + 2000 + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000));
+ });
+});
+
+describe("computeRevocationVerdictFingerprint", () => {
+ test("is stable for the same tuple and differs when iat changes", () => {
+ const base = { tokenId: "t1", issuedAtMs: 1000, clientSecretId: "cs", authMethod: "universal-auth" };
+ expect(computeRevocationVerdictFingerprint(base)).toBe(computeRevocationVerdictFingerprint({ ...base }));
+ // A renewed JWT reuses the jti (tokenId) but carries a fresh iat.
+ expect(computeRevocationVerdictFingerprint(base)).not.toBe(
+ computeRevocationVerdictFingerprint({ ...base, issuedAtMs: 2000 })
+ );
+ });
+
+ test("differs across token id, client secret, and auth method", () => {
+ const base = { tokenId: "t1", issuedAtMs: 1000, clientSecretId: "cs", authMethod: "universal-auth" };
+ expect(computeRevocationVerdictFingerprint(base)).not.toBe(
+ computeRevocationVerdictFingerprint({ ...base, tokenId: "t2" })
+ );
+ expect(computeRevocationVerdictFingerprint(base)).not.toBe(
+ computeRevocationVerdictFingerprint({ ...base, clientSecretId: "cs2" })
+ );
+ expect(computeRevocationVerdictFingerprint(base)).not.toBe(
+ computeRevocationVerdictFingerprint({ ...base, authMethod: "oidc-auth" })
+ );
+ });
+});
+
+describe("evaluateRevocationMarkers", () => {
+ const base = {
+ tokenId: "token-id",
+ identityId: "identity-id",
+ issuedAtMs: NOW * 1000,
+ clientSecretId: "cs-id",
+ authMethod: "universal-auth"
+ };
+
+ test("returns null when no marker matches", () => {
+ expect(evaluateRevocationMarkers({ ...base, markers: [] })).toBeNull();
+ });
+
+ test("denies a per-token marker matching the token id", () => {
+ expect(
+ evaluateRevocationMarkers({
+ ...base,
+ markers: [{ id: "token-id", identityId: "identity-id", createdAt: new Date(NOW * 1000), scope: null }]
+ })
+ ).toBe("token");
+ });
+
+ test("denies an identity-wide marker only for tokens issued before revokedAt", () => {
+ const revokedAfter = { id: "identity-id", identityId: "identity-id", createdAt: new Date((NOW + 10) * 1000) };
+ const revokedBefore = { id: "identity-id", identityId: "identity-id", createdAt: new Date((NOW - 10) * 1000) };
+ expect(evaluateRevocationMarkers({ ...base, markers: [{ ...revokedAfter, scope: null }] })).toBe("identity");
+ expect(evaluateRevocationMarkers({ ...base, markers: [{ ...revokedBefore, scope: null }] })).toBeNull();
+ });
+
+ test("denies scoped markers by client secret and auth method", () => {
+ const revokedAt = new Date((NOW + 10) * 1000);
+ expect(
+ evaluateRevocationMarkers({
+ ...base,
+ markers: [{ id: "uuid", identityId: "identity-id", createdAt: revokedAt, revokedAt, scope: "cs-id" }]
+ })
+ ).toBe("client-secret");
+ expect(
+ evaluateRevocationMarkers({
+ ...base,
+ markers: [{ id: "uuid", identityId: "identity-id", createdAt: revokedAt, revokedAt, scope: "universal-auth" }]
+ })
+ ).toBe("auth-method");
+ });
+});
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 a38f9b857d..51afc1a513 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
@@ -1,5 +1,6 @@
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
+import { generateCacheKeyFromData } from "@app/lib/crypto/cache";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { TIp } from "@app/lib/ip";
@@ -11,6 +12,8 @@ import {
TMinimalRenewClaims,
TRenewableClaims,
TRevocableClaims,
+ TRevocationDenyReason,
+ TRevocationMarker,
TSignIdentityAccessTokenInput,
TSignIdentityAccessTokenOutput
} from "./identity-access-token-types";
@@ -140,6 +143,178 @@ export const computeIssuedTtl = ({
return Math.min(requestedCap, remainingBudget, 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.
+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.
+export const computeSingleIssuanceTtlCap = ({
+ requestedTTL,
+ accessTokenPeriod
+}: {
+ requestedTTL: number;
+ accessTokenPeriod: number;
+}): number => {
+ const { MAX_MACHINE_IDENTITY_TOKEN_AGE: ceiling } = getConfig();
+ const effectiveRequested = accessTokenPeriod > 0 ? accessTokenPeriod : requestedTTL;
+ if (effectiveRequested > 0) {
+ return Math.min(effectiveRequested, ceiling);
+ }
+ return ceiling;
+};
+
+// Latest time an old-style token (one with no built-in expiry) could still be
+// accepted. Used as the fallback record expiry when the token carries no expiry.
+const computeLegacyMarkerUpperSeconds = ({
+ accessTokenMaxTTL,
+ creationEpoch,
+ nowSeconds
+}: {
+ accessTokenMaxTTL: number;
+ creationEpoch: number;
+ nowSeconds: number;
+}): number => {
+ const { MAX_MACHINE_IDENTITY_TOKEN_AGE: ceiling } = getConfig();
+ return accessTokenMaxTTL > 0 ? creationEpoch + accessTokenMaxTTL : nowSeconds + ceiling;
+};
+
+// When a token revokes itself, decide how long to keep its revocation record.
+// Keep it until just after the token would have expired on its own, plus one
+// extra lifetime to catch a renewal that slips in during replica lag, plus the
+// skew buffer. If the token has no expiry, fall back to the old-style
+// latest-valid time.
+export const computePerTokenMarkerExpiry = ({
+ exp,
+ requestedTTL,
+ accessTokenMaxTTL,
+ accessTokenPeriod,
+ creationEpoch,
+ nowSeconds = Math.floor(Date.now() / 1000)
+}: {
+ exp?: number;
+ requestedTTL: number;
+ accessTokenMaxTTL: number;
+ accessTokenPeriod: number;
+ creationEpoch: number;
+ nowSeconds?: number;
+}): Date => {
+ const legacyUpperSeconds = computeLegacyMarkerUpperSeconds({ accessTokenMaxTTL, creationEpoch, nowSeconds });
+
+ if (typeof exp !== "number") {
+ return new Date(legacyUpperSeconds * 1000);
+ }
+
+ const singleIssuanceTtlCap = computeSingleIssuanceTtlCap({ requestedTTL, accessTokenPeriod });
+ const tightenedSeconds = Math.min(exp + singleIssuanceTtlCap, legacyUpperSeconds);
+ return new Date((tightenedSeconds + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000);
+};
+
+// Same idea, but for an admin revoking a token by id with no token in hand.
+// Since we can't read the token's own expiry, keep the record for one full
+// token lifetime from now, capped at the token's overall lifetime limit, plus
+// the skew buffer. The stored token lifetime never changes, so it safely covers
+// any future renewal.
+export const computeTokenAuthRevokeMarkerExpiry = ({
+ accessTokenTTL,
+ accessTokenMaxTTL,
+ accessTokenPeriod,
+ createdAtMs,
+ nowSeconds = Math.floor(Date.now() / 1000)
+}: {
+ accessTokenTTL: number;
+ accessTokenMaxTTL: number;
+ accessTokenPeriod: number;
+ createdAtMs: number;
+ nowSeconds?: number;
+}): Date => {
+ const createdAtSeconds = Math.floor(createdAtMs / 1000);
+ const singleIssuanceTtlCap = computeSingleIssuanceTtlCap({ requestedTTL: accessTokenTTL, accessTokenPeriod });
+ const nowPlusCap = nowSeconds + singleIssuanceTtlCap;
+ const tightenedSeconds =
+ accessTokenMaxTTL > 0 ? Math.min(createdAtSeconds + accessTokenMaxTTL, nowPlusCap) : nowPlusCap;
+ return new Date((tightenedSeconds + IDENTITY_REVOCATION_MARKER_SKEW_SECONDS) * 1000);
+};
+
+export const computeRevocationVerdictFingerprint = ({
+ tokenId,
+ issuedAtMs,
+ clientSecretId,
+ authMethod
+}: {
+ tokenId: string;
+ issuedAtMs: number;
+ clientSecretId?: string;
+ authMethod?: string;
+}): string => generateCacheKeyFromData([tokenId, issuedAtMs, clientSecretId ?? "", authMethod ?? ""]);
+
+// Checks a token against its revocation records and returns why it's blocked,
+// or null if it's still valid. Has no side effects, so the cached path and the
+// direct-database path always agree.
+export const evaluateRevocationMarkers = ({
+ markers,
+ tokenId,
+ identityId,
+ issuedAtMs,
+ clientSecretId,
+ authMethod
+}: {
+ markers: TRevocationMarker[];
+ tokenId: string;
+ identityId: string;
+ issuedAtMs: number;
+ clientSecretId?: string;
+ authMethod?: string;
+}): TRevocationDenyReason | null => {
+ for (const revocation of markers) {
+ // A record with no scope either targets this exact token, or (when the whole
+ // identity was revoked) blocks every token issued before the revocation.
+ if (revocation.scope === null || revocation.scope === undefined) {
+ if (revocation.id === tokenId) {
+ return "token";
+ }
+ if (revocation.id === identityId) {
+ const revokedAtMs = (revocation.revokedAt ?? revocation.createdAt).getTime();
+ if (issuedAtMs < revokedAtMs) {
+ return "identity";
+ }
+ }
+ } else {
+ // A scoped record blocks every token issued before the revocation whose
+ // client secret or login method matches the scope.
+ const revokedAtMs = (revocation.revokedAt ?? revocation.createdAt).getTime();
+ if (issuedAtMs < revokedAtMs) {
+ if (clientSecretId && revocation.scope === clientSecretId) {
+ return "client-secret";
+ }
+ if (authMethod && revocation.scope === authMethod) {
+ return "auth-method";
+ }
+ }
+ }
+ }
+ return null;
+};
+
+export const revocationDenyReasonToMessage = (
+ reason: TRevocationDenyReason,
+ messagePrefix: "Failed to authorize" | "Cannot renew"
+): string => {
+ switch (reason) {
+ case "token":
+ return `${messagePrefix}: token has been revoked`;
+ case "identity":
+ return `${messagePrefix}: identity tokens have been revoked`;
+ case "client-secret":
+ return `${messagePrefix}: client secret has been revoked`;
+ case "auth-method":
+ default:
+ return `${messagePrefix}: auth method has been revoked`;
+ }
+};
+
export const signIdentityAccessToken = (input: TSignIdentityAccessTokenInput): TSignIdentityAccessTokenOutput => {
const appCfg = getConfig();
const jti = input.identityAccessTokenId;
diff --git a/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
index 41e46ab23c..0386b7f130 100644
--- a/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
@@ -53,22 +53,29 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
scopes: string[];
}): Promise<TRevocationRow[]> => {
try {
- return (
- (await db
- .replicaNode()(TableName.IdentityAccessTokenRevocation)
+ // Equality-only UNION ALL arms so each serves from its own index (id arm
+ // from the PK, scope arm from the partial (identityId, scope) index)
+ // instead of scanning (identityId, expiresAt) across a high-volume
+ // identity's markers. Arms are disjoint and the caller tolerates duplicates, so no
+ // dedup is needed. Reads the primary because this runs on a cache miss or
+ // Redis fail-open, where a lagging replica could return a stale result.
+ const idArm = db(TableName.IdentityAccessTokenRevocation)
+ .select("id", "identityId", "revokedAt", "createdAt", "scope")
+ .where("identityId", identityId)
+ .where("expiresAt", ">", db.fn.now())
+ .whereIn("id", [tokenId, identityId]);
+
+ if (scopes.length > 0) {
+ const scopeArm = db(TableName.IdentityAccessTokenRevocation)
.select("id", "identityId", "revokedAt", "createdAt", "scope")
- .where("expiresAt", ">", db.fn.now())
.where("identityId", identityId)
- // Both halves of the OR must be equality predicates so the planner can
- // serve `id IN (...)` from the PK and the `scope IN (...)` filter stays
- // selective. `scope IS NOT NULL` would force a non-sargable scan.
- .andWhere((qb) => {
- void qb.whereIn("id", [tokenId, identityId]);
- if (scopes.length > 0) {
- void qb.orWhereIn("scope", scopes);
- }
- })) as TRevocationRow[]
- );
+ .where("expiresAt", ">", db.fn.now())
+ .whereIn("scope", scopes);
+
+ void idArm.unionAll([scopeArm]);
+ }
+
+ return (await idArm) as TRevocationRow[];
} catch (error) {
throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationFindActiveForToken" });
}
@@ -79,8 +86,9 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
let deletedRevocationIds: { id: string }[] = [];
let numberOfRetryOnFailure = 0;
let isRetrying = false;
+ let totalDeletedCount = 0;
- logger.info(`daily-resource-cleanup: remove expired identity access token revocations started`);
+ logger.info(`resource-cleanup: remove expired identity access token revocations started`);
do {
try {
// eslint-disable-next-line no-await-in-loop
@@ -103,6 +111,7 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
});
numberOfRetryOnFailure = 0;
+ totalDeletedCount += deletedRevocationIds.length;
} catch (error) {
numberOfRetryOnFailure += 1;
deletedRevocationIds = [];
@@ -118,12 +127,15 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
if (numberOfRetryOnFailure >= MAX_RETRY_ON_FAILURE) {
logger.error(
- `daily-resource-cleanup: remove expired identity access token revocations completed with persistent errors after ${MAX_RETRY_ON_FAILURE} retries. Some revocations might not have been pruned.`
+ `resource-cleanup: remove expired identity access token revocations completed with persistent errors after ${MAX_RETRY_ON_FAILURE} retries. Deleted ${totalDeletedCount} revocations; some might not have been pruned.`
);
- return;
+ return totalDeletedCount;
}
- logger.info(`daily-resource-cleanup: remove expired identity access token revocations completed`);
+ logger.info(
+ `resource-cleanup: remove expired identity access token revocations completed. Deleted ${totalDeletedCount} revocations.`
+ );
+ return totalDeletedCount;
};
return {
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 87c6e23096..d08f50601d 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
@@ -13,6 +13,8 @@ const MAX_AGE = 7_776_000;
const AUTH_SECRET = "test-auth-secret";
const NOW_SECONDS = 1_700_000_000;
const ENFORCED_AT = new Date("2026-05-04T00:00:00.000Z");
+// Mirror IDENTITY_REVOCATION_MARKER_SKEW_SECONDS from identity-access-token-fns.
+const MARKER_SKEW_SECONDS = 300;
vi.mock("@app/lib/config/env", () => ({
getConfig: () => ({
@@ -25,6 +27,7 @@ vi.mock("@app/lib/config/env", () => ({
vi.mock("@app/lib/logger", () => ({
logger: {
info: vi.fn(),
+ warn: vi.fn(),
error: vi.fn()
}
}));
@@ -51,7 +54,9 @@ const createService = ({
const keyStore = {
getItem: vi.fn().mockResolvedValue(null),
incrementBy: vi.fn(),
- setItemWithExpiry: vi.fn()
+ setItemWithExpiry: vi.fn(),
+ setItemWithExpiryNX: vi.fn().mockResolvedValue("OK"),
+ incrementSeededWithExpiry: vi.fn().mockResolvedValue(1)
};
const identityAccessTokenRevocationDAL = {
findActiveRevocationsForToken: vi.fn().mockResolvedValue(activeRevocations),
@@ -210,10 +215,11 @@ describe("identityAccessTokenServiceFactory", () => {
await service.revokeAccessToken(accessToken);
+ // maxTTL=0/TTL=0: irreducible ~90d marker (now + ceiling), plus the skew buffer.
expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({
id: "token-id",
identityId: "identity-id",
- expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)
+ expiresAt: new Date((NOW_SECONDS + MAX_AGE + MARKER_SKEW_SECONDS) * 1000)
});
});
@@ -238,11 +244,12 @@ describe("identityAccessTokenServiceFactory", () => {
await service.revokeAccessToken(legacyToken);
- // Legacy row has accessTokenMaxTTL: 7200, createdAt: NOW_SECONDS
+ // Legacy row has accessTokenMaxTTL: 7200, createdAt: NOW_SECONDS. The marker
+ // is clamped to creationEpoch+maxTTL (the legacy upper bound) plus the skew.
expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({
id: "legacy-token-id",
identityId: "identity-id",
- expiresAt: new Date((NOW_SECONDS + 7200) * 1000)
+ expiresAt: new Date((NOW_SECONDS + 7200 + MARKER_SKEW_SECONDS) * 1000)
});
});
@@ -651,4 +658,150 @@ describe("identityAccessTokenServiceFactory", () => {
"membership is inactive"
);
});
+
+ test("tightens the per-token marker to the JWT exp plus one issuance TTL and skew", async () => {
+ // TTL=2h, maxTTL=30d: marker should self-drain ~2h after exp, not in 30d.
+ const twoHours = 7200;
+ const thirtyDays = 2_592_000;
+ 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: 0,
+ ipRestrictionEnabled: false,
+ ttlSeconds: twoHours,
+ accessTokenTTL: twoHours,
+ accessTokenMaxTTL: thirtyDays,
+ accessTokenPeriod: 0,
+ creationEpoch: NOW_SECONDS,
+ identityAuth: {}
+ });
+ const { service, identityAccessTokenRevocationDAL } = createService();
+
+ await service.revokeAccessToken(accessToken);
+
+ // exp = NOW + 2h; cap = min(2h, ceiling) = 2h; clamped by creationEpoch+maxTTL
+ // (NOW + 30d) → exp + 2h wins; plus skew.
+ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({
+ id: "token-id",
+ identityId: "identity-id",
+ expiresAt: new Date((NOW_SECONDS + twoHours + twoHours + MARKER_SKEW_SECONDS) * 1000)
+ });
+ });
+
+ test("bumps the identity revocation version after inserting the marker on revoke", 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: 0,
+ ipRestrictionEnabled: false,
+ ttlSeconds: 3600,
+ accessTokenTTL: 3600,
+ accessTokenMaxTTL: 7200,
+ accessTokenPeriod: 0,
+ creationEpoch: NOW_SECONDS,
+ identityAuth: {}
+ });
+ const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+
+ await service.revokeAccessToken(accessToken);
+
+ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledTimes(1);
+ expect(keyStore.incrementSeededWithExpiry).toHaveBeenCalledWith(
+ "identity-revocation-version:identity-id",
+ expect.any(Number),
+ expect.any(Number)
+ );
+ });
+
+ test("bumps the identity revocation version on identity-wide revoke", async () => {
+ const { service, keyStore } = createService();
+
+ await service.revokeAllTokensForIdentity("identity-id");
+
+ expect(keyStore.incrementSeededWithExpiry).toHaveBeenCalledWith(
+ "identity-revocation-version:identity-id",
+ expect.any(Number),
+ expect.any(Number)
+ );
+ });
+
+ test("serves a cached allow verdict without hitting the revocation DAL", async () => {
+ const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "5";
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ v: 5 });
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).resolves.toMatchObject({
+ identityId: "identity-id"
+ });
+ expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).not.toHaveBeenCalled();
+ });
+
+ test("serves a cached deny verdict without hitting the revocation DAL", async () => {
+ const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "5";
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ deny: "token" });
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(
+ "token has been revoked"
+ );
+ expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).not.toHaveBeenCalled();
+ });
+
+ test("re-queries the primary when the cached allow version is stale", async () => {
+ const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+ // Live version advanced past the version the cached allow was stamped with.
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "6";
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ v: 5 });
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).resolves.toMatchObject({
+ identityId: "identity-id"
+ });
+ expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).toHaveBeenCalledTimes(1);
+ // Re-stamp the allow with the current live version.
+ expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
+ expect.stringContaining("identity-revocation-verdict:identity-id:"),
+ expect.any(Number),
+ JSON.stringify({ v: 6 })
+ );
+ });
+
+ test("fails open to a direct primary query when the verdict cache read errors", async () => {
+ const { service, keyStore, identityAccessTokenRevocationDAL } = createService({
+ activeRevocations: [{ id: "token-id", identityId: "identity-id", createdAt: new Date(NOW_SECONDS * 1000) }]
+ });
+ // Only the revocation cache reads fail; the uses-remaining read still resolves
+ // so we isolate the revocation-check fail-open behaviour.
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-")) {
+ throw new Error("redis down");
+ }
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(
+ "token has been revoked"
+ );
+ expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).toHaveBeenCalled();
+ });
});
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 864b9a108b..97cacf78da 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
@@ -1,11 +1,13 @@
import { Knex } from "knex";
import { IdentityAuthMethod, OrgMembershipStatus, TableName, TIdentityAccessTokens } from "@app/db/schemas";
-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
+import { applyJitter } from "@app/lib/dates";
import { UnauthorizedError } from "@app/lib/errors";
import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip";
+import { logger } from "@app/lib/logger";
import { recordTokenRenewalMetric } from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
@@ -16,11 +18,15 @@ import {
assertMinimalRenewClaims,
assertRevocableClaims,
computeIssuedTtl,
+ computePerTokenMarkerExpiry,
+ computeRevocationVerdictFingerprint,
+ evaluateRevocationMarkers,
hasFullRenewClaims,
hasLegacyTokenWithoutExpExceededMaxAge,
hasNonWildcardTrustedIps,
parseUsesRemaining,
resolveTtlInputs,
+ revocationDenyReasonToMessage,
signIdentityAccessToken,
verifyAccessTokenJwt
} from "./identity-access-token-fns";
@@ -32,7 +38,8 @@ import {
TMinimalRenewClaims,
TOidcAuthDetails,
TRenewAccessTokenDTO,
- TRenewSource
+ TRenewSource,
+ TRevocationDenyReason
} from "./identity-access-token-types";
export type TIssueIdentityAccessTokenInput = {
@@ -70,7 +77,10 @@ type TIdentityAccessTokenServiceFactoryDep = {
identityAccessTokenRevocationDAL: TIdentityAccessTokenRevocationDALFactory;
identityDAL: Pick<TIdentityDALFactory, "getTrustedIpsByAuthMethod" | "findById">;
orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership" | "findOne">;
- keyStore: Pick<TKeyStoreFactory, "getItem" | "incrementBy" | "setItemWithExpiry">;
+ keyStore: Pick<
+ TKeyStoreFactory,
+ "getItem" | "incrementBy" | "setItemWithExpiry" | "setItemWithExpiryNX" | "incrementSeededWithExpiry"
+ >;
};
export type TIdentityAccessTokenServiceFactory = ReturnType<typeof identityAccessTokenServiceFactory>;
@@ -90,6 +100,46 @@ export const identityAccessTokenServiceFactory = ({
);
};
+ // On revoke, bump this identity's version number. Every cached "allowed" answer
+ // remembers the version it was written under, so one bump instantly makes them
+ // all stale. Run it after the revocation record is saved and outside any
+ // transaction, so a request reading in parallel can't cache an allow under the
+ // old version. Best effort: a lost bump lets a revoked token pass for at most
+ // the cache lifetime.
+ const bumpRevocationVersion = async (identityId: string) => {
+ try {
+ await keyStore.incrementSeededWithExpiry(
+ KeyStorePrefixes.IdentityRevocationVersion(identityId),
+ Date.now(),
+ KeyStoreTtls.IdentityRevocationVersionInSeconds
+ );
+ } catch (error) {
+ logger.warn(error, `identity-revocation: failed to bump version [identityId=${identityId}]`);
+ }
+ };
+
+ // Reads this identity's current version number, creating it (from the current
+ // time) if it doesn't exist yet. Returns null only when the cache is down,
+ // which tells the caller not to store an "allowed" answer.
+ const getOrSeedRevocationVersion = async (identityId: string): Promise<number | null> => {
+ const versionKey = KeyStorePrefixes.IdentityRevocationVersion(identityId);
+ const existing = await keyStore.getItem(versionKey);
+ if (existing !== null) {
+ return Number(existing);
+ }
+
+ // Only set it if still missing, so a concurrent revoke's bump wins; then read
+ // back whatever value stuck.
+ await keyStore.setItemWithExpiryNX(versionKey, KeyStoreTtls.IdentityRevocationVersionInSeconds, Date.now());
+ const seeded = await keyStore.getItem(versionKey);
+ return seeded === null ? null : Number(seeded);
+ };
+
+ // A cached "allowed" answer is only trusted while the identity's version
+ // number still matches, so a revoke instantly invalidates it without ever
+ // storing the set of revocation records. A cached "denied"
+ // answer needs no version check and stands for its whole lifetime, because a
+ // revocation record always outlives any token it can block.
const assertTokenIsNotRevoked = async ({
tokenId,
identityId,
@@ -109,38 +159,88 @@ export const identityAccessTokenServiceFactory = ({
if (clientSecretId) scopes.push(clientSecretId);
if (authMethod) scopes.push(authMethod);
+ const fingerprint = computeRevocationVerdictFingerprint({ tokenId, issuedAtMs, clientSecretId, authMethod });
+ const verdictKey = KeyStorePrefixes.IdentityRevocationVerdict(identityId, fingerprint);
+ const versionKey = KeyStorePrefixes.IdentityRevocationVersion(identityId);
+
+ let cacheAvailable = true;
+ let cachedVersion: number | null = null;
+ let cachedVerdictRaw: string | null = null;
+
+ try {
+ // Two getItems (not MGET) to stay Redis-Cluster-safe. The version read here
+ // is what an allow verdict is stamped with, captured before the fill.
+ const [versionRaw, verdictRaw] = await Promise.all([keyStore.getItem(versionKey), keyStore.getItem(verdictKey)]);
+ cachedVersion = versionRaw === null ? null : Number(versionRaw);
+ cachedVerdictRaw = verdictRaw;
+ } catch (error) {
+ cacheAvailable = false;
+ logger.warn(error, `identity-revocation: verdict cache read failed, falling back to primary`);
+ }
+
+ if (cacheAvailable && cachedVerdictRaw) {
+ let parsed: { v?: number; deny?: TRevocationDenyReason } | null = null;
+ try {
+ parsed = JSON.parse(cachedVerdictRaw) as { v?: number; deny?: TRevocationDenyReason };
+ } catch {
+ parsed = null;
+ }
+
+ if (parsed?.deny) {
+ throw new UnauthorizedError({ message: revocationDenyReasonToMessage(parsed.deny, messagePrefix) });
+ }
+ // An allow only holds while the stamped version still matches the live one.
+ if (parsed && typeof parsed.v === "number" && cachedVersion !== null && parsed.v === cachedVersion) {
+ return;
+ }
+ }
+
+ // Resolve the version to stamp before the fill so a concurrent revoke's bump
+ // follows it and invalidates this allow.
+ let versionForStamp: number | null = null;
+ if (cacheAvailable) {
+ try {
+ versionForStamp = cachedVersion !== null ? cachedVersion : await getOrSeedRevocationVersion(identityId);
+ } catch (error) {
+ cacheAvailable = false;
+ logger.warn(error, `identity-revocation: version resolve failed, falling back to primary`);
+ }
+ }
+
const activeRevocations = await identityAccessTokenRevocationDAL.findActiveRevocationsForToken({
tokenId,
identityId,
scopes
});
- for (const revocation of activeRevocations) {
- // Legacy markers have scope=null and key off polymorphic `id`.
- if (revocation.scope === null || revocation.scope === undefined) {
- if (revocation.id === tokenId) {
- throw new UnauthorizedError({ message: `${messagePrefix}: token has been revoked` });
- }
- if (revocation.id === identityId) {
- const revokedAtMs = (revocation.revokedAt ?? revocation.createdAt).getTime();
- if (issuedAtMs < revokedAtMs) {
- throw new UnauthorizedError({ message: `${messagePrefix}: identity tokens have been revoked` });
- }
- }
- } else {
- // Scoped marker: scope holds the value the JWT must NOT match
- // (clientSecretId for UA tokens, authMethod for any token).
- const revokedAtMs = (revocation.revokedAt ?? revocation.createdAt).getTime();
- if (issuedAtMs < revokedAtMs) {
- if (clientSecretId && revocation.scope === clientSecretId) {
- throw new UnauthorizedError({ message: `${messagePrefix}: client secret has been revoked` });
- }
- if (authMethod && revocation.scope === authMethod) {
- throw new UnauthorizedError({ message: `${messagePrefix}: auth method has been revoked` });
- }
+ const denyReason = evaluateRevocationMarkers({
+ markers: activeRevocations,
+ tokenId,
+ identityId,
+ issuedAtMs,
+ clientSecretId,
+ authMethod
+ });
+
+ if (cacheAvailable) {
+ try {
+ const ttl = applyJitter(
+ KeyStoreTtls.IdentityRevocationVerdictBaseInSeconds,
+ KeyStoreTtls.IdentityRevocationVerdictJitterInSeconds
+ );
+ if (denyReason) {
+ await keyStore.setItemWithExpiry(verdictKey, ttl, JSON.stringify({ deny: denyReason }));
+ } else if (versionForStamp !== null) {
+ await keyStore.setItemWithExpiry(verdictKey, ttl, JSON.stringify({ v: versionForStamp }));
}
+ } catch (error) {
+ logger.warn(error, `identity-revocation: verdict cache write failed [identityId=${identityId}]`);
}
}
+
+ if (denyReason) {
+ throw new UnauthorizedError({ message: revocationDenyReasonToMessage(denyReason, messagePrefix) });
+ }
};
// Token Auth materializes a PG row at issuance (admin-managed UI list);
@@ -487,8 +587,6 @@ export const identityAccessTokenServiceFactory = ({
};
const revokeAccessToken = async (accessToken: string) => {
- const appCfg = getConfig();
-
const decodedToken = assertRevocableClaims(verifyAccessTokenJwt(accessToken));
const { identityId } = decodedToken;
const tokenId = decodedToken.jti ?? decodedToken.identityAccessTokenId;
@@ -510,17 +608,22 @@ export const identityAccessTokenServiceFactory = ({
}
: await loadLegacyTokenSource(decodedToken);
- const maxLifetimeSeconds =
- source.accessTokenMaxTTL > 0
- ? source.creationEpoch + source.accessTokenMaxTTL
- : Math.floor(Date.now() / 1000) + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE;
- const expiresAt = new Date(maxLifetimeSeconds * 1000);
+ // Cap the marker at the latest exp of any JWT it must block so it self-drains
+ // within a token TTL rather than the full maxTTL window.
+ const expiresAt = computePerTokenMarkerExpiry({
+ exp: decodedToken.exp,
+ requestedTTL: source.accessTokenTTL,
+ accessTokenMaxTTL: source.accessTokenMaxTTL,
+ accessTokenPeriod: source.accessTokenPeriod,
+ creationEpoch: source.creationEpoch
+ });
await identityAccessTokenRevocationDAL.insertRevocation({
id: tokenId,
identityId,
expiresAt
});
+ await bumpRevocationVersion(identityId);
return { revokedToken: { id: decodedToken.identityAccessTokenId, identityId, isAccessTokenRevoked: true } };
};
@@ -548,9 +651,11 @@ export const identityAccessTokenServiceFactory = ({
identityId,
expiresAt
});
+ await bumpRevocationVersion(identityId);
};
// Identity-wide revoke: any JWT with iat < this epoch is rejected on auth.
+ // Uses the 90d fallback since it is one marker per deleted identity.
const revokeAllTokensForIdentity = async (identityId: string) => {
const appCfg = getConfig();
const revokedAt = new Date();
@@ -561,6 +666,7 @@ export const identityAccessTokenServiceFactory = ({
revokedAt,
expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)
});
+ await bumpRevocationVersion(identityId);
};
// Scoped revoke for Universal Auth client secret deletion: rejects every JWT
@@ -583,6 +689,7 @@ export const identityAccessTokenServiceFactory = ({
revokedAt,
expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)
});
+ await bumpRevocationVersion(identityId);
};
// Scoped revoke for auth-method removal: rejects every JWT issued via the
@@ -605,6 +712,7 @@ export const identityAccessTokenServiceFactory = ({
revokedAt,
expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)
});
+ await bumpRevocationVersion(identityId);
};
return {
diff --git a/backend/src/services/identity-access-token/identity-access-token-types.ts b/backend/src/services/identity-access-token/identity-access-token-types.ts
index 6fa3a15357..e71255187d 100644
--- a/backend/src/services/identity-access-token/identity-access-token-types.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-types.ts
@@ -144,3 +144,15 @@ export type TSignIdentityAccessTokenOutput = {
jti: string;
expiresIn: number;
};
+
+// Columns of a revocation row the runtime check reads to render a verdict.
+export type TRevocationMarker = {
+ id: string;
+ identityId: string;
+ revokedAt?: Date | null;
+ createdAt: Date;
+ scope?: string | null;
+};
+
+// Reason a token is denied. Cached so a hit can build the error without hitting PG.
+export type TRevocationDenyReason = "token" | "identity" | "client-secret" | "auth-method";
diff --git a/backend/src/services/identity-token-auth/identity-token-auth-service.ts b/backend/src/services/identity-token-auth/identity-token-auth-service.ts
index 57a6030eff..53f229920e 100644
--- a/backend/src/services/identity-token-auth/identity-token-auth-service.ts
+++ b/backend/src/services/identity-token-auth/identity-token-auth-service.ts
@@ -15,7 +15,6 @@ import {
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
-import { getConfig } from "@app/lib/config/env";
import {
BadRequestError,
ForbiddenRequestError,
@@ -29,6 +28,7 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { ActorType } from "../auth/auth-type";
import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";
+import { computeTokenAuthRevokeMarkerExpiry } from "../identity-access-token/identity-access-token-fns";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";
import { TOrgDALFactory } from "../org/org-dal";
@@ -900,19 +900,13 @@ export const identityTokenAuthServiceFactory = ({
}
);
- const appCfg = getConfig();
- // maxTTL > 0: the latest possible JWT exp is createdAt + maxTTL regardless of MAX_AGE.
- // A JWT at createdAt + (maxTTL - MAX_AGE) gets a full MAX_AGE-bounded TTL, expiring at
- // createdAt + maxTTL. Using min(maxTTL, MAX_AGE) clips the marker too early when maxTTL > MAX_AGE.
- //
- // maxTTL == 0: no budget cap, so a JWT renewed just before revocation can expire up to MAX_AGE
- // after the revocation time (revokedAt), not after createdAt.
- let expiresAt: Date;
- if (identityAccessToken.accessTokenMaxTTL > 0) {
- expiresAt = new Date(identityAccessToken.createdAt.getTime() + identityAccessToken.accessTokenMaxTTL * 1000);
- } else {
- expiresAt = new Date(Date.now() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000);
- }
+ // No JWT here, so the helper anchors on now plus the row's issuance cap.
+ const expiresAt = computeTokenAuthRevokeMarkerExpiry({
+ accessTokenTTL: identityAccessToken.accessTokenTTL,
+ accessTokenMaxTTL: identityAccessToken.accessTokenMaxTTL,
+ accessTokenPeriod: identityAccessToken.accessTokenPeriod,
+ createdAtMs: identityAccessToken.createdAt.getTime()
+ });
await identityAccessTokenService.markPerTokenRevocation({
tokenId: identityAccessToken.id,
identityId: identityAccessToken.identityId,
diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
index 39438a27a3..a73c53e5aa 100644
--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts
@@ -97,7 +97,6 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
await userNotificationDAL.pruneNotifications();
await keyValueStoreDAL.pruneExpiredKeys();
await scepTransactionDAL.pruneExpiredTransactions();
- await identityAccessTokenRevocationDAL.removeExpiredRevocations();
await auditLogDAL.pruneAuditLog();
}
});
@@ -128,6 +127,10 @@ export const dailyResourceCleanUpQueueServiceFactory = ({
handler: async () => {
logger.info(`cron[${CronJobName.FrequentResourceCleanup}]: task started`);
await identityAccessTokenDAL.removeExpiredTokens();
+ const deletedRevocations = await identityAccessTokenRevocationDAL.removeExpiredRevocations();
+ logger.info(
+ `cron[${CronJobName.FrequentResourceCleanup}]: removed ${deletedRevocations} expired identity access token revocations`
+ );
const newlyExpired = await approvalRequestDAL.markExpiredRequests();
if (newlyExpired > 0) {
await certificateRequestDAL.markExpiredApprovalRequests();