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
improvement(eng-4942): use PG as primary for revocation storage
Tre Dubravaea1764d847ad
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 053339d9fb..f5c2a3d8c4 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -77,41 +77,6 @@ export const mockKeyStore = (): TKeyStoreFactory => {hashGet: async (key, field) => {return hashStore[key]?.[field] ?? null;},- hashGetMulti: async (key, fields) => {- const bucket = hashStore[key] ?? {};- return fields.map((field) => bucket[field] ?? null);- },- hashIncrementBy: async (key, field, value) => {- if (!hashStore[key]) {- hashStore[key] = {};- }- const current = parseInt(hashStore[key][field] ?? "0", 10);- const next = (Number.isNaN(current) ? 0 : current) + value;- hashStore[key][field] = String(next);- return next;- },- hashSetWithExpiry: async (key, fields) => {- if (!hashStore[key]) {- hashStore[key] = {};- }- for (const [field, value] of Object.entries(fields)) {- hashStore[key][field] = String(value);- }- },- hashDelete: async (key, ...fields) => {- const bucket = hashStore[key];- if (!bucket) {- return 0;- }- let deleted = 0;- for (const field of fields) {- if (field in bucket) {- delete bucket[field];- deleted += 1;- }- }- return deleted;- },pgIncrementBy: async () => {return 1;},diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 8ce2dbb503..340dfc855d 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -63,11 +63,8 @@ export const KeyStorePrefixes = {SecretSyncLastRunTimestamp: (syncId: string) => `secret-sync-last-run-${syncId}` as const,IdentityAccessTokenStatusUpdate: (identityAccessTokenId: string) =>`identity-access-token-status:${identityAccessTokenId}`,- // Per-identity hash of token-level state; field schema in IdentityTokenStateFields.- IdentityTokenState: (identityId: string) => `identity-token-state:${identityId}` as const,- // Single-flight marker for hydrateRedisFromPg; lives in the same Redis it gates,- // so a flush evicts it and the next pod re-hydrates.- IdentityTokenHydrate: "identity-token-hydrate" as const,+ IdentityTokenUsesRemaining: (identityId: string, jti: string) =>+ `identity-token-uses-remaining:${identityId}:${jti}` as const,ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`,GatewayIdentityCredential: (identityId: string) => `gateway-credentials:${identityId}`,ActiveSSEConnectionsSet: (projectId: string, identityId: string) =>@@ -130,14 +127,6 @@ export const KeyStorePrefixes = {TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const};-// Field names in the IdentityTokenState hash.-// RevokedAfter: ISO timestamp; identity-wide revocation epoch (JWTs with iat < this are rejected).-// UsesRemaining: per-token counter; <= 0 means revoked or exhausted.-export const IdentityTokenStateFields = {- RevokedAfter: "revokedAfter" as const,- UsesRemaining: (jti: string) => `usesRemaining:${jti}` as const-};-export const KeyStoreTtls = {SetSyncSecretIntegrationLastRunTimestampInSeconds: 60,SetSecretSyncLastRunTimestampInSeconds: 60,@@ -223,10 +212,6 @@ export type TKeyStoreFactory = {// hash operationshashSet: (key: string, field: string, value: string) => Promise<number>;hashGet: (key: string, field: string) => Promise<string | null>;- hashGetMulti: (key: string, fields: string[]) => Promise<(string | null)[]>;- hashIncrementBy: (key: string, field: string, value: number) => Promise<number>;- hashSetWithExpiry: (key: string, fields: Record<string, string | number>, expiryInSeconds: number) => Promise<void>;- hashDelete: (key: string, ...fields: string[]) => Promise<number>;// pgpgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;@@ -371,32 +356,6 @@ export const keyStoreFactory = (const hashGet = async (key: string, field: string) => primaryRedis.hget(key, field);- // Multi-field read in a single round-trip. Returns one value (or null) per requested field, in order.- const hashGetMulti = async (key: string, fields: string[]) =>- fields.length === 0 ? [] : primaryRedis.hmget(key, ...fields);-- // Atomic increment of a hash field; returns the new value. Use a negative `value` to decrement.- const hashIncrementBy = async (key: string, field: string, value: number) => primaryRedis.hincrby(key, field, value);-- // Set multiple fields at once and refresh the key-level TTL in a single pipelined round-trip.- // Hashes only support key-level TTL, so the caller refreshes the expiry on each write.- const hashSetWithExpiry = async (key: string, fields: Record<string, string | number>, expiryInSeconds: number) => {- const flat: (string | number)[] = [];- for (const [field, value] of Object.entries(fields)) {- flat.push(field, value);- }- if (flat.length === 0) {- return;- }- const pipeline = primaryRedis.pipeline();- pipeline.hset(key, ...flat);- pipeline.expire(key, expiryInSeconds);- await pipeline.exec();- };-- const hashDelete = async (key: string, ...fields: string[]) =>- fields.length === 0 ? 0 : primaryRedis.hdel(key, ...fields);-// List operationsconst listPush = async (key: string, value: string) => primaryRedis.rpush(key, value);@@ -496,10 +455,6 @@ export const keyStoreFactory = (pgIncrementBy,hashSet,hashGet,- hashGetMulti,- hashIncrementBy,- hashSetWithExpiry,- hashDelete,listPush,listRange,listRemove,diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 08d0bfa72c..55a09997c1 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -75,41 +75,6 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {hashGet: async (key, field) => {return hashStore[key]?.[field] ?? null;},- hashGetMulti: async (key, fields) => {- const bucket = hashStore[key] ?? {};- return fields.map((field) => bucket[field] ?? null);- },- hashIncrementBy: async (key, field, value) => {- if (!hashStore[key]) {- hashStore[key] = {};- }- const current = parseInt(hashStore[key][field] ?? "0", 10);- const next = (Number.isNaN(current) ? 0 : current) + value;- hashStore[key][field] = String(next);- return next;- },- hashSetWithExpiry: async (key, fields) => {- if (!hashStore[key]) {- hashStore[key] = {};- }- for (const [field, value] of Object.entries(fields)) {- hashStore[key][field] = String(value);- }- },- hashDelete: async (key, ...fields) => {- const bucket = hashStore[key];- if (!bucket) {- return 0;- }- let deleted = 0;- for (const field of fields) {- if (field in bucket) {- delete bucket[field];- deleted += 1;- }- }- return deleted;- },pgIncrementBy: async () => {return 1;},diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 8611793ce5..784c41f5dc 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -105,8 +105,7 @@ export enum QueueName {PamDiscoveryScan = "pam-discovery-scan",CaAutoRenewal = "ca-auto-renewal",CertificateCleanup = "certificate-cleanup",- DigiCertOrderPolling = "digicert-order-polling",- IdentityAccessTokenPgMirror = "identity-access-token-pg-mirror"+ DigiCertOrderPolling = "digicert-order-polling"}export enum QueueJobs {@@ -178,9 +177,7 @@ export enum QueueJobs {CaAdcsInstall = "ca-adcs-install-job",CertificateCleanup = "certificate-cleanup-job",DailySecretSyncRetry = "daily-secret-sync-retry-job",- DigiCertOrderPolling = "digicert-order-polling-job",- IdentityAccessTokenPgMirrorRevokeToken = "identity-access-token-pg-mirror-revoke-token",- IdentityAccessTokenPgMirrorRevokeAll = "identity-access-token-pg-mirror-revoke-all"+ DigiCertOrderPolling = "digicert-order-polling-job"}export type TQueueOptions = {@@ -554,24 +551,6 @@ export type TQueueJobTypes = {name: QueueJobs.DigiCertOrderPolling;payload: undefined;};- [QueueName.IdentityAccessTokenPgMirror]:- | {- name: QueueJobs.IdentityAccessTokenPgMirrorRevokeToken;- payload: {- kind: "revoke-token";- tokenId: string;- identityId: string;- expiresAt: string;- };- }- | {- name: QueueJobs.IdentityAccessTokenPgMirrorRevokeAll;- payload: {- kind: "revoke-all-for-identity";- identityId: string;- revokedAt: string;- };- };};const SECRET_SCANNING_QUEUES = [diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 413715c787..98d7940e4a 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -306,7 +306,6 @@ import { identityMetadataDALFactory } from "@app/services/identity/identity-metaimport { identityOrgDALFactory } from "@app/services/identity/identity-org-dal";import { identityServiceFactory } from "@app/services/identity/identity-service";import { identityAccessTokenDALFactory } from "@app/services/identity-access-token/identity-access-token-dal";-import { identityAccessTokenQueueServiceFactory } from "@app/services/identity-access-token/identity-access-token-queue";import { identityAccessTokenRevocationDALFactory } from "@app/services/identity-access-token/identity-access-token-revocation-dal";import { identityAccessTokenServiceFactory } from "@app/services/identity-access-token/identity-access-token-service";import { identityAliCloudAuthDALFactory } from "@app/services/identity-alicloud-auth/identity-alicloud-auth-dal";@@ -1878,18 +1877,12 @@ export const registerRoutes = async (membershipRoleDAL});- const identityAccessTokenQueue = identityAccessTokenQueueServiceFactory({- queueService,- identityAccessTokenRevocationDAL- });-const identityAccessTokenService = identityAccessTokenServiceFactory({identityAccessTokenDAL,identityAccessTokenRevocationDAL,identityDAL,orgDAL,- keyStore,- identityAccessTokenQueue+ keyStore});const identityV2Service = identityV2ServiceFactory({@@ -3464,11 +3457,6 @@ export const registerRoutes = async (await server.register(registerBddNockRouter, { prefix: "/api/__bdd_nock__" });}- // Fire-and-forget: replay revoked-token markers from Postgres into Redis so- // the auth hot path is authoritative after a Redis flush. Errors are logged- // inside hydrateRedisFromPg; this must not block server startup.- void identityAccessTokenService.hydrateRedisFromPg();-server.addHook("onClose", async () => {cronJobs.forEach((job) => job.stop());await telemetryService.flushAll();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 119987e144..125a8fb8c8 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@@ -33,16 +33,6 @@ export const parseUsesRemaining = (raw: string | null): number | null => {return Number.isNaN(parsed) ? null : parsed;};-// Parse the identity-wide revocation epoch (ISO timestamp) into ms-since-epoch.-// Returns null when absent or unparseable.-export const parseRevokedAfter = (raw: string | null): number | null => {- if (!raw) {- return null;- }- const ms = new Date(raw).getTime();- return Number.isFinite(ms) ? ms : null;-};-// Resolve TTL inputs into the (requestedTTL, requestedMaxTTL) pair that// computeIssuedTtl expects. Periodic mode (period > 0) uses period as the// effective TTL with no per-token max; standard mode passes the inputs through.diff --git a/backend/src/services/identity-access-token/identity-access-token-queue.ts b/backend/src/services/identity-access-token/identity-access-token-queue.tsdeleted file mode 100644index d1c701a736..0000000000--- a/backend/src/services/identity-access-token/identity-access-token-queue.ts+++ /dev/null@@ -1,99 +0,0 @@-import { getConfig } from "@app/lib/config/env";-import { logger } from "@app/lib/logger";-import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";--import { TIdentityAccessTokenRevocationDALFactory } from "./identity-access-token-revocation-dal";--type TIdentityAccessTokenQueueServiceFactoryDep = {- queueService: TQueueServiceFactory;- identityAccessTokenRevocationDAL: TIdentityAccessTokenRevocationDALFactory;-};--export type TIdentityAccessTokenQueueServiceFactory = ReturnType<typeof identityAccessTokenQueueServiceFactory>;--type TRevokeTokenPayload = {- kind: "revoke-token";- tokenId: string;- identityId: string;- expiresAt: string;-};--type TRevokeAllPayload = {- kind: "revoke-all-for-identity";- identityId: string;- revokedAt: string;-};--type TPgMirrorPayload = TRevokeTokenPayload | TRevokeAllPayload;--export const identityAccessTokenQueueServiceFactory = ({- queueService,- identityAccessTokenRevocationDAL-}: TIdentityAccessTokenQueueServiceFactoryDep) => {- const queuePgMirror = async (payload: TPgMirrorPayload) => {- if (payload.kind === "revoke-token") {- await queueService.queue(- QueueName.IdentityAccessTokenPgMirror,- QueueJobs.IdentityAccessTokenPgMirrorRevokeToken,- payload,- {- jobId: `iat-revoke-token-${payload.tokenId}`,- attempts: 5,- backoff: { type: "exponential", delay: 500 },- removeOnComplete: true,- removeOnFail: { count: 20 }- }- );- } else {- await queueService.queue(- QueueName.IdentityAccessTokenPgMirror,- QueueJobs.IdentityAccessTokenPgMirrorRevokeAll,- payload,- {- jobId: `iat-revoke-all-${payload.identityId}`,- attempts: 5,- backoff: { type: "exponential", delay: 500 },- removeOnComplete: true,- removeOnFail: { count: 20 }- }- );- }- };-- queueService.start(QueueName.IdentityAccessTokenPgMirror, async (job) => {- const data = job.data as TPgMirrorPayload;-- switch (data.kind) {- case "revoke-token": {- await identityAccessTokenRevocationDAL.insertRevocation({- id: data.tokenId,- identityId: data.identityId,- expiresAt: new Date(data.expiresAt)- });- break;- }- case "revoke-all-for-identity": {- const appCfg = getConfig();- // expiresAt = revokedAt + MAX_AGE: every JWT issued before revokedAt- // has its exp <= revokedAt + MAX_AGE, so the marker can be dropped- // after that window closes.- const revokedAt = new Date(data.revokedAt);- await identityAccessTokenRevocationDAL.insertRevocation({- id: data.identityId,- identityId: data.identityId,- revokedAt,- expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)- });- break;- }- default:- break;- }- });-- queueService.listen(QueueName.IdentityAccessTokenPgMirror, "failed", (_, err) => {- logger.error(err, `${QueueName.IdentityAccessTokenPgMirror}: job failed`);- });-- return { queuePgMirror };-};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.tsindex 2e4b2215e3..3fb3aa6c43 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@@ -7,9 +7,8 @@ type TRevocationRow = Pick<TIdentityAccessTokenRevocations, "id" | "identityId"export type TIdentityAccessTokenRevocationDALFactory = ReturnType<typeof identityAccessTokenRevocationDALFactory>;// `id` is set explicitly: JWT jti for per-token revocations, identityId for-// revoke-all sentinels. `revokedAt` is populated only for sentinels so-// hydration can replay the exact revocation time rather than falling back to-// createdAt (which is BullMQ job execution time, not the revocation call).+// revoke-all sentinels. `revokedAt` is populated only for sentinels so runtime+// validation can compare the JWT iat against the exact revocation time.type TInsertRevocationInput = {id: string;identityId: string;@@ -23,31 +22,34 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {await db(TableName.IdentityAccessTokenRevocation).insert(row).onConflict(["id"])- .merge({ updatedAt: db.fn.now() });+ .merge({+ identityId: row.identityId,+ expiresAt: row.expiresAt,+ revokedAt: row.revokedAt ?? null,+ updatedAt: db.fn.now()+ });} catch (error) {throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationInsert" });}};- // Cursor pagination keyed on id. The WHERE on expiresAt prunes expired rows- // from the scan; ORDER BY id keeps batches stable across MVCC churn between- // calls.- const findActive = async ({ limit, afterId }: { limit: number; afterId?: string }): Promise<TRevocationRow[]> => {+ const findActiveRevocationsForToken = async ({+ tokenId,+ identityId+ }: {+ tokenId: string;+ identityId: string;+ }): Promise<TRevocationRow[]> => {try {- let query = db+ return (await db.replicaNode()(TableName.IdentityAccessTokenRevocation).select("id", "identityId", "revokedAt", "createdAt").where("expiresAt", ">", db.fn.now())- .orderBy("id", "asc")- .limit(limit);-- if (afterId) {- query = query.andWhere("id", ">", afterId);- }-- return (await query) as TRevocationRow[];+ .where("identityId", identityId)+ // Revoke-all uses identityId as id+ .whereIn("id", [tokenId, identityId])) as TRevocationRow[];} catch (error) {- throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationFindActive" });+ throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationFindActiveForToken" });}};@@ -61,7 +63,7 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {return {insertRevocation,- findActive,+ findActiveRevocationsForToken,removeExpiredRevocations};};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 6e6b2a09c0..2741484fab 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@@ -3,10 +3,8 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, viimport { IdentityAuthMethod } from "@app/db/schemas";import { crypto } from "@app/lib/crypto";import { IPType, TIp } from "@app/lib/ip";-import { QueueJobs, QueueName } from "@app/queue";import { signIdentityAccessToken } from "./identity-access-token-fns";-import { identityAccessTokenQueueServiceFactory } from "./identity-access-token-queue";import { identityAccessTokenServiceFactory } from "./identity-access-token-service";import { TIdentityAccessTokenJwtPayload } from "./identity-access-token-types";@@ -30,17 +28,21 @@ vi.mock("@app/lib/logger", () => ({const createService = ({trustedIps = [],- membership = { isActive: true }+ membership = { isActive: true },+ activeRevocations = []}: {trustedIps?: TIp[] | null;membership?: { isActive: boolean } | null;+ activeRevocations?: Array<{ id: string; identityId: string; revokedAt?: Date | null; createdAt: Date }>;} = {}) => {const keyStore = {- hashGetMulti: vi.fn().mockResolvedValue([null, null]),- hashIncrementBy: vi.fn(),- hashSetWithExpiry: vi.fn(),- setItemWithExpiry: vi.fn(),- setItemWithExpiryNX: vi.fn()+ getItem: vi.fn().mockResolvedValue(null),+ incrementBy: vi.fn(),+ setItemWithExpiry: vi.fn()+ };+ const identityAccessTokenRevocationDAL = {+ findActiveRevocationsForToken: vi.fn().mockResolvedValue(activeRevocations),+ insertRevocation: vi.fn()};const identityDAL = {getTrustedIpsByAuthMethod: vi.fn().mockResolvedValue(trustedIps),@@ -49,22 +51,16 @@ const createService = ({const orgDAL = {findEffectiveOrgMembership: vi.fn().mockResolvedValue(membership)};- const identityAccessTokenQueue = {- queuePgMirror: vi.fn(),- startPartitionMaintenanceCron: vi.fn(),- runPartitionMaintenance: vi.fn()- };const service = identityAccessTokenServiceFactory({identityAccessTokenDAL: { findOne: vi.fn() } as never,- identityAccessTokenRevocationDAL: {} as never,+ identityAccessTokenRevocationDAL: identityAccessTokenRevocationDAL as never,identityDAL: identityDAL as never,orgDAL: orgDAL as never,- keyStore: keyStore as never,- identityAccessTokenQueue: identityAccessTokenQueue as never+ keyStore: keyStore as never});- return { service, keyStore, identityDAL, orgDAL, identityAccessTokenQueue };+ return { service, keyStore, identityDAL, orgDAL, identityAccessTokenRevocationDAL };};const createTokenClaims = (@@ -118,7 +114,7 @@ describe("identityAccessTokenServiceFactory", () => {vi.clearAllMocks();});- test("queues per-token revocation with the JWT exp for zero configured TTL tokens", async () => {+ test("writes per-token revocation to PG with the JWT exp for zero configured TTL tokens", async () => {const { accessToken } = signIdentityAccessToken({identityAccessTokenId: "token-id",identityId: "identity-id",@@ -137,18 +133,123 @@ describe("identityAccessTokenServiceFactory", () => {creationEpoch: NOW_SECONDS,identityAuth: {}});- const { service, identityAccessTokenQueue } = createService();+ const { service, identityAccessTokenRevocationDAL } = createService();await service.revokeAccessToken(accessToken);- expect(identityAccessTokenQueue.queuePgMirror).toHaveBeenCalledWith({- kind: "revoke-token",- tokenId: "token-id",+ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({+ id: "token-id",+ identityId: "identity-id",+ expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)+ });+ });++ test("writes identity-wide revocation sentinel to PG", async () => {+ const { service, identityAccessTokenRevocationDAL } = createService();++ await service.revokeAllTokensForIdentity("identity-id");++ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({+ id: "identity-id",+ identityId: "identity-id",+ revokedAt: new Date(NOW_SECONDS * 1000),+ expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)+ });+ });++ test("rejects active per-token PG revocations", async () => {+ const { service } = createService({+ activeRevocations: [{ id: "token-id", identityId: "identity-id", createdAt: new Date(NOW_SECONDS * 1000) }]+ });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(+ "token has been revoked"+ );+ });++ test("rejects active identity-wide PG revocations for tokens issued before revokedAt", async () => {+ const { service } = createService({+ activeRevocations: [+ {+ id: "identity-id",+ identityId: "identity-id",+ revokedAt: new Date((NOW_SECONDS + 10) * 1000),+ createdAt: new Date((NOW_SECONDS + 10) * 1000)+ }+ ]+ });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(+ "identity tokens have been revoked"+ );+ });++ test("allows tokens issued after an identity-wide PG revocation", async () => {+ const { service } = createService({+ activeRevocations: [+ {+ id: "identity-id",+ identityId: "identity-id",+ revokedAt: new Date((NOW_SECONDS - 10) * 1000),+ createdAt: new Date((NOW_SECONDS - 10) * 1000)+ }+ ]+ });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).resolves.toMatchObject({identityId: "identity-id",- expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000).toISOString()+ orgId: "org-id"});});+ test("keeps usage counters in Redis", async () => {+ const { service, keyStore } = createService();+ keyStore.getItem.mockResolvedValue("1");+ keyStore.incrementBy.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);+ });++ test("rejects exhausted Redis usage counters", async () => {+ const { service, keyStore } = createService();+ keyStore.getItem.mockResolvedValue("0");++ await expect(+ service.fnValidateIdentityAccessTokenFast(createTokenClaims({ numUsesLimit: 3 }), "10.0.0.1")+ ).rejects.toThrow("usage limit reached");+ });++ test("rejects renewal when PG says the token is revoked", 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: MAX_AGE,+ accessTokenTTL: 0,+ accessTokenMaxTTL: 0,+ accessTokenPeriod: 0,+ creationEpoch: NOW_SECONDS,+ identityAuth: {}+ });+ const { service } = createService({+ activeRevocations: [{ id: "token-id", identityId: "identity-id", createdAt: new Date(NOW_SECONDS * 1000) }]+ });++ await expect(service.renewAccessToken({ accessToken })).rejects.toThrow("token has been revoked");+ });+test("checks current trusted IPs even when the token was issued without IP restrictions", async () => {const { service, identityDAL } = createService({trustedIps: [{ ipAddress: "10.0.0.0", prefix: 24, type: IPType.IPV4 }]@@ -190,82 +291,3 @@ describe("identityAccessTokenServiceFactory", () => {);});});--describe("identityAccessTokenQueueServiceFactory", () => {- afterEach(() => {- vi.clearAllMocks();- });-- test("queues PG mirror jobs with BullMQ-safe job IDs", async () => {- const queueService = {- queue: vi.fn(),- upsertJobScheduler: vi.fn(),- listen: vi.fn(),- start: vi.fn()- };-- const queue = identityAccessTokenQueueServiceFactory({- queueService: queueService as never,- identityAccessTokenRevocationDAL: {- insertRevocation: vi.fn(),- ensurePartition: vi.fn(),- listPartitionsExpiredBefore: vi.fn(),- dropPartition: vi.fn()- } as never- });-- await queue.queuePgMirror({- kind: "revoke-token",- tokenId: "token-id",- identityId: "identity-id",- expiresAt: "2026-04-28T00:00:00.000Z"- });-- expect(queueService.queue).toHaveBeenCalledWith(- QueueName.IdentityAccessTokenPgMirror,- QueueJobs.IdentityAccessTokenPgMirrorRevokeToken,- expect.any(Object),- expect.objectContaining({ jobId: "iat-revoke-token-token-id" })- );- });-- test("mirrors per-token revocations using the queued expiration", async () => {- const insertRevocation = vi.fn();- let worker: ((job: { name: QueueJobs; data: unknown }) => Promise<void>) | undefined;- const queueService = {- queue: vi.fn(),- upsertJobScheduler: vi.fn(),- listen: vi.fn(),- start: vi.fn((_queueName: QueueName, handler: (job: { name: QueueJobs; data: unknown }) => Promise<void>) => {- worker = handler;- })- };-- identityAccessTokenQueueServiceFactory({- queueService: queueService as never,- identityAccessTokenRevocationDAL: {- insertRevocation,- ensurePartition: vi.fn(),- listPartitionsExpiredBefore: vi.fn(),- dropPartition: vi.fn()- } as never- });-- await worker?.({- name: QueueJobs.IdentityAccessTokenPgMirrorRevokeToken,- data: {- kind: "revoke-token",- tokenId: "token-id",- identityId: "identity-id",- expiresAt: "2026-04-28T00:00:00.000Z"- }- });-- expect(queueService.start).toHaveBeenCalledWith(QueueName.IdentityAccessTokenPgMirror, expect.any(Function));- expect(insertRevocation).toHaveBeenCalledWith({- id: "token-id",- identityId: "identity-id",- expiresAt: new Date("2026-04-28T00:00:00.000Z")- });- });-});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 31fab1552c..7b86da6bae 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,12 +1,11 @@import { Knex } from "knex";import { IdentityAuthMethod, OrgMembershipStatus, TIdentityAccessTokens } from "@app/db/schemas";-import { IdentityTokenStateFields, KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";import { UnauthorizedError } from "@app/lib/errors";import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip";-import { logger } from "@app/lib/logger";import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";@@ -19,13 +18,11 @@ import {computeIssuedTtl,hasFullRenewClaims,hasNonWildcardTrustedIps,- parseRevokedAfter,parseUsesRemaining,resolveTtlInputs,signIdentityAccessToken,verifyAccessTokenJwt} from "./identity-access-token-fns";-import { TIdentityAccessTokenQueueServiceFactory } from "./identity-access-token-queue";import { TIdentityAccessTokenRevocationDALFactory } from "./identity-access-token-revocation-dal";import {TAWSAuthDetails,@@ -71,11 +68,7 @@ type TIdentityAccessTokenServiceFactoryDep = {identityAccessTokenRevocationDAL: TIdentityAccessTokenRevocationDALFactory;identityDAL: Pick<TIdentityDALFactory, "getTrustedIpsByAuthMethod" | "findById">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;- keyStore: Pick<- TKeyStoreFactory,- "hashGetMulti" | "hashIncrementBy" | "hashSetWithExpiry" | "setItemWithExpiry" | "setItemWithExpiryNX"- >;- identityAccessTokenQueue: TIdentityAccessTokenQueueServiceFactory;+ keyStore: Pick<TKeyStoreFactory, "getItem" | "incrementBy" | "setItemWithExpiry">;};export type TIdentityAccessTokenServiceFactory = ReturnType<typeof identityAccessTokenServiceFactory>;@@ -85,9 +78,46 @@ export const identityAccessTokenServiceFactory = ({identityAccessTokenRevocationDAL,identityDAL,orgDAL,- keyStore,- identityAccessTokenQueue+ keyStore}: TIdentityAccessTokenServiceFactoryDep) => {+ const setUsesRemaining = async (identityId: string, tokenId: string, usesRemaining: number, ttlSeconds: number) => {+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.IdentityTokenUsesRemaining(identityId, tokenId),+ ttlSeconds,+ usesRemaining+ );+ };++ const assertTokenIsNotRevoked = async ({+ tokenId,+ identityId,+ issuedAtMs,+ messagePrefix = "Failed to authorize"+ }: {+ tokenId: string;+ identityId: string;+ issuedAtMs: number;+ messagePrefix?: "Failed to authorize" | "Cannot renew";+ }) => {+ const activeRevocations = await identityAccessTokenRevocationDAL.findActiveRevocationsForToken({+ tokenId,+ identityId+ });++ for (const revocation of activeRevocations) {+ 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` });+ }+ }+ }+ };+// Token Auth materializes a PG row at issuance (admin-managed UI list);// every other method lazily inserts a row only on revoke.const issueIdentityAccessToken = async (@@ -163,9 +193,10 @@ export const identityAccessTokenServiceFactory = ({});if (numUsesLimit > 0) {- await keyStore.hashSetWithExpiry(- KeyStorePrefixes.IdentityTokenState(input.identityId),- { [IdentityTokenStateFields.UsesRemaining(identityAccessToken.id)]: numUsesLimit },+ await setUsesRemaining(+ input.identityId,+ identityAccessToken.id,+ numUsesLimit,appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);}@@ -185,38 +216,29 @@ export const identityAccessTokenServiceFactory = ({throw new UnauthorizedError({ message: "Identity access token exceeded max age, please re-authenticate" });}- const stateKey = KeyStorePrefixes.IdentityTokenState(token.identityId);-- const [revokedAfter, usesRemainingRaw] = await keyStore.hashGetMulti(stateKey, [- IdentityTokenStateFields.RevokedAfter,- IdentityTokenStateFields.UsesRemaining(token.jti)+ const [, usesRemainingRaw] = await Promise.all([+ assertTokenIsNotRevoked({+ tokenId: token.jti,+ identityId: token.identityId,+ issuedAtMs+ }),+ keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, token.jti))]);- const revokedAfterMs = parseRevokedAfter(revokedAfter);- if (revokedAfterMs !== null && issuedAtMs < revokedAfterMs) {- throw new UnauthorizedError({ message: "Failed to authorize: identity tokens have been revoked" });- }-- // The counter doubles as the per-token revoke marker. null means- // unlimited and not revoked; <= 0 means revoked or exhausted.+ // null means unlimited or the Redis counter was lost; <= 0 means exhausted.const remainingFromState = parseUsesRemaining(usesRemainingRaw);if (remainingFromState !== null && remainingFromState <= 0) {- throw new UnauthorizedError({ message: "Failed to authorize: token revoked or usage limit reached" });+ throw new UnauthorizedError({ message: "Failed to authorize: token usage limit reached" });}if (token.numUsesLimit && token.numUsesLimit > 0) {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 keyStore.hashSetWithExpiry(- stateKey,- { [IdentityTokenStateFields.UsesRemaining(token.jti)]: token.numUsesLimit - 1 },- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );+ await setUsesRemaining(token.identityId, token.jti, token.numUsesLimit - 1, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);} else {- const remaining = await keyStore.hashIncrementBy(- stateKey,- IdentityTokenStateFields.UsesRemaining(token.jti),+ const remaining = await keyStore.incrementBy(+ KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, token.jti),-1);if (remaining < 0) {@@ -318,22 +340,21 @@ export const identityAccessTokenServiceFactory = ({}: await loadLegacyRenewSource(decodedToken);- const stateKey = KeyStorePrefixes.IdentityTokenState(decodedToken.identityId);const { jti } = decodedToken;- const [existingUsesRemainingRaw, revokedAfterRaw] = await keyStore.hashGetMulti(stateKey, [- IdentityTokenStateFields.UsesRemaining(jti),- IdentityTokenStateFields.RevokedAfter+ const [, existingUsesRemainingRaw] = await Promise.all([+ assertTokenIsNotRevoked({+ tokenId: jti,+ identityId: decodedToken.identityId,+ issuedAtMs: decodedToken.iat * 1000,+ messagePrefix: "Cannot renew"+ }),+ keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(decodedToken.identityId, jti))]);const existingRemaining = parseUsesRemaining(existingUsesRemainingRaw);if (existingRemaining !== null && existingRemaining <= 0) {- throw new UnauthorizedError({ message: "Cannot renew revoked or exhausted access token" });- }-- const renewRevokedAfterMs = parseRevokedAfter(revokedAfterRaw);- if (renewRevokedAfterMs !== null && decodedToken.iat * 1000 < renewRevokedAfterMs) {- throw new UnauthorizedError({ message: "Cannot renew: identity tokens have been revoked" });+ throw new UnauthorizedError({ message: "Cannot renew exhausted access token" });}const { requestedTTL, requestedMaxTTL } = resolveTtlInputs(@@ -374,15 +395,11 @@ export const identityAccessTokenServiceFactory = ({creationEpoch: source.creationEpoch});- // Renewed JWT keeps the same `jti`, so any existing revocation marker- // already applies. Reseed the counter to the current remaining budget.+ // Renewed JWT keeps the same `jti`; PG revocation already applies. Reseed+ // the Redis counter to the current remaining budget.if (numUsesLimit > 0) {const remainingUses = existingRemaining === null ? numUsesLimit : Math.max(0, existingRemaining);- await keyStore.hashSetWithExpiry(- stateKey,- { [IdentityTokenStateFields.UsesRemaining(jti)]: remainingUses },- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );+ await setUsesRemaining(decodedToken.identityId, jti, remainingUses, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);}return {@@ -397,20 +414,12 @@ export const identityAccessTokenServiceFactory = ({const decodedToken = assertRevocableClaims(verifyAccessTokenJwt(accessToken));const { jti, identityId } = decodedToken;+ const expiresAt = new Date((decodedToken.exp ?? decodedToken.iat + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE) * 1000);- await keyStore.hashSetWithExpiry(- KeyStorePrefixes.IdentityTokenState(identityId),- { [IdentityTokenStateFields.UsesRemaining(jti)]: 0 },- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );-- void identityAccessTokenQueue.queuePgMirror({- kind: "revoke-token",- tokenId: decodedToken.identityAccessTokenId,+ await identityAccessTokenRevocationDAL.insertRevocation({+ id: jti,identityId,- expiresAt: new Date(- (decodedToken.exp ?? decodedToken.iat + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE) * 1000- ).toISOString()+ expiresAt});return { revokedToken: { id: decodedToken.identityAccessTokenId, identityId, isAccessTokenRevoked: true } };@@ -429,14 +438,6 @@ export const identityAccessTokenServiceFactory = ({identityId: string;expiresAt: Date;}) => {- const appCfg = getConfig();-- await keyStore.hashSetWithExpiry(- KeyStorePrefixes.IdentityTokenState(identityId),- { [IdentityTokenStateFields.UsesRemaining(tokenId)]: 0 },- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );-if (expiresAt.getTime() <= Date.now()) {return;}@@ -453,102 +454,20 @@ export const identityAccessTokenServiceFactory = ({const appCfg = getConfig();const revokedAt = new Date();- await keyStore.hashSetWithExpiry(- KeyStorePrefixes.IdentityTokenState(identityId),- { [IdentityTokenStateFields.RevokedAfter]: revokedAt.toISOString() },- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );-- void identityAccessTokenQueue.queuePgMirror({- kind: "revoke-all-for-identity",+ await identityAccessTokenRevocationDAL.insertRevocation({+ id: identityId,identityId,- revokedAt: revokedAt.toISOString()+ revokedAt,+ expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)});};- const HYDRATION_LEASE_SECONDS = 600;- const HYDRATION_MARKER_SECONDS = 2_592_000;-- const hydrateRedisFromPg = async () => {- const acquired = await keyStore.setItemWithExpiryNX(- KeyStorePrefixes.IdentityTokenHydrate,- HYDRATION_LEASE_SECONDS,- "in-progress"- );- if (acquired === null) {- logger.info("identityAccessToken.hydrateRedisFromPg: skipped (another pod or already hydrated)");- return;- }-- const appCfg = getConfig();- const BATCH_SIZE = 5_000;-- logger.info("identityAccessToken.hydrateRedisFromPg: starting Redis hydration from Postgres");-- let afterId: string | undefined;- let totalTokens = 0;- let totalIdentities = 0;- try {- // eslint-disable-next-line no-constant-condition- while (true) {- // Cursor pagination on id avoids MVCC drift across batches. The- // expiresAt > NOW() filter inside the DAL drives partition pruning.- // eslint-disable-next-line no-await-in-loop- const rows = await identityAccessTokenRevocationDAL.findActive({ limit: BATCH_SIZE, afterId });-- if (rows.length === 0) {- break;- }-- const fieldsByIdentity = new Map<string, Record<string, string | number>>();- for (const row of rows) {- const bucket = fieldsByIdentity.get(row.identityId) ?? {};- if (row.id === row.identityId) {- bucket[IdentityTokenStateFields.RevokedAfter] = (row.revokedAt ?? row.createdAt).toISOString();- totalIdentities += 1;- } else {- bucket[IdentityTokenStateFields.UsesRemaining(row.id)] = 0;- totalTokens += 1;- }- fieldsByIdentity.set(row.identityId, bucket);- }-- // eslint-disable-next-line no-await-in-loop- await Promise.allSettled(- Array.from(fieldsByIdentity.entries()).map(async ([identityId, fields]) =>- keyStore.hashSetWithExpiry(- KeyStorePrefixes.IdentityTokenState(identityId),- fields,- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- )- )- );-- if (rows.length < BATCH_SIZE) {- break;- }- afterId = rows[rows.length - 1].id;- }- } catch (err) {- logger.error(err, "identityAccessToken.hydrateRedisFromPg: failed during hydration");- return;- }-- // Promote the lease to a long-lived marker. Failure here is non-fatal: the- // lease will expire and the next pod retries idempotently.- await keyStore.setItemWithExpiry(KeyStorePrefixes.IdentityTokenHydrate, HYDRATION_MARKER_SECONDS, "complete");- logger.info(- `identityAccessToken.hydrateRedisFromPg: completed [tokenRevocations=${totalTokens}] [identityRevocations=${totalIdentities}]`- );- };-return {issueIdentityAccessToken,renewAccessToken,revokeAccessToken,revokeAllTokensForIdentity,markPerTokenRevocation,- fnValidateIdentityAccessTokenFast,- hydrateRedisFromPg+ fnValidateIdentityAccessTokenFast};};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.tsindex c61643d271..0167a81efc 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@@ -25,14 +25,14 @@ export type TKubernetesAuthDetails = {name: string;};-// Custom claims that the redesigned identity access token JWT carries so the-// auth hot path doesn't need to hit Postgres for the common case. `jti`, `iat`,-// and `exp` come from the JWT spec — declared here for post-verify typing.+// Custom claims the identity access token JWT carries for stateless TTL/auth+// context. `jti`, `iat`, and `exp` come from the JWT spec — declared here for+// post-verify typing.//// `accessTokenTTL`, `accessTokenMaxTTL`, and `accessTokenPeriod` are mirrored-// into every renewed JWT so the renew flow can recompute caps without a PG-// read (the row may not exist for non-Token-Auth methods under the lazy-insert-// model).+// into every renewed JWT so the renew flow can recompute caps without loading+// a token row (the row may not exist for non-Token-Auth methods under the+// lazy-insert model).//// `creationEpoch` anchors the maxTTL lifetime budget across renewals. JWT `iat`// is restamped on every renewal, so it cannot anchor "since creation" — this