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): support legacy JWTs through PG fallback
Tre Dubravad0b95101c299
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.tsindex 464d1fbeda..72acb55297 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@@ -10,9 +10,11 @@* depend on or mutate the seeded machine identity.*/+import { randomUUID } from "node:crypto";+import jwt from "jsonwebtoken";-import { AccessScope, OrgMembershipRole, TableName } from "@app/db/schemas";+import { AccessScope, IdentityAuthMethod, OrgMembershipRole, TableName } from "@app/db/schemas";import { seedData1 } from "@app/db/seed-data";import { AuthTokenType } from "@app/services/auth/auth-type";@@ -122,8 +124,8 @@ const deleteOrgIdentityMembership = async (identityId: string) => {expect(membership).toBeDefined();- await testDb(TableName.MembershipRole).where({ membershipId: membership!.id }).delete();- await testDb(TableName.Membership).where({ id: membership!.id }).delete();+ await testDb(TableName.MembershipRole).where({ membershipId: membership.id }).delete();+ await testDb(TableName.Membership).where({ id: membership.id }).delete();};const waitForRevocationRow = async (tokenId: string) => {@@ -174,6 +176,33 @@ const getMaxIdentityAccessTokenTTL = async () => {return maxIdentityAccessTokenTTL;};+const createLegacyAccessTokenWithoutOrgClaims = async (identityId: string) => {+ const tokenId = randomUUID();++ await testDb(TableName.IdentityAccessToken).insert({+ id: tokenId,+ identityId,+ accessTokenTTL: 3600,+ accessTokenMaxTTL: 7200,+ accessTokenNumUses: 0,+ accessTokenNumUsesLimit: 0,+ isAccessTokenRevoked: false,+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ accessTokenPeriod: 0+ } as never);++ return jwt.sign(+ {+ authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,+ identityId,+ identityAccessTokenId: tokenId,+ clientSecretId: ""+ },+ process.env.AUTH_SECRET ?? "something-random",+ { expiresIn: 3600 }+ );+};+// ---------------------------------------------------------------------------// test suite// ---------------------------------------------------------------------------@@ -228,6 +257,42 @@ describe("Identity Access Token — redesigned JWT flow", () => {expect(res.statusCode).toBe(401);});+ test("legacy JWT missing org claims authenticates and renews from its token row", async () => {+ const { identityId } = await createUaIdentity("test-legacy-token-no-org-claims");++ try {+ const legacyToken = await createLegacyAccessTokenWithoutOrgClaims(identityId);+ const legacyDecoded = jwt.decode(legacyToken) as { jti?: string; orgId?: string } | null;+ expect(legacyDecoded).not.toBeNull();+ expect(legacyDecoded!.jti).toBeUndefined();+ expect(legacyDecoded!.orgId).toBeUndefined();++ const authRes = await callDetailsEndpoint(legacyToken);+ expect(authRes.statusCode).toBe(200);++ const renewRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/token/renew",+ body: { accessToken: legacyToken }+ });+ expect(renewRes.statusCode).toBe(200);++ const renewedAccessToken = renewRes.json().accessToken as string;+ const renewedDecoded = jwt.decode(renewedAccessToken) as {+ orgId?: string;+ rootOrgId?: string;+ parentOrgId?: string;+ } | null;+ expect(renewedDecoded).not.toBeNull();+ expect(renewedDecoded!.orgId).toBe(seedData1.organization.id);+ expect(renewedDecoded!.rootOrgId).toBe(seedData1.organization.id);+ expect(renewedDecoded!.parentOrgId).toBe(seedData1.organization.id);+ expect((await callDetailsEndpoint(renewedAccessToken)).statusCode).toBe(200);+ } finally {+ await cleanupIdentityDirect(identityId);+ }+ });+// -------------------------------------------------------------------------// 3. Per-token revoke: revoking a token blocks subsequent requests// -------------------------------------------------------------------------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 125a8fb8c8..0236997213 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@@ -7,7 +7,6 @@ import { AuthTokenType } from "../auth/auth-type";import {TComputeIssuedTtlInput,TCoreTokenClaims,- TFastPathClaims,TIdentityAccessTokenJwtPayload,TMinimalRenewClaims,TRenewableClaims,@@ -53,44 +52,41 @@ export const verifyAccessTokenJwt = (accessToken: string): TIdentityAccessTokenJreturn decoded;};+// Pre-redesign JWTs were signed without `jti`, so `identityAccessTokenId` is the+// stable id we can rely on across both formats. Callers that need the live token+// id read `decoded.jti ?? decoded.identityAccessTokenId`.const hasCoreTokenClaims = (decoded: TIdentityAccessTokenJwtPayload): decoded is TCoreTokenClaims =>- !!decoded.jti && typeof decoded.iat === "number" && !!decoded.identityId;+ typeof decoded.iat === "number" && !!decoded.identityId && !!decoded.identityAccessTokenId;-// Claims required by EVERY renewable JWT (legacy + new format). Legacy tokens-// don't carry the new-format claims; the renew flow loads those from PG instead.+// Baseline assertion shared by every JWT-consuming entry point (auth, renew,+// revoke). Per-flow predicates narrow further.export const assertMinimalRenewClaims = (decoded: TIdentityAccessTokenJwtPayload): TMinimalRenewClaims => {- if (!hasCoreTokenClaims(decoded) || !decoded.identityAccessTokenId) {- throw new UnauthorizedError({ message: "Cannot renew identity access token, please re-authenticate" });- }- return decoded as TMinimalRenewClaims;-};--// New-format JWTs carry these in addition to the minimal claims, letting renew-// run without a PG lookup. False = legacy token, requires a DAL fallback.-export const hasFullRenewClaims = (decoded: TMinimalRenewClaims): decoded is TRenewableClaims => {- return (- !!decoded.authMethod &&- typeof decoded.accessTokenTTL === "number" &&- typeof decoded.accessTokenMaxTTL === "number" &&- typeof decoded.accessTokenPeriod === "number" &&- typeof decoded.creationEpoch === "number"- );-};--export const assertRevocableClaims = (decoded: TIdentityAccessTokenJwtPayload): TRevocableClaims => {- if (!hasCoreTokenClaims(decoded) || !decoded.authMethod || typeof decoded.accessTokenTTL !== "number") {- throw new UnauthorizedError({ message: "Cannot revoke legacy identity access token" });- }- return decoded as TRevocableClaims;-};--export const assertFastPathClaims = (decoded: TIdentityAccessTokenJwtPayload): TFastPathClaims => {- if (!hasCoreTokenClaims(decoded) || !decoded.orgId || !decoded.rootOrgId || !decoded.parentOrgId) {+ if (!hasCoreTokenClaims(decoded)) {throw new UnauthorizedError({ message: "Invalid identity access token claims, please re-authenticate" });}- return decoded as TFastPathClaims;+ return decoded;};+// True when the JWT carries every claim needed to auth/renew without a PG read:+// jti + org claims + TTL/period/creationEpoch budget anchors. Legacy tokens fail+// this and fall through to loadLegacyTokenSource.+export const hasFullRenewClaims = (decoded: TMinimalRenewClaims): decoded is TRenewableClaims =>+ !!decoded.jti &&+ !!decoded.orgId &&+ !!decoded.rootOrgId &&+ !!decoded.parentOrgId &&+ !!decoded.authMethod &&+ typeof decoded.accessTokenTTL === "number" &&+ typeof decoded.accessTokenMaxTTL === "number" &&+ typeof decoded.accessTokenPeriod === "number" &&+ typeof decoded.creationEpoch === "number";++// Revoke only needs the core claims — `assertMinimalRenewClaims` is the same+// check; this alias preserves intent at the call site.+export const assertRevocableClaims = assertMinimalRenewClaims as (+ decoded: TIdentityAccessTokenJwtPayload+) => TRevocableClaims;+// Compute the TTL (seconds) to sign the JWT with.//// Three caps: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 bae1e153bb..0bb6908c1d 100644--- a/backend/src/services/identity-access-token/identity-access-token-service.test.ts+++ b/backend/src/services/identity-access-token/identity-access-token-service.test.ts@@ -54,16 +54,17 @@ const createService = ({const orgDAL = {findEffectiveOrgMembership: vi.fn().mockResolvedValue(membership)};+ const identityAccessTokenDAL = { findOne: vi.fn().mockResolvedValue(tokenRow) };const service = identityAccessTokenServiceFactory({- identityAccessTokenDAL: { findOne: vi.fn().mockResolvedValue(tokenRow) } as never,+ identityAccessTokenDAL: identityAccessTokenDAL as never,identityAccessTokenRevocationDAL: identityAccessTokenRevocationDAL as never,identityDAL: identityDAL as never,orgDAL: orgDAL as never,keyStore: keyStore as never});- return { service, keyStore, identityDAL, orgDAL, identityAccessTokenRevocationDAL };+ return { service, keyStore, identityDAL, orgDAL, identityAccessTokenDAL, identityAccessTokenRevocationDAL };};const createTokenClaims = (@@ -90,23 +91,39 @@ const createTokenClaims = (...overrides});-const signLegacyAccessToken = (overrides: Partial<TIdentityAccessTokenJwtPayload> = {}) =>+const signLegacyUniversalAuthAccessToken = (+ overrides: Partial<TIdentityAccessTokenJwtPayload> = {},+ options: { expiresIn?: number } = { expiresIn: MAX_AGE }+) => {+ const payload = {+ identityId: "identity-id",+ clientSecretId: "",+ identityAccessTokenId: "legacy-token-id",+ authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,+ ...overrides+ };+ const signOptions = options.expiresIn === undefined ? undefined : { expiresIn: options.expiresIn };++ return crypto.jwt().sign(payload, AUTH_SECRET, signOptions);+};++const signLegacyOidcAccessToken = (overrides: Partial<TIdentityAccessTokenJwtPayload> = {}) =>crypto.jwt().sign({identityId: "identity-id",- identityName: "identity-name",- orgId: "org-id",- rootOrgId: "root-org-id",- parentOrgId: "parent-org-id",- clientSecretId: "",identityAccessTokenId: "legacy-token-id",authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,- identityAuth: {},+ identityAuth: {+ oidc: {+ claims: {+ sub: "legacy-sub"+ }+ }+ },...overrides},AUTH_SECRET,{- jwtid: "legacy-token-id",expiresIn: MAX_AGE});@@ -195,6 +212,19 @@ describe("identityAccessTokenServiceFactory", () => {});});+ test("writes per-token revocation to PG for exact legacy tokens", async () => {+ const { service, identityAccessTokenRevocationDAL } = createService();+ const legacyToken = signLegacyUniversalAuthAccessToken();++ await service.revokeAccessToken(legacyToken);++ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({+ id: "legacy-token-id",+ identityId: "identity-id",+ 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) }]@@ -411,20 +441,59 @@ describe("identityAccessTokenServiceFactory", () => {await expect(service.renewAccessToken({ accessToken })).rejects.toThrow("Cannot renew exhausted access token");});- test("authenticates legacy tokens with fast-path claims", async () => {- const { service } = createService();- const legacyToken = signLegacyAccessToken();+ test("authenticates exact legacy Universal Auth tokens from their PG row", async () => {+ const { service, identityAccessTokenDAL, orgDAL } = createService({ tokenRow: createLegacyTokenRow() });+ const legacyToken = signLegacyUniversalAuthAccessToken();const legacyClaims = verifyAccessTokenJwt(legacyToken);+ expect(legacyClaims.jti).toBeUndefined();+ expect(legacyClaims.orgId).toBeUndefined();await expect(service.fnValidateIdentityAccessTokenFast(legacyClaims, "10.0.0.1")).resolves.toMatchObject({identityId: "identity-id",- orgId: "org-id"+ orgId: "org-id",+ rootOrgId: "org-id",+ parentOrgId: "org-id"+ });+ expect(identityAccessTokenDAL.findOne).toHaveBeenCalledWith({ id: "legacy-token-id" });+ expect(orgDAL.findEffectiveOrgMembership).toHaveBeenCalledWith({+ actorType: "identity",+ actorId: "identity-id",+ orgId: "org-id",+ status: "accepted"+ });+ });++ test("preserves legacy method-specific auth details during renewal", async () => {+ const { service } = createService({+ tokenRow: createLegacyTokenRow({ authMethod: IdentityAuthMethod.OIDC_AUTH })+ });+ const legacyToken = signLegacyOidcAccessToken();++ const renewed = await service.renewAccessToken({ accessToken: legacyToken });+ const renewedClaims = verifyAccessTokenJwt(renewed.accessToken);++ expect(renewedClaims.identityAuth).toEqual({+ oidc: {+ claims: {+ sub: "legacy-sub"+ }+ }});});+ test("rejects legacy auth when org claims are missing and the PG row is missing", async () => {+ const { service } = createService({ tokenRow: null });+ const legacyToken = signLegacyUniversalAuthAccessToken();+ const legacyClaims = verifyAccessTokenJwt(legacyToken);++ await expect(service.fnValidateIdentityAccessTokenFast(legacyClaims, "10.0.0.1")).rejects.toThrow(+ "Cannot renew revoked or unknown access token"+ );+ });+test("renews legacy tokens from their PG row into new-format tokens", async () => {const { service } = createService({ tokenRow: createLegacyTokenRow() });- const legacyToken = signLegacyAccessToken();+ const legacyToken = signLegacyUniversalAuthAccessToken();const renewed = await service.renewAccessToken({ accessToken: legacyToken });const renewedClaims = verifyAccessTokenJwt(renewed.accessToken);@@ -443,7 +512,7 @@ describe("identityAccessTokenServiceFactory", () => {test("rejects legacy renewal when the PG row is missing", async () => {const { service } = createService({ tokenRow: null });- const legacyToken = signLegacyAccessToken();+ const legacyToken = signLegacyUniversalAuthAccessToken();await expect(service.renewAccessToken({ accessToken: legacyToken })).rejects.toThrow("Cannot renew revoked or unknown access token"@@ -454,7 +523,7 @@ describe("identityAccessTokenServiceFactory", () => {const { service } = createService({tokenRow: createLegacyTokenRow({ isAccessTokenRevoked: true })});- const legacyToken = signLegacyAccessToken();+ const legacyToken = signLegacyUniversalAuthAccessToken();await expect(service.renewAccessToken({ accessToken: legacyToken })).rejects.toThrow("Cannot renew revoked or unknown access token"@@ -469,7 +538,7 @@ describe("identityAccessTokenServiceFactory", () => {createdAt: new Date((NOW_SECONDS - 3600) * 1000)})});- const legacyToken = signLegacyAccessToken();+ const legacyToken = signLegacyUniversalAuthAccessToken();await expect(service.renewAccessToken({ accessToken: legacyToken })).rejects.toThrow("has reached its max TTL");});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 62b51423ff..1a6425c033 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@@ -12,7 +12,6 @@ import { TIdentityDALFactory } from "../identity/identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { TIdentityAccessTokenDALFactory } from "./identity-access-token-dal";import {- assertFastPathClaims,assertMinimalRenewClaims,assertRevocableClaims,computeIssuedTtl,@@ -28,6 +27,7 @@ import {TAWSAuthDetails,TIdentityAccessTokenJwtPayload,TKubernetesAuthDetails,+ TMinimalRenewClaims,TOidcAuthDetails,TRenewAccessTokenDTO,TRenewSource@@ -204,9 +204,53 @@ export const identityAccessTokenServiceFactory = ({return { accessToken, identityAccessToken };};+ // Loads the auth/renew context for a legacy JWT from PG. Legacy tokens predate+ // the lazy-insert model and always have a row; revoked or missing rows mean+ // the token can't be safely upgraded. Auth uses a subset of these fields.+ const loadLegacyTokenSource = async (decoded: TMinimalRenewClaims): Promise<TRenewSource> => {+ const row = await identityAccessTokenDAL.findOne({ id: decoded.identityAccessTokenId });+ if (!row || row.isAccessTokenRevoked) {+ throw new UnauthorizedError({ message: "Cannot renew revoked or unknown access token" });+ }+ const fallbackOrgId = decoded.orgId ?? row.identityOrgId ?? "";+ return {+ authMethod: row.authMethod as IdentityAuthMethod,+ accessTokenTTL: row.accessTokenTTL,+ accessTokenMaxTTL: row.accessTokenMaxTTL,+ accessTokenPeriod: row.accessTokenPeriod,+ // Anchor the upgraded JWT's maxTTL budget on the row's createdAt so the+ // legacy lifetime carries over without a free renewal-time extension.+ creationEpoch: Math.floor(row.createdAt.getTime() / 1000),+ identityName: row.identityName ?? decoded.identityName ?? "",+ orgId: fallbackOrgId,+ rootOrgId: decoded.rootOrgId ?? fallbackOrgId,+ parentOrgId: decoded.parentOrgId ?? fallbackOrgId,+ clientSecretId: decoded.clientSecretId ?? "",+ numUsesLimit: row.accessTokenNumUsesLimit,+ identityAuth: decoded.identityAuth+ };+ };+const fnValidateIdentityAccessTokenFast = async (rawToken: TIdentityAccessTokenJwtPayload, ipAddress?: string) => {const appCfg = getConfig();- const token = assertFastPathClaims(rawToken);+ const token = assertMinimalRenewClaims(rawToken);+ const tokenId = token.jti ?? token.identityAccessTokenId;+ const source: TRenewSource = hasFullRenewClaims(token)+ ? {+ authMethod: token.authMethod,+ accessTokenTTL: token.accessTokenTTL,+ accessTokenMaxTTL: token.accessTokenMaxTTL,+ accessTokenPeriod: token.accessTokenPeriod,+ creationEpoch: token.creationEpoch,+ identityName: token.identityName ?? "",+ orgId: token.orgId,+ rootOrgId: token.rootOrgId,+ parentOrgId: token.parentOrgId,+ clientSecretId: token.clientSecretId,+ numUsesLimit: token.numUsesLimit ?? 0,+ identityAuth: token.identityAuth+ }+ : await loadLegacyTokenSource(token);// Legacy tokens (pre-redesign) were signed without `expiresIn` so the JWT// has no `exp`. For those, enforce the `iat + MAX_AGE` ceiling here.@@ -218,11 +262,11 @@ export const identityAccessTokenServiceFactory = ({const [, usesRemainingRaw] = await Promise.all([assertTokenIsNotRevoked({- tokenId: token.jti,+ tokenId,identityId: token.identityId,issuedAtMs}),- keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, token.jti))+ keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, tokenId))]);// null means unlimited or the Redis counter was lost; <= 0 means exhausted.@@ -231,19 +275,16 @@ export const identityAccessTokenServiceFactory = ({throw new UnauthorizedError({ message: "Failed to authorize: token usage limit reached" });}- if (token.numUsesLimit && token.numUsesLimit > 0) {+ const numUsesLimit = token.numUsesLimit ?? source.numUsesLimit;++ if (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 setUsesRemaining(- token.identityId,- token.jti,- token.numUsesLimit - 1,- appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE- );+ await setUsesRemaining(token.identityId, tokenId, numUsesLimit - 1, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);} else {const remaining = await keyStore.incrementBy(- KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, token.jti),+ KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, tokenId),-1);if (remaining < 0) {@@ -252,11 +293,8 @@ export const identityAccessTokenServiceFactory = ({}}- if (ipAddress && token.authMethod) {- const trustedIps = await identityDAL.getTrustedIpsByAuthMethod(- token.identityId,- token.authMethod as IdentityAuthMethod- );+ if (ipAddress) {+ const trustedIps = await identityDAL.getTrustedIpsByAuthMethod(token.identityId, source.authMethod);if (hasNonWildcardTrustedIps(trustedIps as TIp[] | null | undefined)) {checkIPAgainstBlocklist({ipAddress,@@ -268,7 +306,7 @@ export const identityAccessTokenServiceFactory = ({const orgMembership = await orgDAL.findEffectiveOrgMembership({actorType: ActorType.IDENTITY,actorId: token.identityId,- orgId: token.orgId,+ orgId: source.orgId,status: OrgMembershipStatus.Accepted});if (!orgMembership) {@@ -280,41 +318,13 @@ export const identityAccessTokenServiceFactory = ({return {identityId: token.identityId,- identityName: token.identityName ?? "",- name: token.identityName ?? "",- orgId: token.orgId,- rootOrgId: token.rootOrgId,- parentOrgId: token.parentOrgId,+ identityName: source.identityName,+ name: source.identityName,+ orgId: source.orgId,+ rootOrgId: source.rootOrgId,+ parentOrgId: source.parentOrgId,orgName: undefined as string | undefined,- authMethod: (token.authMethod ?? "") as string- };- };-- // Loads the renewal source for a legacy JWT from PG. Legacy tokens predate- // the lazy-insert model and always have a row; revoked or missing rows mean- // the token can't be safely upgraded.- const loadLegacyRenewSource = async (- decoded: TIdentityAccessTokenJwtPayload & { identityAccessTokenId: string }- ): Promise<TRenewSource> => {- const row = await identityAccessTokenDAL.findOne({ id: decoded.identityAccessTokenId });- if (!row || row.isAccessTokenRevoked) {- throw new UnauthorizedError({ message: "Cannot renew revoked or unknown access token" });- }- const fallbackOrgId = decoded.orgId ?? row.identityOrgId ?? "";- return {- authMethod: row.authMethod as IdentityAuthMethod,- accessTokenTTL: row.accessTokenTTL,- accessTokenMaxTTL: row.accessTokenMaxTTL,- accessTokenPeriod: row.accessTokenPeriod,- // Anchor the upgraded JWT's maxTTL budget on the row's createdAt so the- // legacy lifetime carries over without a free renewal-time extension.- creationEpoch: Math.floor(row.createdAt.getTime() / 1000),- identityName: row.identityName ?? decoded.identityName ?? "",- orgId: fallbackOrgId,- rootOrgId: decoded.rootOrgId ?? fallbackOrgId,- parentOrgId: decoded.parentOrgId ?? fallbackOrgId,- clientSecretId: decoded.clientSecretId ?? "",- identityAuth: decoded.identityAuth+ authMethod: source.authMethod};};@@ -337,24 +347,25 @@ export const identityAccessTokenServiceFactory = ({accessTokenPeriod: decodedToken.accessTokenPeriod,creationEpoch: decodedToken.creationEpoch,identityName: decodedToken.identityName ?? "",- orgId: decodedToken.orgId ?? "",- rootOrgId: decodedToken.rootOrgId ?? decodedToken.orgId ?? "",- parentOrgId: decodedToken.parentOrgId ?? decodedToken.orgId ?? "",+ orgId: decodedToken.orgId,+ rootOrgId: decodedToken.rootOrgId,+ parentOrgId: decodedToken.parentOrgId,clientSecretId: decodedToken.clientSecretId,+ numUsesLimit: decodedToken.numUsesLimit ?? 0,identityAuth: decodedToken.identityAuth}- : await loadLegacyRenewSource(decodedToken);+ : await loadLegacyTokenSource(decodedToken);- const { jti } = decodedToken;+ const tokenId = decodedToken.jti ?? decodedToken.identityAccessTokenId;const [, existingUsesRemainingRaw] = await Promise.all([assertTokenIsNotRevoked({- tokenId: jti,+ tokenId,identityId: decodedToken.identityId,issuedAtMs: decodedToken.iat * 1000,messagePrefix: "Cannot renew"}),- keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(decodedToken.identityId, jti))+ keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(decodedToken.identityId, tokenId))]);const existingRemaining = parseUsesRemaining(existingUsesRemainingRaw);@@ -378,7 +389,7 @@ export const identityAccessTokenServiceFactory = ({throw new UnauthorizedError({ message: "Cannot renew: identity access token has reached its max TTL" });}- const numUsesLimit = decodedToken.numUsesLimit ?? 0;+ const numUsesLimit = decodedToken.numUsesLimit ?? source.numUsesLimit;const ipRestrictionEnabled = Boolean(decodedToken.ipRestrictionEnabled);const { accessToken: renewedToken } = signIdentityAccessToken({@@ -400,11 +411,11 @@ export const identityAccessTokenServiceFactory = ({creationEpoch: source.creationEpoch});- // Renewed JWT keeps the same `jti`; PG revocation already applies. Reseed+ // Renewed JWT keeps the same token id; 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 setUsesRemaining(decodedToken.identityId, jti, remainingUses, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);+ await setUsesRemaining(decodedToken.identityId, tokenId, remainingUses, appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);}return {@@ -418,11 +429,12 @@ export const identityAccessTokenServiceFactory = ({const appCfg = getConfig();const decodedToken = assertRevocableClaims(verifyAccessTokenJwt(accessToken));- const { jti, identityId } = decodedToken;+ const { identityId } = decodedToken;+ const tokenId = decodedToken.jti ?? decodedToken.identityAccessTokenId;const expiresAt = new Date((decodedToken.exp ?? decodedToken.iat + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE) * 1000);await identityAccessTokenRevocationDAL.insertRevocation({- id: jti,+ id: tokenId,identityId,expiresAt});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 0167a81efc..6fa3a15357 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@@ -63,40 +63,37 @@ export type TIdentityAccessTokenJwtPayload = {};};-// Claims shared by every validated JWT path — the common core all three assert-// helpers require before they check their own additional fields.+// Claims present on every JWT we accept (legacy + new format). Pre-redesign+// JWTs lacked `jti` but always carried `identityAccessTokenId`, so that's the+// stable token id across both formats.export type TCoreTokenClaims = TIdentityAccessTokenJwtPayload & {- jti: string;iat: number;identityId: string;-};--// Always present on legacy and new-format renewable JWTs. Renewals fall back-// to PG when the new-format claims (TRenewableClaims) aren't all present.-export type TMinimalRenewClaims = TCoreTokenClaims & {identityAccessTokenId: string;};-// New-format JWTs carry these in addition to TMinimalRenewClaims, letting renew-// run without a PG read. `creationEpoch` anchors the maxTTL budget across renewals.+// Same shape as core; named here for call-site clarity in the renew flow.+export type TMinimalRenewClaims = TCoreTokenClaims;++// Same shape as core; named here for call-site clarity in the revoke flow.+export type TRevocableClaims = TCoreTokenClaims;++// New-format JWTs carry every claim needed to auth/renew without a PG read.+// `creationEpoch` anchors the maxTTL budget across renewals.export type TRenewableClaims = TMinimalRenewClaims & {+ jti: string;authMethod: IdentityAuthMethod;+ orgId: string;+ rootOrgId: string;+ parentOrgId: string;accessTokenTTL: number;accessTokenMaxTTL: number;accessTokenPeriod: number;creationEpoch: number;};-// Claims required by the hot-path validator (fnValidateIdentityAccessTokenFast).-export type TFastPathClaims = TCoreTokenClaims & {- orgId: string;- rootOrgId: string;- parentOrgId: string;-};--// Resolved renewal source — either parsed from new-format claims or loaded from-// PG for legacy upgrade. Same shape regardless of origin so the rest of renew-// is path-agnostic.+// Resolved auth/renew context — parsed from new-format claims or loaded from+// PG for legacy tokens. Auth uses a subset; renew uses every field.export type TRenewSource = {authMethod: IdentityAuthMethod;accessTokenTTL: number;@@ -108,14 +105,10 @@ export type TRenewSource = {rootOrgId: string;parentOrgId: string;clientSecretId: string;+ numUsesLimit: number;identityAuth?: TIdentityAccessTokenJwtPayload["identityAuth"];};-export type TRevocableClaims = TCoreTokenClaims & {- authMethod: IdentityAuthMethod;- accessTokenTTL: number;-};-export type TComputeIssuedTtlInput = {requestedTTL: number;maxTTL: number;