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): rework access tokens to prevent unbounded growth in db
Tre Dubrava5c0bd84d8f52
diff --git a/.gitignore b/.gitignoreindex 35e51be3dd..dc5f528060 100644--- a/.gitignore+++ b/.gitignore@@ -64,6 +64,7 @@ yarn-error.log*# Editor specific.vscode/*.idea/*+.claude/frontend-builddiff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex f5c2a3d8c4..053339d9fb 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -77,6 +77,41 @@ 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/e2e-test/routes/v1/identity-access-token-redesign.spec.ts b/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.tsnew file mode 100644index 0000000000..5ffafcc803--- /dev/null+++ b/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts@@ -0,0 +1,390 @@+/**+ * E2E tests for the redesigned identity-access-token auth flow.+ *+ * Prerequisites (handled by vitest-environment-knex.ts):+ * - testServer: running Fastify instance+ * - jwtAuthToken: pre-authenticated admin JWT (user session)+ * - testDb: knex instance+ *+ * These tests create and tear down temporary identities so they do not+ * depend on or mutate the seeded machine identity.+ */++import jwt from "jsonwebtoken";++import { AccessScope, OrgMembershipRole, TableName } from "@app/db/schemas";+import { seedData1 } from "@app/db/seed-data";+import { AuthTokenType } from "@app/services/auth/auth-type";++// ---------------------------------------------------------------------------+// helpers+// ---------------------------------------------------------------------------++/** Create a temporary identity and attach Universal Auth to it. */+const createUaIdentity = async (+ name: string,+ uaConfig: {+ accessTokenTTL?: number;+ accessTokenMaxTTL?: number;+ accessTokenNumUsesLimit?: number;+ accessTokenTrustedIps?: Array<{ ipAddress: string }>;+ } = {}+) => {+ // 1. Create bare identity+ const createRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/identities",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {+ name,+ role: OrgMembershipRole.Member,+ organizationId: seedData1.organization.id+ }+ });+ expect(createRes.statusCode).toBe(200);+ const identity = createRes.json().identity as { id: string };++ const ttl = uaConfig.accessTokenTTL ?? 2592000;+ const maxTtl = uaConfig.accessTokenMaxTTL ?? ttl;++ // 2. Attach Universal Auth+ const attachRes = await testServer.inject({+ method: "POST",+ url: `/api/v1/auth/universal-auth/identities/${identity.id}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {+ accessTokenTTL: ttl,+ accessTokenMaxTTL: maxTtl,+ accessTokenNumUsesLimit: uaConfig.accessTokenNumUsesLimit ?? 0,+ accessTokenTrustedIps: uaConfig.accessTokenTrustedIps+ }+ });+ expect(attachRes.statusCode).toBe(200);++ // 3. Create a client secret+ const csRes = await testServer.inject({+ method: "POST",+ url: `/api/v1/auth/universal-auth/identities/${identity.id}/client-secrets`,+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {}+ });+ expect(csRes.statusCode).toBe(200);+ const { clientSecret } = csRes.json();+ const clientId = attachRes.json().identityUniversalAuth.clientId as string;++ return { identityId: identity.id, clientId, clientSecret };+};++/** Log in as a Universal Auth identity and return the access token. */+const loginWithUa = async (clientId: string, clientSecret: string) => {+ const loginRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/universal-auth/login",+ body: { clientId, clientSecret }+ });+ expect(loginRes.statusCode).toBe(200);+ return loginRes.json().accessToken as string;+};++/** Delete a temporary identity (cleanup). */+const deleteIdentity = async (identityId: string) => {+ await testServer.inject({+ method: "DELETE",+ url: `/api/v1/identities/${identityId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+};++const cleanupIdentityDirect = async (identityId: string) => {+ await testDb(TableName.Identity).where({ id: identityId }).delete();+};++const updateUaAccessTokenTrustedIps = async (identityId: string, ips: Array<{ ipAddress: string }>) => {+ const res = await testServer.inject({+ method: "PATCH",+ url: `/api/v1/auth/universal-auth/identities/${identityId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: {+ accessTokenTrustedIps: ips+ }+ });+ expect(res.statusCode).toBe(200);+};++const deleteOrgIdentityMembership = async (identityId: string) => {+ const membership = await testDb(TableName.Membership)+ .where({+ scope: AccessScope.Organization,+ scopeOrgId: seedData1.organization.id,+ actorIdentityId: identityId+ })+ .first<{ id: string }>();++ expect(membership).toBeDefined();++ await testDb(TableName.MembershipRole).where({ membershipId: membership!.id }).delete();+ await testDb(TableName.Membership).where({ id: membership!.id }).delete();+};++const waitForRevocationRow = async (tokenId: string) => {+ const deadline = Date.now() + 10_000;++ while (Date.now() < deadline) {+ // eslint-disable-next-line no-await-in-loop+ const row = await testDb(TableName.IdentityAccessTokenRevocation)+ .where({ id: tokenId })+ .first<{ id: string; identityId: string; expiresAt: Date }>();++ if (row) {+ return row;+ }++ // eslint-disable-next-line no-await-in-loop+ await new Promise((resolve) => {+ setTimeout(resolve, 100);+ });+ }++ throw new Error(`Timed out waiting for identity access token revocation row ${tokenId}`);+};++/**+ * Hit a lightweight authenticated endpoint that accepts IDENTITY_ACCESS_TOKEN.+ * GET /api/v1/identities/details only accepts identity tokens — ideal for+ * validating whether a given token is currently authorised.+ */+const callDetailsEndpoint = (accessToken: string, ip?: string) =>+ testServer.inject({+ method: "GET",+ url: "/api/v1/identities/details",+ headers: { authorization: `Bearer ${accessToken}`, ...(ip ? { "x-forwarded-for": ip } : {}) }+ });++const getMaxIdentityAccessTokenTTL = async () => {+ const statusRes = await testServer.inject({+ method: "GET",+ url: "/api/status"+ });++ expect(statusRes.statusCode).toBe(200);++ const { maxIdentityAccessTokenTTL } = statusRes.json();+ expect(typeof maxIdentityAccessTokenTTL).toBe("number");++ return maxIdentityAccessTokenTTL;+};++// ---------------------------------------------------------------------------+// test suite+// ---------------------------------------------------------------------------++describe("Identity Access Token — redesigned JWT flow", () => {+ // -------------------------------------------------------------------------+ // 1. Issuance caps TTL to MAX_MACHINE_IDENTITY_TOKEN_AGE when accessTokenTTL=0+ // -------------------------------------------------------------------------+ test("issuance with accessTokenTTL=0 caps exp to MAX_MACHINE_IDENTITY_TOKEN_AGE", async () => {+ const maxIdentityAccessTokenTTL = await getMaxIdentityAccessTokenTTL();+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-ttl-cap", {+ accessTokenTTL: 0,+ accessTokenMaxTTL: 0+ });++ try {+ const accessToken = await loginWithUa(clientId, clientSecret);++ const decoded = jwt.decode(accessToken) as { iat: number; exp: number } | null;+ expect(decoded).not.toBeNull();+ expect(typeof decoded!.iat).toBe("number");+ expect(typeof decoded!.exp).toBe("number");++ const issuedTtl = decoded!.exp - decoded!.iat;+ // The issued TTL should be at most MAX_MACHINE_IDENTITY_TOKEN_AGE.+ // Allow 2 s of drift for test execution latency.+ expect(issuedTtl).toBeLessThanOrEqual(maxIdentityAccessTokenTTL);+ expect(issuedTtl).toBeGreaterThanOrEqual(maxIdentityAccessTokenTTL - 2);+ } finally {+ await deleteIdentity(identityId);+ }+ });++ // -------------------------------------------------------------------------+ // 2. Legacy JWT (missing jti / orgId) is rejected with 401+ // -------------------------------------------------------------------------+ test("legacy JWT missing jti and orgId is rejected with 401", async () => {+ // Hand-craft a JWT that looks like the old design: correct authTokenType+ // but none of the new required claims (jti is absent, orgId absent).+ const legacyPayload = {+ authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,+ identityId: "00000000-0000-0000-0000-000000000001",+ identityAccessTokenId: "00000000-0000-0000-0000-000000000002",+ clientSecretId: "00000000-0000-0000-0000-000000000003",+ identityAuth: {}+ // Deliberately omitting: jti, orgId, rootOrgId, parentOrgId, iat (numeric)+ };++ const legacyToken = jwt.sign(legacyPayload, process.env.AUTH_SECRET ?? "something-random", { expiresIn: 3600 });++ const res = await callDetailsEndpoint(legacyToken);+ expect(res.statusCode).toBe(401);+ });++ // -------------------------------------------------------------------------+ // 3. Per-token revoke: revoking a token blocks subsequent requests+ // -------------------------------------------------------------------------+ test("revoking a token with POST /api/v1/auth/token/revoke causes subsequent 401", async () => {+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-per-token-revoke");++ try {+ const accessToken = await loginWithUa(clientId, clientSecret);++ // Token is valid before revocation.+ const preRevokeRes = await callDetailsEndpoint(accessToken);+ expect(preRevokeRes.statusCode).toBe(200);++ // Revoke.+ const revokeRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/token/revoke",+ body: { accessToken }+ });+ expect(revokeRes.statusCode).toBe(200);++ // Token must now be rejected.+ const postRevokeRes = await callDetailsEndpoint(accessToken);+ expect(postRevokeRes.statusCode).toBe(401);+ } finally {+ await deleteIdentity(identityId);+ }+ });++ // -------------------------------------------------------------------------+ // 4. Identity-wide revoke: deleting identity invalidates all its tokens+ // -------------------------------------------------------------------------+ test("deleting an identity revokes all its active tokens", async () => {+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-identity-delete-revoke");++ // Issue two independent tokens for the same identity.+ const tokenA = await loginWithUa(clientId, clientSecret);+ const tokenB = await loginWithUa(clientId, clientSecret);++ // Both should be valid before deletion.+ expect((await callDetailsEndpoint(tokenA)).statusCode).toBe(200);+ expect((await callDetailsEndpoint(tokenB)).statusCode).toBe(200);++ // Delete the identity (this also calls revokeAllTokensForIdentity internally).+ const deleteRes = await testServer.inject({+ method: "DELETE",+ url: `/api/v1/identities/${identityId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ expect(deleteRes.statusCode).toBe(200);++ // Both previously valid tokens must now be rejected.+ expect((await callDetailsEndpoint(tokenA)).statusCode).toBe(401);+ expect((await callDetailsEndpoint(tokenB)).statusCode).toBe(401);+ });++ // -------------------------------------------------------------------------+ // 5. Usage-limit: accessTokenNumUsesLimit=2 allows 2 calls, blocks the 3rd+ // -------------------------------------------------------------------------+ test("usage-limited token (numUsesLimit=2) is rejected after two successful uses", async () => {+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-usage-limit", {+ accessTokenNumUsesLimit: 2+ });++ try {+ const accessToken = await loginWithUa(clientId, clientSecret);++ // First use — should succeed.+ const res1 = await callDetailsEndpoint(accessToken);+ expect(res1.statusCode).toBe(200);++ // Second use — should succeed.+ const res2 = await callDetailsEndpoint(accessToken);+ expect(res2.statusCode).toBe(200);++ // Third use — limit exhausted, must be rejected.+ const res3 = await callDetailsEndpoint(accessToken);+ expect(res3.statusCode).toBe(401);+ } finally {+ await deleteIdentity(identityId);+ }+ });++ // -------------------------------------------------------------------------+ // 6. Trusted-IP config changes invalidate already issued tokens+ // -------------------------------------------------------------------------+ test("trusted IP changes reject old tokens from disallowed IPs", async () => {+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-stale-trusted-ip", {+ accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]+ });++ try {+ const accessToken = await loginWithUa(clientId, clientSecret);++ expect((await callDetailsEndpoint(accessToken)).statusCode).toBe(200);++ await updateUaAccessTokenTrustedIps(identityId, [{ ipAddress: "10.0.0.0/24" }]);++ expect((await callDetailsEndpoint(accessToken, "192.168.1.1")).statusCode).toBe(403);+ } finally {+ await deleteIdentity(identityId);+ }+ });++ // -------------------------------------------------------------------------+ // 7. Org membership changes invalidate already issued tokens+ // -------------------------------------------------------------------------+ test("org membership removal invalidates old tokens", async () => {+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-stale-org-membership");++ try {+ const accessToken = await loginWithUa(clientId, clientSecret);++ expect((await callDetailsEndpoint(accessToken)).statusCode).toBe(200);++ await deleteOrgIdentityMembership(identityId);++ expect((await callDetailsEndpoint(accessToken)).statusCode).toBe(401);+ } finally {+ await cleanupIdentityDirect(identityId);+ }+ });++ // -------------------------------------------------------------------------+ // 8. Per-token revocation survives Redis loss through PG hydration+ // -------------------------------------------------------------------------+ test("zero-TTL revocation survives Redis loss through PG hydration", async () => {+ const { identityId, clientId, clientSecret } = await createUaIdentity("test-revoke-hydrate", {+ accessTokenTTL: 0,+ accessTokenMaxTTL: 0+ });++ try {+ const accessToken = await loginWithUa(clientId, clientSecret);+ const decoded = jwt.decode(accessToken) as { exp: number; identityAccessTokenId: string } | null;+ expect(decoded).not.toBeNull();+ expect(typeof decoded!.exp).toBe("number");+ expect(typeof decoded!.identityAccessTokenId).toBe("string");++ const revokeRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/auth/token/revoke",+ body: { accessToken }+ });+ expect(revokeRes.statusCode).toBe(200);++ const revocation = await waitForRevocationRow(decoded!.identityAccessTokenId);+ const expectedExpiresAtMs = decoded!.exp * 1000;+ expect(revocation.expiresAt.getTime()).toBeGreaterThan(Date.now());+ expect(Math.abs(revocation.expiresAt.getTime() - expectedExpiresAtMs)).toBeLessThanOrEqual(2_000);++ await testRedis.flushdb("SYNC");+ await (globalThis as any).testServices.identityAccessToken.hydrateRedisFromPg();++ expect((await callDetailsEndpoint(accessToken)).statusCode).toBe(401);+ } finally {+ await cleanupIdentityDirect(identityId);+ }+ });+});diff --git a/backend/e2e-test/vitest-environment-knex.ts b/backend/e2e-test/vitest-environment-knex.tsindex a1d3b7d49d..8205b98901 100644--- a/backend/e2e-test/vitest-environment-knex.ts+++ b/backend/e2e-test/vitest-environment-knex.ts@@ -102,6 +102,8 @@ export default {// @ts-expect-error typeglobalThis.testDb = db;// @ts-expect-error type+ globalThis.testRedis = redis;+ // @ts-expect-error typeglobalThis.testQueue = queue;// @ts-expect-error typeglobalThis.testSuperAdminDAL = superAdminDAL;@@ -139,6 +141,8 @@ export default {// @ts-expect-error typedelete globalThis.testServer;// @ts-expect-error type+ delete globalThis.testRedis;+ // @ts-expect-error typedelete globalThis.testSuperAdminDAL;// @ts-expect-error typedelete globalThis.jwtAuthToken;diff --git a/backend/src/@types/fastify-zod.d.ts b/backend/src/@types/fastify-zod.d.tsindex 91cd006059..7610d499d9 100644--- a/backend/src/@types/fastify-zod.d.ts+++ b/backend/src/@types/fastify-zod.d.ts@@ -1,4 +1,6 @@import { FastifyInstance, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault } from "fastify";+import type { Cluster, Redis } from "ioredis";+import type { Knex } from "knex";import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";import { CustomLogger } from "@app/lib/logger/logger";@@ -17,6 +19,8 @@ declare global {// used only for testingconst testServer: FastifyZodProvider;+ const testDb: Knex;+ const testRedis: Redis | Cluster;const testSuperAdminDAL: TSuperAdminDALFactory;const testKmsRootConfigDAL: TKmsRootConfigDALFactory;const testHsmService: THsmServiceFactory;diff --git a/backend/src/@types/winrm-client.d.ts b/backend/src/@types/winrm-client.d.tsnew file mode 100644index 0000000000..e265335ee5--- /dev/null+++ b/backend/src/@types/winrm-client.d.ts@@ -0,0 +1,24 @@+declare module "winrm-client" {+ export function runPowershell(+ command: string,+ host: string,+ username: string,+ password: string,+ port: number,+ useHttps?: boolean,+ rejectUnauthorized?: boolean,+ caCert?: string,+ tlsServerName?: string+ ): Promise<string>;++ export function runCommand(+ command: string,+ host: string,+ username: string,+ password: string,+ port: number,+ isPowershell?: boolean,+ useHttps?: boolean,+ rejectUnauthorized?: boolean+ ): Promise<string>;+}diff --git a/backend/src/db/migrations/20260428145237_identity-access-token-revocations.ts b/backend/src/db/migrations/20260428145237_identity-access-token-revocations.tsnew file mode 100644index 0000000000..3f18ae2bdc--- /dev/null+++ b/backend/src/db/migrations/20260428145237_identity-access-token-revocations.ts@@ -0,0 +1,30 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.IdentityAccessTokenRevocation)) {+ return;+ }++ await knex.schema.createTable(TableName.IdentityAccessTokenRevocation, (t) => {+ t.uuid("id").primary();+ t.uuid("identityId").notNullable();+ t.timestamp("expiresAt", { useTz: true }).notNullable();+ // Populated for identity-wide revoke-all markers (id == identityId);+ // null for per-token revocations. Stored so hydration can replay the+ // exact revocation timestamp rather than falling back to createdAt+ // (which reflects BullMQ job execution time, not the revocation call).+ t.timestamp("revokedAt", { useTz: true }).nullable();+ t.timestamps(true, true, true);+ t.index("expiresAt");+ });++ await createOnUpdateTrigger(knex, TableName.IdentityAccessTokenRevocation);+}++export async function down(knex: Knex): Promise<void> {+ await dropOnUpdateTrigger(knex, TableName.IdentityAccessTokenRevocation);+ await knex.schema.dropTableIfExists(TableName.IdentityAccessTokenRevocation);+}diff --git a/backend/src/db/schemas/identity-access-token-revocations.ts b/backend/src/db/schemas/identity-access-token-revocations.tsnew file mode 100644index 0000000000..583f70a418--- /dev/null+++ b/backend/src/db/schemas/identity-access-token-revocations.ts@@ -0,0 +1,26 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const IdentityAccessTokenRevocationsSchema = z.object({+ id: z.string().uuid(),+ identityId: z.string().uuid(),+ expiresAt: z.date(),+ revokedAt: z.date().nullable().optional(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TIdentityAccessTokenRevocations = z.infer<typeof IdentityAccessTokenRevocationsSchema>;+export type TIdentityAccessTokenRevocationsInsert = Omit<+ z.input<typeof IdentityAccessTokenRevocationsSchema>,+ TImmutableDBKeys+>;+export type TIdentityAccessTokenRevocationsUpdate = Partial<+ Omit<z.input<typeof IdentityAccessTokenRevocationsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 8ac69fffb7..5c4856b7a7 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -65,6 +65,7 @@ export * from "./group-project-membership-roles";export * from "./group-project-memberships";export * from "./groups";export * from "./identities";+export * from "./identity-access-token-revocations";export * from "./identity-access-tokens";export * from "./identity-alicloud-auths";export * from "./identity-aws-auths";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 5eec2ab6be..815d66989a 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -93,6 +93,7 @@ export enum TableName {Webhook = "webhooks",Identity = "identities",IdentityAccessToken = "identity_access_tokens",+ IdentityAccessTokenRevocation = "identity_access_token_revocations",IdentityTokenAuth = "identity_token_auths",IdentityUniversalAuth = "identity_universal_auths",IdentityKubernetesAuth = "identity_kubernetes_auths",diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex d44006c1c5..8ce2dbb503 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -63,6 +63,11 @@ 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,ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`,GatewayIdentityCredential: (identityId: string) => `gateway-credentials:${identityId}`,ActiveSSEConnectionsSet: (projectId: string, identityId: string) =>@@ -125,6 +130,14 @@ 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,@@ -210,6 +223,10 @@ 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>;@@ -354,6 +371,32 @@ 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);@@ -453,6 +496,10 @@ 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 55a09997c1..08d0bfa72c 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -75,6 +75,41 @@ 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/lib/config/env.ts b/backend/src/lib/config/env.tsindex af23082a90..6f8a6b2423 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -238,6 +238,9 @@ const envSchema = zJWT_INVITE_LIFETIME: zpStr(z.string().default("1d")),JWT_MFA_LIFETIME: zpStr(z.string().default("5m")),JWT_PROVIDER_AUTH_LIFETIME: zpStr(z.string().default("15m")),+ // Server-enforced ceiling on identity access token lifetime (in seconds). Caps `exp`+ // at issuance and renewal so machine-identity JWTs cannot be immortal.+ MAX_MACHINE_IDENTITY_TOKEN_AGE: zpStr(z.coerce.number().int().positive().default(7_776_000)),// OauthCLIENT_ID_GOOGLE_LOGIN: zpStr(z.string().optional()),CLIENT_SECRET_GOOGLE_LOGIN: zpStr(z.string().optional()),diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 784c41f5dc..8611793ce5 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -105,7 +105,8 @@ export enum QueueName {PamDiscoveryScan = "pam-discovery-scan",CaAutoRenewal = "ca-auto-renewal",CertificateCleanup = "certificate-cleanup",- DigiCertOrderPolling = "digicert-order-polling"+ DigiCertOrderPolling = "digicert-order-polling",+ IdentityAccessTokenPgMirror = "identity-access-token-pg-mirror"}export enum QueueJobs {@@ -177,7 +178,9 @@ export enum QueueJobs {CaAdcsInstall = "ca-adcs-install-job",CertificateCleanup = "certificate-cleanup-job",DailySecretSyncRetry = "daily-secret-sync-retry-job",- DigiCertOrderPolling = "digicert-order-polling-job"+ DigiCertOrderPolling = "digicert-order-polling-job",+ IdentityAccessTokenPgMirrorRevokeToken = "identity-access-token-pg-mirror-revoke-token",+ IdentityAccessTokenPgMirrorRevokeAll = "identity-access-token-pg-mirror-revoke-all"}export type TQueueOptions = {@@ -551,6 +554,24 @@ 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/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex 378a23ea18..8f11dfc570 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -266,7 +266,10 @@ export const injectIdentity = fp(break;}case AuthMode.IDENTITY_ACCESS_TOKEN: {- const identity = await server.services.identityAccessToken.fnValidateIdentityAccessToken(token, req.realIp);+ const identity = await server.services.identityAccessToken.fnValidateIdentityAccessTokenFast(+ token,+ req.realIp+ );const serverCfg = await getServerCfg();requestContext.set(RequestContextKey.OrgId, identity.orgId);requestContext.set(RequestContextKey.OrgName, identity.orgName);diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex f2cb01f82c..413715c787 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -306,6 +306,8 @@ 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";import { identityAliCloudAuthServiceFactory } from "@app/services/identity-alicloud-auth/identity-alicloud-auth-service";@@ -554,6 +556,7 @@ export const registerRoutes = async (const identityV2DAL = identityV2DALFactory(db);const identityMetadataDAL = identityMetadataDALFactory(db);const identityAccessTokenDAL = identityAccessTokenDALFactory(db);+ const identityAccessTokenRevocationDAL = identityAccessTokenRevocationDALFactory(db);const identityOrgMembershipDAL = identityOrgDALFactory(db);const identityGroupMembershipDAL = identityGroupMembershipDALFactory(db);const identityProjectDAL = identityProjectDALFactory(db);@@ -1875,6 +1878,20 @@ export const registerRoutes = async (membershipRoleDAL});+ const identityAccessTokenQueue = identityAccessTokenQueueServiceFactory({+ queueService,+ identityAccessTokenRevocationDAL+ });++ const identityAccessTokenService = identityAccessTokenServiceFactory({+ identityAccessTokenDAL,+ identityAccessTokenRevocationDAL,+ identityDAL,+ orgDAL,+ keyStore,+ identityAccessTokenQueue+ });+const identityV2Service = identityV2ServiceFactory({membershipIdentityDAL,membershipRoleDAL,@@ -1882,6 +1899,7 @@ export const registerRoutes = async (licenseService,permissionService,identityDAL: identityV2DAL,+ identityAccessTokenService,keyStore});@@ -1900,32 +1918,26 @@ export const registerRoutes = async (auditLogService});- const identityAccessTokenService = identityAccessTokenServiceFactory({- identityAccessTokenDAL,- accessTokenQueue,- identityDAL,- orgDAL- });-const identityTokenAuthService = identityTokenAuthServiceFactory({identityTokenAuthDAL,identityAccessTokenDAL,permissionService,licenseService,orgDAL,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityUaService = identityUaServiceFactory({identityDAL,permissionService,- identityAccessTokenDAL,identityUaClientSecretDAL,identityUaDAL,licenseService,keyStore,orgDAL,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityKubernetesAuthService = identityKubernetesAuthServiceFactory({@@ -1942,7 +1954,8 @@ export const registerRoutes = async (kmsService,membershipIdentityDAL,gatewayPoolService,- gatewayPoolDAL+ gatewayPoolDAL,+ identityAccessTokenService});const identityGcpAuthService = identityGcpAuthServiceFactory({identityDAL,@@ -1951,7 +1964,8 @@ export const registerRoutes = async (identityAccessTokenDAL,permissionService,licenseService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityAliCloudAuthService = identityAliCloudAuthServiceFactory({@@ -1961,7 +1975,8 @@ export const registerRoutes = async (identityAliCloudAuthDAL,licenseService,permissionService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityTlsCertAuthService = identityTlsCertAuthServiceFactory({@@ -1972,7 +1987,8 @@ export const registerRoutes = async (permissionService,kmsService,membershipIdentityDAL,- orgDAL+ orgDAL,+ identityAccessTokenService});const identityAwsAuthService = identityAwsAuthServiceFactory({@@ -1982,7 +1998,8 @@ export const registerRoutes = async (identityAwsAuthDAL,licenseService,permissionService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityAzureAuthService = identityAzureAuthServiceFactory({@@ -1992,7 +2009,8 @@ export const registerRoutes = async (identityAccessTokenDAL,permissionService,licenseService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityOciAuthService = identityOciAuthServiceFactory({@@ -2002,7 +2020,8 @@ export const registerRoutes = async (identityOciAuthDAL,licenseService,permissionService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const pitService = pitServiceFactory({@@ -2028,7 +2047,8 @@ export const registerRoutes = async (permissionService,licenseService,kmsService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityJwtAuthService = identityJwtAuthServiceFactory({@@ -2039,7 +2059,8 @@ export const registerRoutes = async (identityAccessTokenDAL,licenseService,kmsService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identitySpiffeAuthService = identitySpiffeAuthServiceFactory({@@ -2050,7 +2071,8 @@ export const registerRoutes = async (identityAccessTokenDAL,licenseService,kmsService,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const identityLdapAuthService = identityLdapAuthServiceFactory({@@ -2063,7 +2085,8 @@ export const registerRoutes = async (identityDAL,identityAuthTemplateDAL,keyStore,- membershipIdentityDAL+ membershipIdentityDAL,+ identityAccessTokenService});const convertorService = convertorServiceFactory({@@ -2179,6 +2202,7 @@ export const registerRoutes = async (secretFolderVersionDAL: folderVersionDAL,snapshotDAL,identityAccessTokenDAL,+ identityAccessTokenRevocationDAL,secretSharingDAL,secretVersionV2DAL: secretVersionV2BridgeDAL,identityUniversalAuthClientSecretDAL: identityUaClientSecretDAL,@@ -3364,7 +3388,8 @@ export const registerRoutes = async (redisConfigured: z.boolean().optional(),secretScanningConfigured: z.boolean().optional(),samlDefaultOrgSlug: z.string().optional(),- auditLogStorageDisabled: z.boolean().optional()+ auditLogStorageDisabled: z.boolean().optional(),+ maxIdentityAccessTokenTTL: z.number().optional()})}},@@ -3392,7 +3417,8 @@ export const registerRoutes = async (redisConfigured: cfg.isRedisConfigured,secretScanningConfigured: cfg.isSecretScanningConfigured,samlDefaultOrgSlug: cfg.samlDefaultOrgSlug,- auditLogStorageDisabled: Boolean(cfg.DISABLE_POSTGRES_AUDIT_LOG_STORAGE)+ auditLogStorageDisabled: Boolean(cfg.DISABLE_POSTGRES_AUDIT_LOG_STORAGE),+ maxIdentityAccessTokenTTL: cfg.MAX_MACHINE_IDENTITY_TOKEN_AGE};}});@@ -3438,6 +3464,11 @@ 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/server/routes/v1/identity-access-token-router.ts b/backend/src/server/routes/v1/identity-access-token-router.tsindex 64e093a834..22d16db528 100644--- a/backend/src/server/routes/v1/identity-access-token-router.ts+++ b/backend/src/server/routes/v1/identity-access-token-router.ts@@ -28,14 +28,14 @@ export const registerIdentityAccessTokenRouter = async (server: FastifyZodProvid}},handler: async (req) => {- const { accessToken, identityAccessToken } = await server.services.identityAccessToken.renewAccessToken({+ const { accessToken, expiresIn, accessTokenMaxTTL } = await server.services.identityAccessToken.renewAccessToken({accessToken: req.body.accessToken});return {accessToken,tokenType: "Bearer" as const,- expiresIn: identityAccessToken.accessTokenTTL,- accessTokenMaxTTL: identityAccessToken.accessTokenMaxTTL+ expiresIn,+ accessTokenMaxTTL};}});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.tsnew file mode 100644index 0000000000..05d8086b24--- /dev/null+++ b/backend/src/services/identity-access-token/identity-access-token-fns.test.ts@@ -0,0 +1,114 @@+import { afterEach, describe, expect, test, vi } from "vitest";++import { computeIssuedTtl } from "./identity-access-token-fns";++const MAX_AGE = 7_776_000;+const NOW = 1_700_000_000;++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({+ MAX_MACHINE_IDENTITY_TOKEN_AGE: MAX_AGE+ })+}));++describe("computeIssuedTtl", () => {+ afterEach(() => {+ vi.clearAllMocks();+ });++ describe("at issuance (creationEpoch === nowSeconds)", () => {+ test("requestedTTL=0 and maxTTL=0 returns MAX_AGE", () => {+ expect(computeIssuedTtl({ requestedTTL: 0, maxTTL: 0, creationEpoch: NOW, nowSeconds: NOW })).toBe(MAX_AGE);+ });++ test("requestedTTL larger than MAX_AGE is capped to MAX_AGE", () => {+ expect(computeIssuedTtl({ requestedTTL: MAX_AGE + 10_000, maxTTL: 0, creationEpoch: NOW, nowSeconds: NOW })).toBe(+ MAX_AGE+ );+ });++ test("maxTTL > MAX_AGE is allowed; ceiling still binds the per-issuance JWT", () => {+ expect(computeIssuedTtl({ requestedTTL: 0, maxTTL: MAX_AGE + 50_000, creationEpoch: NOW, nowSeconds: NOW })).toBe(+ MAX_AGE+ );+ });++ test("requestedTTL=600 with maxTTL=3600 returns 600 (requested wins)", () => {+ expect(computeIssuedTtl({ requestedTTL: 600, maxTTL: 3600, creationEpoch: NOW, nowSeconds: NOW })).toBe(600);+ });++ test("maxTTL wins when smaller than requestedTTL (pathological config)", () => {+ expect(computeIssuedTtl({ requestedTTL: 3600, maxTTL: 600, creationEpoch: NOW, nowSeconds: NOW })).toBe(600);+ });+ });++ describe("at renewal (nowSeconds > creationEpoch)", () => {+ test("budget shrinks as time elapses; remainingBudget binds when smaller than requestedTTL", () => {+ // 1h elapsed of a 24h budget; 23h remaining; requested 5h → 5h wins+ const oneHour = 3600;+ const result = computeIssuedTtl({+ requestedTTL: 5 * oneHour,+ maxTTL: 24 * oneHour,+ creationEpoch: NOW,+ nowSeconds: NOW + oneHour+ });+ expect(result).toBe(5 * oneHour);+ });++ test("remainingBudget binds when smaller than requestedTTL near end of life", () => {+ // 23h elapsed of a 24h budget; only 1h remaining; requested 5h → 1h wins+ const oneHour = 3600;+ const result = computeIssuedTtl({+ requestedTTL: 5 * oneHour,+ maxTTL: 24 * oneHour,+ creationEpoch: NOW,+ nowSeconds: NOW + 23 * oneHour+ });+ expect(result).toBe(oneHour);+ });++ test("returns 0 exactly at budget exhaustion", () => {+ const maxTTL = 86_400;+ const result = computeIssuedTtl({+ requestedTTL: 3600,+ maxTTL,+ creationEpoch: NOW,+ nowSeconds: NOW + maxTTL+ });+ expect(result).toBe(0);+ });++ test("returns negative past budget exhaustion (caller rejects on <= 0)", () => {+ const maxTTL = 86_400;+ const result = computeIssuedTtl({+ requestedTTL: 3600,+ maxTTL,+ creationEpoch: NOW,+ nowSeconds: NOW + maxTTL + 60+ });+ expect(result).toBeLessThan(0);+ });++ test("maxTTL > ceiling: each renewed JWT is ceiling-bounded; budget keeps decaying", () => {+ // 180d budget, 90d ceiling, 30d elapsed → 150d remaining → ceiling (90d) wins+ const day = 86_400;+ const result = computeIssuedTtl({+ requestedTTL: 0,+ maxTTL: 180 * day,+ creationEpoch: NOW,+ nowSeconds: NOW + 30 * day+ });+ expect(result).toBe(MAX_AGE);+ });++ test("maxTTL=0 means no budget cap; pure (requested, ceiling) min", () => {+ const result = computeIssuedTtl({+ requestedTTL: 600,+ maxTTL: 0,+ creationEpoch: NOW,+ nowSeconds: NOW + 1_000_000+ });+ expect(result).toBe(600);+ });+ });+});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.tsnew file mode 100644index 0000000000..119987e144--- /dev/null+++ b/backend/src/services/identity-access-token/identity-access-token-fns.ts@@ -0,0 +1,177 @@+import { getConfig } from "@app/lib/config/env";+import { crypto } from "@app/lib/crypto";+import { BadRequestError, UnauthorizedError } from "@app/lib/errors";+import { TIp } from "@app/lib/ip";++import { AuthTokenType } from "../auth/auth-type";+import {+ TComputeIssuedTtlInput,+ TCoreTokenClaims,+ TFastPathClaims,+ TIdentityAccessTokenJwtPayload,+ TMinimalRenewClaims,+ TRenewableClaims,+ TRevocableClaims,+ TSignIdentityAccessTokenInput,+ TSignIdentityAccessTokenOutput+} from "./identity-access-token-types";++export const hasNonWildcardTrustedIps = (trustedIps: TIp[] | null | undefined): boolean => {+ if (!trustedIps || trustedIps.length === 0) {+ return false;+ }+ return trustedIps.some((ip) => ip.ipAddress !== "0.0.0.0/0" && ip.ipAddress !== "::/0");+};++// Parse the per-token uses-remaining hash field. Returns null when absent or+// unparseable (treated as "no constraint"); callers reject on values <= 0.+export const parseUsesRemaining = (raw: string | null): number | null => {+ if (raw === null) {+ return null;+ }+ const parsed = parseInt(raw, 10);+ 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.+export const resolveTtlInputs = (period: number, ttl: number, maxTTL: number) => {+ if (period > 0) {+ return { requestedTTL: period, requestedMaxTTL: 0 };+ }+ return { requestedTTL: ttl, requestedMaxTTL: maxTTL };+};++// Verify the JWT signature and assert it carries the IDENTITY_ACCESS_TOKEN type+// claim. Caller still asserts the per-flow required claims via the helpers below.+export const verifyAccessTokenJwt = (accessToken: string): TIdentityAccessTokenJwtPayload => {+ const decoded = crypto.jwt().verify(accessToken, getConfig().AUTH_SECRET) as TIdentityAccessTokenJwtPayload;+ if (decoded.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN) {+ throw new BadRequestError({ message: "Token is not an identity access token" });+ }+ return decoded;+};++const hasCoreTokenClaims = (decoded: TIdentityAccessTokenJwtPayload): decoded is TCoreTokenClaims =>+ !!decoded.jti && typeof decoded.iat === "number" && !!decoded.identityId;++// 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.+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) {+ throw new UnauthorizedError({ message: "Invalid identity access token claims, please re-authenticate" });+ }+ return decoded as TFastPathClaims;+};++// Compute the TTL (seconds) to sign the JWT with.+//+// Three caps:+// - requestedTTL: per-issuance lifetime requested by the caller (0 = no cap).+// - ceiling: env-enforced maximum age for any single JWT (always positive).+// A token may live past this *via renewals* — each new JWT gets a fresh+// ceiling-bounded exp; the ceiling does not bound total token lifetime.+// - maxTTL: total lifetime budget across all renewals, anchored at+// creationEpoch. At first issuance creationEpoch === nowSeconds so the+// remaining budget equals maxTTL; on renew it shrinks as time elapses.+// 0 = no budget cap.+//+// Returns possibly <= 0 when the budget is exhausted (renew callers must+// reject this as a re-auth signal; issuance can never reach 0 because the+// ceiling is always positive and remainingBudget at issuance == maxTTL).+export const computeIssuedTtl = ({+ requestedTTL,+ maxTTL,+ creationEpoch,+ nowSeconds+}: TComputeIssuedTtlInput): number => {+ const { MAX_MACHINE_IDENTITY_TOKEN_AGE: ceiling } = getConfig();++ let requestedCap = Infinity;+ if (requestedTTL > 0) {+ requestedCap = requestedTTL;+ }++ let remainingBudget = Infinity;+ // this handles tokens with a maxTTL for renewal cases+ if (maxTTL > 0) {+ remainingBudget = creationEpoch + maxTTL - nowSeconds;+ }++ // this essentially says, give us the value that expires the soonest of:+ // - the TTL in the token config+ // - The remaining time that the token as a whole can be renewed for+ // - The maximum TTL for any single token issuance (defined by env var)+ return Math.min(requestedCap, remainingBudget, ceiling);+};++export const signIdentityAccessToken = (input: TSignIdentityAccessTokenInput): TSignIdentityAccessTokenOutput => {+ const appCfg = getConfig();+ const jti = input.identityAccessTokenId;++ const payload: TIdentityAccessTokenJwtPayload = {+ identityId: input.identityId,+ identityName: input.identityName,+ authMethod: input.authMethod,+ orgId: input.orgId,+ rootOrgId: input.rootOrgId,+ parentOrgId: input.parentOrgId,+ clientSecretId: input.clientSecretId,+ identityAccessTokenId: input.identityAccessTokenId,+ ipRestrictionEnabled: input.ipRestrictionEnabled,+ accessTokenTTL: input.accessTokenTTL,+ accessTokenMaxTTL: input.accessTokenMaxTTL,+ accessTokenPeriod: input.accessTokenPeriod,+ creationEpoch: input.creationEpoch,+ authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,+ identityAuth: input.identityAuth ?? {}+ };++ if (input.numUsesLimit > 0) {+ payload.numUsesLimit = input.numUsesLimit;+ }++ const accessToken = crypto.jwt().sign(payload, appCfg.AUTH_SECRET, {+ jwtid: jti,+ expiresIn: input.ttlSeconds+ });++ return { accessToken, jti, expiresIn: input.ttlSeconds };+};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.tsnew file mode 100644index 0000000000..d1c701a736--- /dev/null+++ b/backend/src/services/identity-access-token/identity-access-token-queue.ts@@ -0,0 +1,99 @@+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.tsnew file mode 100644index 0000000000..2e4b2215e3--- /dev/null+++ b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts@@ -0,0 +1,67 @@+import { TDbClient } from "@app/db";+import { TableName, TIdentityAccessTokenRevocations } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";++type TRevocationRow = Pick<TIdentityAccessTokenRevocations, "id" | "identityId" | "revokedAt" | "createdAt">;++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).+type TInsertRevocationInput = {+ id: string;+ identityId: string;+ expiresAt: Date;+ revokedAt?: Date | null;+};++export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {+ const insertRevocation = async (row: TInsertRevocationInput) => {+ try {+ await db(TableName.IdentityAccessTokenRevocation)+ .insert(row)+ .onConflict(["id"])+ .merge({ 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[]> => {+ try {+ let query = 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[];+ } catch (error) {+ throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationFindActive" });+ }+ };++ const removeExpiredRevocations = async () => {+ try {+ await db(TableName.IdentityAccessTokenRevocation).where("expiresAt", "<", db.fn.now()).delete();+ } catch (error) {+ throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationRemoveExpired" });+ }+ };++ return {+ insertRevocation,+ findActive,+ 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.tsnew file mode 100644index 0000000000..6e6b2a09c0--- /dev/null+++ b/backend/src/services/identity-access-token/identity-access-token-service.test.ts@@ -0,0 +1,271 @@+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";++import { 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";++const MAX_AGE = 7_776_000;+const AUTH_SECRET = "test-auth-secret";+const NOW_SECONDS = 1_700_000_000;++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({+ AUTH_SECRET,+ MAX_MACHINE_IDENTITY_TOKEN_AGE: MAX_AGE+ })+}));++vi.mock("@app/lib/logger", () => ({+ logger: {+ info: vi.fn(),+ error: vi.fn()+ }+}));++const createService = ({+ trustedIps = [],+ membership = { isActive: true }+}: {+ trustedIps?: TIp[] | null;+ membership?: { isActive: boolean } | null;+} = {}) => {+ const keyStore = {+ hashGetMulti: vi.fn().mockResolvedValue([null, null]),+ hashIncrementBy: vi.fn(),+ hashSetWithExpiry: vi.fn(),+ setItemWithExpiry: vi.fn(),+ setItemWithExpiryNX: vi.fn()+ };+ const identityDAL = {+ getTrustedIpsByAuthMethod: vi.fn().mockResolvedValue(trustedIps),+ findById: vi.fn()+ };+ 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,+ identityDAL: identityDAL as never,+ orgDAL: orgDAL as never,+ keyStore: keyStore as never,+ identityAccessTokenQueue: identityAccessTokenQueue as never+ });++ return { service, keyStore, identityDAL, orgDAL, identityAccessTokenQueue };+};++const createTokenClaims = (+ overrides: Partial<TIdentityAccessTokenJwtPayload> = {}+): TIdentityAccessTokenJwtPayload => ({+ jti: "token-id",+ iat: NOW_SECONDS,+ exp: NOW_SECONDS + 3600,+ identityId: "identity-id",+ identityName: "identity-name",+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ orgId: "org-id",+ rootOrgId: "root-org-id",+ parentOrgId: "parent-org-id",+ ipRestrictionEnabled: false,+ clientSecretId: "",+ identityAccessTokenId: "token-id",+ authTokenType: "identity-access-token",+ accessTokenTTL: 0,+ accessTokenMaxTTL: 0,+ accessTokenPeriod: 0,+ creationEpoch: NOW_SECONDS,+ identityAuth: {},+ ...overrides+});++describe("identityAccessTokenServiceFactory", () => {+ let previousFipsEnabled: string | undefined;++ beforeAll(async () => {+ previousFipsEnabled = process.env.FIPS_ENABLED;+ process.env.FIPS_ENABLED = "false";+ await crypto.initialize({} as never, {} as never, {} as never);+ });++ afterAll(() => {+ if (previousFipsEnabled === undefined) {+ delete process.env.FIPS_ENABLED;+ } else {+ process.env.FIPS_ENABLED = previousFipsEnabled;+ }+ });++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(NOW_SECONDS * 1000));+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ test("queues per-token revocation with the JWT exp for zero configured TTL tokens", 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, identityAccessTokenQueue } = createService();++ await service.revokeAccessToken(accessToken);++ expect(identityAccessTokenQueue.queuePgMirror).toHaveBeenCalledWith({+ kind: "revoke-token",+ tokenId: "token-id",+ identityId: "identity-id",+ expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000).toISOString()+ });+ });++ 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 }]+ });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "192.168.1.1")).rejects.toThrow(+ "current IP address"+ );+ expect(identityDAL.getTrustedIpsByAuthMethod).toHaveBeenCalledWith(+ "identity-id",+ IdentityAuthMethod.UNIVERSAL_AUTH+ );+ });++ test("allows wildcard current trusted IPs", async () => {+ const { service } = createService({+ trustedIps: [{ ipAddress: "0.0.0.0/0", prefix: 0, type: IPType.IPV4 }]+ });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "192.168.1.1")).resolves.toMatchObject({+ identityId: "identity-id",+ orgId: "org-id"+ });+ });++ test("rejects when the identity no longer has an effective org membership", async () => {+ const { service } = createService({ membership: null });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(+ "not a member"+ );+ });++ test("rejects when the identity org membership is inactive", async () => {+ const { service } = createService({ membership: { isActive: false } });++ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(+ "membership is inactive"+ );+ });+});++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 e299770760..31fab1552c 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,243 +1,554 @@-import { IdentityAuthMethod, TableName, TIdentityAccessTokens } from "@app/db/schemas";+import { Knex } from "knex";++import { IdentityAuthMethod, OrgMembershipStatus, TIdentityAccessTokens } from "@app/db/schemas";+import { IdentityTokenStateFields, KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";-import { BadRequestError, UnauthorizedError } from "@app/lib/errors";+import { UnauthorizedError } from "@app/lib/errors";import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip";-import { ActorType } from "@app/services/auth/auth-type";+import { logger } from "@app/lib/logger";-import { TAccessTokenQueueServiceFactory } from "../access-token-queue/access-token-queue";-import { AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { TIdentityAccessTokenDALFactory } from "./identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload, TRenewAccessTokenDTO } from "./identity-access-token-types";+import {+ assertFastPathClaims,+ assertMinimalRenewClaims,+ assertRevocableClaims,+ 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,+ TIdentityAccessTokenJwtPayload,+ TKubernetesAuthDetails,+ TOidcAuthDetails,+ TRenewAccessTokenDTO,+ TRenewSource+} from "./identity-access-token-types";++export type TIssueIdentityAccessTokenInput = {+ identityId: string;+ identityName: string;+ authMethod: IdentityAuthMethod;+ orgId: string;+ rootOrgId: string;+ parentOrgId: string;+ subOrganizationId: string | null;+ accessTokenTTL: number;+ accessTokenMaxTTL: number;+ accessTokenNumUsesLimit: number;+ // 0 = standard TTL/MaxTTL. > 0 = periodic mode (TTL is the period).+ accessTokenPeriod: number;+ accessTokenTrustedIps: TIp[];+ clientSecretId?: string;+ identityAuth?: {+ oidc?: TOidcAuthDetails;+ kubernetes?: TKubernetesAuthDetails;+ aws?: TAWSAuthDetails;+ };+ // Set by Token Auth to insert a real PG row in its transaction; every other+ // auth method omits this and gets a fresh in-memory UUID.+ persistToPg?: { tx: Knex; name?: string | null };+};++export type TIssueIdentityAccessTokenOutput = {+ accessToken: string;+ identityAccessToken: TIdentityAccessTokens;+};type TIdentityAccessTokenServiceFactoryDep = {identityAccessTokenDAL: TIdentityAccessTokenDALFactory;- identityDAL: Pick<TIdentityDALFactory, "getTrustedIpsByAuthMethod">;- accessTokenQueue: Pick<- TAccessTokenQueueServiceFactory,- "updateIdentityAccessTokenStatus" | "getIdentityTokenDetailsInCache"+ identityAccessTokenRevocationDAL: TIdentityAccessTokenRevocationDALFactory;+ identityDAL: Pick<TIdentityDALFactory, "getTrustedIpsByAuthMethod" | "findById">;+ orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;+ keyStore: Pick<+ TKeyStoreFactory,+ "hashGetMulti" | "hashIncrementBy" | "hashSetWithExpiry" | "setItemWithExpiry" | "setItemWithExpiryNX">;- orgDAL: Pick<TOrgDALFactory, "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenQueue: TIdentityAccessTokenQueueServiceFactory;};export type TIdentityAccessTokenServiceFactory = ReturnType<typeof identityAccessTokenServiceFactory>;export const identityAccessTokenServiceFactory = ({identityAccessTokenDAL,- accessTokenQueue,+ identityAccessTokenRevocationDAL,identityDAL,- orgDAL+ orgDAL,+ keyStore,+ identityAccessTokenQueue}: TIdentityAccessTokenServiceFactoryDep) => {- const validateAccessTokenExp = async (identityAccessToken: TIdentityAccessTokens) => {- const {- id: tokenId,- accessTokenNumUses,- accessTokenTTL,- accessTokenNumUsesLimit,- accessTokenLastRenewedAt,- createdAt: accessTokenCreatedAt- } = identityAccessToken;-- if (accessTokenNumUsesLimit > 0 && accessTokenNumUses > 0 && accessTokenNumUses >= accessTokenNumUsesLimit) {- await identityAccessTokenDAL.deleteById(tokenId);- throw new UnauthorizedError({- message: "Unable to renew because access token number of uses limit reached"- });- }-- // ttl check- if (Number(accessTokenTTL) > 0) {- const currentDate = new Date();- if (accessTokenLastRenewedAt) {- // access token has been renewed- const accessTokenRenewed = new Date(accessTokenLastRenewedAt);- const ttlInMilliseconds = Number(accessTokenTTL) * 1000;- const expirationDate = new Date(accessTokenRenewed.getTime() + ttlInMilliseconds);-- if (currentDate > expirationDate) {- await identityAccessTokenDAL.deleteById(tokenId);- throw new UnauthorizedError({- message: "Failed to renew MI access token due to TTL expiration"- });- }- } else {- // access token has never been renewed- const accessTokenCreated = new Date(accessTokenCreatedAt);- const ttlInMilliseconds = Number(accessTokenTTL) * 1000;- const expirationDate = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);-- if (currentDate > expirationDate) {- await identityAccessTokenDAL.deleteById(tokenId);- throw new UnauthorizedError({- message: "Failed to renew MI access token due to TTL expiration"- });- }- }+ // 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 (+ input: TIssueIdentityAccessTokenInput+ ): Promise<TIssueIdentityAccessTokenOutput> => {+ const appCfg = getConfig();+ const issuedAt = new Date();++ const period = Number(input.accessTokenPeriod) || 0;+ const { requestedTTL, requestedMaxTTL } = resolveTtlInputs(+ period,+ Number(input.accessTokenTTL) || 0,+ Number(input.accessTokenMaxTTL) || 0+ );++ const creationEpoch = Math.floor(issuedAt.getTime() / 1000);+ const ttl = computeIssuedTtl({+ requestedTTL,+ maxTTL: requestedMaxTTL,+ creationEpoch,+ nowSeconds: creationEpoch+ });++ const ipRestrictionEnabled = hasNonWildcardTrustedIps(input.accessTokenTrustedIps);+ const numUsesLimit = Number(input.accessTokenNumUsesLimit) || 0;++ const baseRow = {+ identityId: input.identityId,+ isAccessTokenRevoked: false,+ accessTokenTTL: ttl,+ accessTokenMaxTTL: requestedMaxTTL,+ accessTokenNumUses: 0,+ accessTokenNumUsesLimit: numUsesLimit,+ accessTokenPeriod: period,+ authMethod: input.authMethod,+ subOrganizationId: input.subOrganizationId+ };++ let identityAccessToken: TIdentityAccessTokens;+ if (input.persistToPg) {+ identityAccessToken = await identityAccessTokenDAL.create(+ { ...baseRow, name: input.persistToPg.name ?? null },+ input.persistToPg.tx+ );+ } else {+ identityAccessToken = {+ ...baseRow,+ id: crypto.nativeCrypto.randomUUID(),+ createdAt: issuedAt,+ updatedAt: issuedAt+ };+ }++ const { accessToken } = signIdentityAccessToken({+ identityAccessTokenId: identityAccessToken.id,+ identityId: input.identityId,+ identityName: input.identityName,+ authMethod: input.authMethod,+ orgId: input.orgId,+ rootOrgId: input.rootOrgId,+ parentOrgId: input.parentOrgId,+ clientSecretId: input.clientSecretId ?? "",+ numUsesLimit,+ ipRestrictionEnabled,+ ttlSeconds: ttl,+ // Store the original configured value (not the ceiling-capped computed TTL)+ // so that renewals re-apply configMaxTTL fresh each time.+ accessTokenTTL: requestedTTL,+ accessTokenMaxTTL: requestedMaxTTL,+ accessTokenPeriod: period,+ creationEpoch,+ identityAuth: input.identityAuth+ });++ if (numUsesLimit > 0) {+ await keyStore.hashSetWithExpiry(+ KeyStorePrefixes.IdentityTokenState(input.identityId),+ { [IdentityTokenStateFields.UsesRemaining(identityAccessToken.id)]: numUsesLimit },+ appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE+ );}++ return { accessToken, identityAccessToken };};- const renewAccessToken = async ({ accessToken }: TRenewAccessTokenDTO) => {+ const fnValidateIdentityAccessTokenFast = async (rawToken: TIdentityAccessTokenJwtPayload, ipAddress?: string) => {const appCfg = getConfig();+ const token = assertFastPathClaims(rawToken);++ // Legacy tokens (pre-redesign) were signed without `expiresIn` so the JWT+ // has no `exp`. For those, enforce the `iat + MAX_AGE` ceiling here.+ // New tokens always have `exp`; jwt.verify already rejected expired ones.+ const issuedAtMs = token.iat * 1000;+ if (typeof token.exp !== "number" && Date.now() > issuedAtMs + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000) {+ throw new UnauthorizedError({ message: "Identity access token exceeded max age, please re-authenticate" });+ }- const decodedToken = crypto.jwt().verify(accessToken, appCfg.AUTH_SECRET) as TIdentityAccessTokenJwtPayload;- if (decodedToken.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN) {- throw new BadRequestError({ message: "Only identity access tokens can be renewed" });+ const stateKey = KeyStorePrefixes.IdentityTokenState(token.identityId);++ const [revokedAfter, usesRemainingRaw] = await keyStore.hashGetMulti(stateKey, [+ IdentityTokenStateFields.RevokedAfter,+ IdentityTokenStateFields.UsesRemaining(token.jti)+ ]);++ const revokedAfterMs = parseRevokedAfter(revokedAfter);+ if (revokedAfterMs !== null && issuedAtMs < revokedAfterMs) {+ throw new UnauthorizedError({ message: "Failed to authorize: identity tokens have been revoked" });}- const identityAccessToken = await identityAccessTokenDAL.findOne({- [`${TableName.IdentityAccessToken}.id` as "id"]: decodedToken.identityAccessTokenId,- isAccessTokenRevoked: false- });- if (!identityAccessToken) throw new UnauthorizedError({ message: "No identity access token found" });-- let { accessTokenNumUses } = identityAccessToken;- const tokenStatusInCache = await accessTokenQueue.getIdentityTokenDetailsInCache(identityAccessToken.id);- if (tokenStatusInCache) {- accessTokenNumUses = tokenStatusInCache.numberOfUses;- }- await validateAccessTokenExp({ ...identityAccessToken, accessTokenNumUses });-- const {- accessTokenMaxTTL,- createdAt: accessTokenCreatedAt,- accessTokenTTL,- accessTokenPeriod- } = identityAccessToken;-- // Only enforce Max TTL for non-periodic tokens- if (Number(accessTokenMaxTTL) > 0 && Number(accessTokenPeriod) === 0) {- const accessTokenCreated = new Date(accessTokenCreatedAt);- const ttlInMilliseconds = Number(accessTokenMaxTTL) * 1000;- const currentDate = new Date();- const expirationDate = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);-- if (currentDate > expirationDate) {- await identityAccessTokenDAL.deleteById(identityAccessToken.id);- throw new UnauthorizedError({- message: "Failed to renew MI access token due to Max TTL expiration"- });+ // The counter doubles as the per-token revoke marker. null means+ // unlimited and not revoked; <= 0 means revoked or exhausted.+ const remainingFromState = parseUsesRemaining(usesRemainingRaw);+ if (remainingFromState !== null && remainingFromState <= 0) {+ throw new UnauthorizedError({ message: "Failed to authorize: token revoked or 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+ );+ } else {+ const remaining = await keyStore.hashIncrementBy(+ stateKey,+ IdentityTokenStateFields.UsesRemaining(token.jti),+ -1+ );+ if (remaining < 0) {+ throw new UnauthorizedError({ message: "Failed to authorize: token usage limit reached" });+ }}+ }- const extendToDate = new Date(currentDate.getTime() + Number(accessTokenTTL * 1000));- if (extendToDate > expirationDate) {- await identityAccessTokenDAL.deleteById(identityAccessToken.id);- throw new UnauthorizedError({- message: "Failed to renew MI access token past its Max TTL expiration"+ if (ipAddress && token.authMethod) {+ const trustedIps = await identityDAL.getTrustedIpsByAuthMethod(+ token.identityId,+ token.authMethod as IdentityAuthMethod+ );+ if (hasNonWildcardTrustedIps(trustedIps as TIp[] | null | undefined)) {+ checkIPAgainstBlocklist({+ ipAddress,+ trustedIps: trustedIps as TIp[]});}}- const updatedIdentityAccessToken = await identityAccessTokenDAL.updateById(identityAccessToken.id, {- accessTokenLastRenewedAt: new Date()+ const orgMembership = await orgDAL.findEffectiveOrgMembership({+ actorType: ActorType.IDENTITY,+ actorId: token.identityId,+ orgId: token.orgId,+ status: OrgMembershipStatus.Accepted});+ if (!orgMembership) {+ throw new UnauthorizedError({ message: "Identity is not a member of the organization" });+ }+ if (!orgMembership.isActive) {+ throw new UnauthorizedError({ message: "Identity organization membership is inactive" });+ }- const ttl = Number(accessTokenTTL);- const period = Number(accessTokenPeriod);-- let expiresIn: number | undefined;- if (period > 0) {- expiresIn = period;- } else if (ttl > 0) {- expiresIn = ttl;- } else {- expiresIn = undefined;- }-- const renewedToken = crypto.jwt().sign(- {- identityId: decodedToken.identityId,- clientSecretId: decodedToken.clientSecretId,- identityAccessTokenId: decodedToken.identityAccessTokenId,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,- identityAuth: decodedToken.identityAuth- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- expiresIn !== undefined ? { expiresIn } : undefined- );+ return {+ identityId: token.identityId,+ identityName: token.identityName ?? "",+ name: token.identityName ?? "",+ orgId: token.orgId,+ rootOrgId: token.rootOrgId,+ parentOrgId: token.parentOrgId,+ orgName: undefined as string | undefined,+ authMethod: (token.authMethod ?? "") as string+ };+ };- return { accessToken: renewedToken, identityAccessToken: updatedIdentityAccessToken };+ // 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+ };};- const revokeAccessToken = async (accessToken: string) => {+ const renewAccessToken = async ({ accessToken }: TRenewAccessTokenDTO) => {const appCfg = getConfig();+ const decodedToken = assertMinimalRenewClaims(verifyAccessTokenJwt(accessToken));- const decodedToken = crypto.jwt().verify(accessToken, appCfg.AUTH_SECRET) as TIdentityAccessTokenJwtPayload & {- identityAccessTokenId: string;- };- if (decodedToken.authTokenType !== AuthTokenType.IDENTITY_ACCESS_TOKEN) {- throw new UnauthorizedError({ message: "Only identity access tokens can be revoked" });+ // Single-JWT max age. New-format validation enforces this on the hot path+ // via the same check; mirror it here so legacy JWTs (which were signed+ // with arbitrarily long expiresIn) can't renew themselves indefinitely.+ if (decodedToken.iat * 1000 + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000 < Date.now()) {+ throw new UnauthorizedError({ message: "Identity access token exceeded max age, please re-authenticate" });+ }++ const source: TRenewSource = hasFullRenewClaims(decodedToken)+ ? {+ authMethod: decodedToken.authMethod,+ accessTokenTTL: decodedToken.accessTokenTTL,+ accessTokenMaxTTL: decodedToken.accessTokenMaxTTL,+ accessTokenPeriod: decodedToken.accessTokenPeriod,+ creationEpoch: decodedToken.creationEpoch,+ identityName: decodedToken.identityName ?? "",+ orgId: decodedToken.orgId ?? "",+ rootOrgId: decodedToken.rootOrgId ?? decodedToken.orgId ?? "",+ parentOrgId: decodedToken.parentOrgId ?? decodedToken.orgId ?? "",+ clientSecretId: decodedToken.clientSecretId,+ identityAuth: decodedToken.identityAuth+ }+ : 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 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" });}- const identityAccessToken = await identityAccessTokenDAL.findOne({- [`${TableName.IdentityAccessToken}.id` as "id"]: decodedToken.identityAccessTokenId,- isAccessTokenRevoked: false+ const { requestedTTL, requestedMaxTTL } = resolveTtlInputs(+ source.accessTokenPeriod,+ source.accessTokenTTL,+ source.accessTokenMaxTTL+ );+ const nowSeconds = Math.floor(Date.now() / 1000);+ const ttl = computeIssuedTtl({+ requestedTTL,+ maxTTL: requestedMaxTTL,+ creationEpoch: source.creationEpoch,+ nowSeconds});- if (!identityAccessToken) throw new UnauthorizedError({ message: "No identity access token found" });+ if (ttl <= 0) {+ throw new UnauthorizedError({ message: "Cannot renew: identity access token has reached its max TTL" });+ }- const revokedToken = await identityAccessTokenDAL.updateById(identityAccessToken.id, {- isAccessTokenRevoked: true+ const numUsesLimit = decodedToken.numUsesLimit ?? 0;+ const ipRestrictionEnabled = Boolean(decodedToken.ipRestrictionEnabled);++ const { accessToken: renewedToken } = signIdentityAccessToken({+ identityAccessTokenId: decodedToken.identityAccessTokenId,+ identityId: decodedToken.identityId,+ identityName: source.identityName,+ authMethod: source.authMethod,+ orgId: source.orgId,+ rootOrgId: source.rootOrgId,+ parentOrgId: source.parentOrgId,+ clientSecretId: source.clientSecretId,+ numUsesLimit,+ ipRestrictionEnabled,+ ttlSeconds: ttl,+ identityAuth: source.identityAuth,+ accessTokenTTL: source.accessTokenTTL,+ accessTokenMaxTTL: source.accessTokenMaxTTL,+ accessTokenPeriod: source.accessTokenPeriod,+ creationEpoch: source.creationEpoch});- return { revokedToken };+ // Renewed JWT keeps the same `jti`, so any existing revocation marker+ // already applies. Reseed the 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+ );+ }++ return {+ accessToken: renewedToken,+ expiresIn: ttl,+ accessTokenMaxTTL: source.accessTokenMaxTTL+ };};- const fnValidateIdentityAccessToken = async (token: TIdentityAccessTokenJwtPayload, ipAddress?: string) => {- const identityAccessToken = await identityAccessTokenDAL.findOne({- [`${TableName.IdentityAccessToken}.id` as "id"]: token.identityAccessTokenId,- isAccessTokenRevoked: false+ const revokeAccessToken = async (accessToken: string) => {+ const appCfg = getConfig();++ const decodedToken = assertRevocableClaims(verifyAccessTokenJwt(accessToken));+ const { jti, identityId } = decodedToken;++ 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,+ identityId,+ expiresAt: new Date(+ (decodedToken.exp ?? decodedToken.iat + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE) * 1000+ ).toISOString()});- if (!identityAccessToken) throw new UnauthorizedError({ message: "No identity access token found" });- if (identityAccessToken.isAccessTokenRevoked)- throw new UnauthorizedError({- message: "Failed to authorize revoked access token, access token is revoked"- });-- const trustedIps = await identityDAL.getTrustedIpsByAuthMethod(- identityAccessToken.identityId,- identityAccessToken.authMethod as IdentityAuthMethod++ return { revokedToken: { id: decodedToken.identityAccessTokenId, identityId, isAccessTokenRevoked: true } };+ };++ // Per-token revoke from a context that doesn't have a JWT (e.g. Token Auth's+ // admin "revoke this token by id" flow). Caller computes the latest possible+ // exp and passes it as `expiresAt`; we skip the PG insert if it's already+ // in the past since no future JWT could be blocked by such a marker.+ const markPerTokenRevocation = async ({+ tokenId,+ identityId,+ expiresAt+ }: {+ tokenId: string;+ identityId: string;+ expiresAt: Date;+ }) => {+ const appCfg = getConfig();++ await keyStore.hashSetWithExpiry(+ KeyStorePrefixes.IdentityTokenState(identityId),+ { [IdentityTokenStateFields.UsesRemaining(tokenId)]: 0 },+ appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE);- if (ipAddress && trustedIps) {- checkIPAgainstBlocklist({- ipAddress,- trustedIps: trustedIps as TIp[]- });- }- const scopeOrgId = identityAccessToken.subOrganizationId || identityAccessToken.identityOrgId;+ if (expiresAt.getTime() <= Date.now()) {+ return;+ }- const identityOrgDetails = await orgDAL.findOne({ id: scopeOrgId });+ await identityAccessTokenRevocationDAL.insertRevocation({+ id: tokenId,+ identityId,+ expiresAt+ });+ };- const isSubOrg = Boolean(identityOrgDetails.rootOrgId);+ // Identity-wide revoke: any JWT with iat < this epoch is rejected on auth.+ const revokeAllTokensForIdentity = async (identityId: string) => {+ const appCfg = getConfig();+ const revokedAt = new Date();- const rootOrgId = isSubOrg ? identityOrgDetails.rootOrgId || identityOrgDetails.id : identityOrgDetails.id;+ await keyStore.hashSetWithExpiry(+ KeyStorePrefixes.IdentityTokenState(identityId),+ { [IdentityTokenStateFields.RevokedAfter]: revokedAt.toISOString() },+ appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE+ );- // Verify identity membership in the organization (direct or via group)- const identityOrgMembership = await orgDAL.findEffectiveOrgMembership({- actorType: ActorType.IDENTITY,- actorId: identityAccessToken.identityId,- orgId: identityOrgDetails.id+ void identityAccessTokenQueue.queuePgMirror({+ kind: "revoke-all-for-identity",+ identityId,+ revokedAt: revokedAt.toISOString()});+ };++ const HYDRATION_LEASE_SECONDS = 600;+ const HYDRATION_MARKER_SECONDS = 2_592_000;- if (!identityOrgMembership) {- throw new BadRequestError({ message: "Identity does not belong to this organization" });+ 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 orgId = identityOrgDetails.id;- const orgName = identityOrgDetails.name;- const parentOrgId = identityOrgDetails.parentOrgId || rootOrgId;+ 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;+ }- let { accessTokenNumUses } = identityAccessToken;- const tokenStatusInCache = await accessTokenQueue.getIdentityTokenDetailsInCache(identityAccessToken.id);- if (tokenStatusInCache) {- accessTokenNumUses = tokenStatusInCache.numberOfUses;+ 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;}- await validateAccessTokenExp({ ...identityAccessToken, accessTokenNumUses });- await accessTokenQueue.updateIdentityAccessTokenStatus(identityAccessToken.id, Number(accessTokenNumUses) + 1);- return { ...identityAccessToken, orgId, rootOrgId, parentOrgId, orgName };+ // 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 { renewAccessToken, revokeAccessToken, fnValidateIdentityAccessToken };+ return {+ issueIdentityAccessToken,+ renewAccessToken,+ revokeAccessToken,+ revokeAllTokensForIdentity,+ markPerTokenRevocation,+ fnValidateIdentityAccessTokenFast,+ hydrateRedisFromPg+ };};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 a8a62a9e0c..c61643d271 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@@ -1,3 +1,5 @@+import { IdentityAuthMethod } from "@app/db/schemas";+export type TRenewAccessTokenDTO = {accessToken: string;};@@ -23,14 +25,129 @@ 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.+//+// `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).+//+// `creationEpoch` anchors the maxTTL lifetime budget across renewals. JWT `iat`+// is restamped on every renewal, so it cannot anchor "since creation" — this+// claim is set at first issuance and copied through unchanged on renew.export type TIdentityAccessTokenJwtPayload = {+ jti?: string;+ iat?: number;+ exp?: number;identityId: string;+ identityName?: string;+ authMethod?: IdentityAuthMethod;+ orgId?: string;+ rootOrgId?: string;+ parentOrgId?: string;+ numUsesLimit?: number;+ ipRestrictionEnabled?: boolean;clientSecretId: string;identityAccessTokenId: string;authTokenType: string;+ accessTokenTTL?: number;+ accessTokenMaxTTL?: number;+ accessTokenPeriod?: number;+ creationEpoch?: number;identityAuth: {oidc?: TOidcAuthDetails;kubernetes?: TKubernetesAuthDetails;aws?: TAWSAuthDetails;};};++// Claims shared by every validated JWT path — the common core all three assert+// helpers require before they check their own additional fields.+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.+export type TRenewableClaims = TMinimalRenewClaims & {+ authMethod: IdentityAuthMethod;+ 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.+export type TRenewSource = {+ authMethod: IdentityAuthMethod;+ accessTokenTTL: number;+ accessTokenMaxTTL: number;+ accessTokenPeriod: number;+ creationEpoch: number;+ identityName: string;+ orgId: string;+ rootOrgId: string;+ parentOrgId: string;+ clientSecretId: string;+ identityAuth?: TIdentityAccessTokenJwtPayload["identityAuth"];+};++export type TRevocableClaims = TCoreTokenClaims & {+ authMethod: IdentityAuthMethod;+ accessTokenTTL: number;+};++export type TComputeIssuedTtlInput = {+ requestedTTL: number;+ maxTTL: number;+ creationEpoch: number;+ nowSeconds: number;+};++export type TSignIdentityAccessTokenInput = {+ identityAccessTokenId: string;+ identityId: string;+ identityName: string;+ authMethod: IdentityAuthMethod;+ orgId: string;+ rootOrgId: string;+ parentOrgId: string;+ clientSecretId: string;+ numUsesLimit: number;+ ipRestrictionEnabled: boolean;+ ttlSeconds: number;+ accessTokenTTL: number;+ accessTokenMaxTTL: number;+ accessTokenPeriod: number;+ creationEpoch: number;+ identityAuth?: {+ oidc?: TOidcAuthDetails;+ kubernetes?: TKubernetesAuthDetails;+ aws?: TAWSAuthDetails;+ };+};++export type TSignIdentityAccessTokenOutput = {+ accessToken: string;+ jti: string;+ expiresIn: number;+};diff --git a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.tsindex adea74032c..cbeb029e54 100644--- a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts+++ b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts@@ -14,7 +14,6 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";-import { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -22,17 +21,17 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -48,7 +47,7 @@ import {type TIdentityAliCloudAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;identityAliCloudAuthDAL: Pick<TIdentityAliCloudAuthDALFactory,"findOne" | "transaction" | "create" | "updateById" | "delete"@@ -57,6 +56,10 @@ type TIdentityAliCloudAuthServiceFactoryDep = {licenseService: Pick<TLicenseServiceFactory, "getPlan">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityAliCloudAuthServiceFactory = ReturnType<typeof identityAliCloudAuthServiceFactory>;@@ -68,7 +71,8 @@ export const identityAliCloudAuthServiceFactory = ({membershipIdentityDAL,licenseService,permissionService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityAliCloudAuthServiceFactoryDep) => {const login = async ({ identityId, organizationSlug, ...params }: TLoginAliCloudAuthDTO) => {const appCfg = getConfig();@@ -154,7 +158,7 @@ export const identityAliCloudAuthServiceFactory = ({}// Generate the token- const identityAccessToken = await identityAliCloudAuthDAL.transaction(async (tx) => {+ await identityAliCloudAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -174,35 +178,29 @@ export const identityAliCloudAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityAliCloudAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityAliCloudAuth.accessTokenTTL,- accessTokenMaxTTL: identityAliCloudAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityAliCloudAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.ALICLOUD_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityAliCloudAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityAliCloudAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.ALICLOUD_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityAliCloudAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityAliCloudAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityAliCloudAuth.accessTokenNumUsesLimit),+ // AliCloud auth schema has no accessTokenPeriod column.+ accessTokenPeriod: 0,+ accessTokenTrustedIps: identityAliCloudAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -573,6 +571,12 @@ export const identityAliCloudAuthServiceFactory = ({return { ...deletedAliCloudAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityAliCloudAuth;};diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.tsindex bff0267dd4..2e0976474b 100644--- a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts@@ -15,7 +15,6 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";-import { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -23,17 +22,17 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -51,12 +50,16 @@ import {type TIdentityAwsAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;identityAwsAuthDAL: Pick<TIdentityAwsAuthDALFactory, "findOne" | "transaction" | "create" | "updateById" | "delete">;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityAwsAuthServiceFactory = ReturnType<typeof identityAwsAuthServiceFactory>;@@ -102,7 +105,8 @@ export const identityAwsAuthServiceFactory = ({membershipIdentityDAL,licenseService,permissionService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityAwsAuthServiceFactoryDep) => {const login = async ({identityId,@@ -242,7 +246,7 @@ export const identityAwsAuthServiceFactory = ({}}- const identityAccessToken = await identityAwsAuthDAL.transaction(async (tx) => {+ await identityAwsAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -262,50 +266,42 @@ export const identityAwsAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityAwsAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityAwsAuth.accessTokenTTL,- accessTokenMaxTTL: identityAwsAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityAwsAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.AWS_AUTH,- subOrganizationId- },- tx- );- return newToken;});+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;+const splitArn = extractPrincipalArnEntity(Arn);- const accessToken = crypto.jwt().sign(- {- identityId: identityAwsAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,- identityAuth: {- aws: {- accountId: Account,- arn: Arn,- userId: UserId,-- // Derived from ARN- partition: splitArn.Partition,- service: splitArn.Service,- resourceType: splitArn.Type,- resourceName: splitArn.FriendlyName- }+ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityAwsAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.AWS_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityAwsAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityAwsAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityAwsAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityAwsAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityAwsAuth.accessTokenTrustedIps as TIp[],+ identityAuth: {+ aws: {+ accountId: Account,+ arn: Arn,+ userId: UserId,++ // Derived from ARN+ partition: splitArn.Partition,+ service: splitArn.Service,+ resourceType: splitArn.Type,+ resourceName: splitArn.FriendlyName}- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ }+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -677,6 +673,12 @@ export const identityAwsAuthServiceFactory = ({return { ...deletedAwsAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityAwsAuth;};diff --git a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts b/backend/src/services/identity-azure-auth/identity-azure-auth-service.tsindex c5bc02746a..ee240a2218 100644--- a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts+++ b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts@@ -11,7 +11,6 @@ import {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 { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -19,16 +18,16 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -49,10 +48,14 @@ type TIdentityAzureAuthServiceFactoryDep = {"findOne" | "transaction" | "create" | "updateById" | "delete">;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityAzureAuthServiceFactory = ReturnType<typeof identityAzureAuthServiceFactory>;@@ -64,7 +67,8 @@ export const identityAzureAuthServiceFactory = ({identityAccessTokenDAL,permissionService,licenseService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityAzureAuthServiceFactoryDep) => {const login = async ({ identityId, jwt: azureJwt, organizationSlug }: TLoginAzureAuthDTO) => {const appCfg = getConfig();@@ -158,7 +162,7 @@ export const identityAzureAuthServiceFactory = ({}}- const identityAccessToken = await identityAzureAuthDAL.transaction(async (tx) => {+ await identityAzureAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -178,36 +182,28 @@ export const identityAzureAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityAzureAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityAzureAuth.accessTokenTTL,- accessTokenMaxTTL: identityAzureAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityAzureAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.AZURE_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityAzureAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityAzureAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.AZURE_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityAzureAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityAzureAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityAzureAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityAzureAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityAzureAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -578,6 +574,12 @@ export const identityAzureAuthServiceFactory = ({return { ...deletedAzureAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityAzureAuth;};diff --git a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.tsindex 081bc24b99..421528c208 100644--- a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts+++ b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts@@ -11,7 +11,6 @@ import {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 { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -19,16 +18,16 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -47,10 +46,14 @@ type TIdentityGcpAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identityGcpAuthDAL: Pick<TIdentityGcpAuthDALFactory, "findOne" | "transaction" | "create" | "updateById" | "delete">;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityGcpAuthServiceFactory = ReturnType<typeof identityGcpAuthServiceFactory>;@@ -62,7 +65,8 @@ export const identityGcpAuthServiceFactory = ({identityAccessTokenDAL,permissionService,licenseService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityGcpAuthServiceFactoryDep) => {const login = async ({ identityId, jwt: gcpJwt, organizationSlug }: TLoginGcpAuthDTO) => {const appCfg = getConfig();@@ -201,7 +205,7 @@ export const identityGcpAuthServiceFactory = ({}}- const identityAccessToken = await identityGcpAuthDAL.transaction(async (tx) => {+ await identityGcpAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -221,35 +225,28 @@ export const identityGcpAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityGcpAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityGcpAuth.accessTokenTTL,- accessTokenMaxTTL: identityGcpAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityGcpAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.GCP_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityGcpAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );++ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityGcpAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.GCP_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityGcpAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityGcpAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityGcpAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityGcpAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityGcpAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -626,6 +623,12 @@ export const identityGcpAuthServiceFactory = ({return { ...deletedGcpAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityGcpAuth;};diff --git a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.tsindex 40f2879c3b..60b014bb94 100644--- a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts+++ b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts@@ -28,7 +28,7 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";@@ -36,10 +36,10 @@ import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } fromimport { getValueByDot } from "@app/lib/template/dot-access";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";import { KmsDataKey } from "../kms/kms-types";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";@@ -60,11 +60,15 @@ type TIdentityJwtAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identityJwtAuthDAL: TIdentityJwtAuthDALFactory;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityJwtAuthServiceFactory = ReturnType<typeof identityJwtAuthServiceFactory>;@@ -77,7 +81,8 @@ export const identityJwtAuthServiceFactory = ({licenseService,identityAccessTokenDAL,kmsService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityJwtAuthServiceFactoryDep) => {const login = async ({ identityId, jwt: jwtValue, organizationSlug }: TLoginJwtAuthDTO) => {const appCfg = getConfig();@@ -316,7 +321,7 @@ export const identityJwtAuthServiceFactory = ({}}- const identityAccessToken = await identityJwtAuthDAL.transaction(async (tx) => {+ await identityJwtAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -336,37 +341,28 @@ export const identityJwtAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityJwtAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityJwtAuth.accessTokenTTL,- accessTokenMaxTTL: identityJwtAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityJwtAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.JWT_AUTH,- subOrganizationId- },- tx- );-- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityJwtAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityJwtAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.JWT_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityJwtAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityJwtAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityJwtAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityJwtAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityJwtAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -827,6 +823,11 @@ export const identityJwtAuthServiceFactory = ({return { ...deletedJwtAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});+ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityJwtAuth;};diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.tsindex 3edb55a657..c09ea24412 100644--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts@@ -33,7 +33,6 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";-import { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -43,17 +42,17 @@ import {} from "@app/lib/errors";import { GatewayHttpProxyActions, GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";import { KmsDataKey } from "../kms/kms-types";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";@@ -83,7 +82,7 @@ type TIdentityKubernetesAuthServiceFactoryDep = {TIdentityKubernetesAuthDALFactory,"create" | "findOne" | "transaction" | "updateById" | "delete">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;@@ -98,6 +97,10 @@ type TIdentityKubernetesAuthServiceFactoryDep = {>;gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityKubernetesAuthServiceFactory = ReturnType<typeof identityKubernetesAuthServiceFactory>;@@ -118,7 +121,8 @@ export const identityKubernetesAuthServiceFactory = ({kmsService,gatewayPoolService,gatewayPoolDAL,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityKubernetesAuthServiceFactoryDep) => {const $gatewayProxyWrapper = async <T>(inputs: {@@ -662,7 +666,7 @@ export const identityKubernetesAuthServiceFactory = ({}}- const identityAccessToken = await identityKubernetesAuthDAL.transaction(async (tx) => {+ await identityKubernetesAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -682,42 +686,34 @@ export const identityKubernetesAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityKubernetesAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityKubernetesAuth.accessTokenTTL,- accessTokenMaxTTL: identityKubernetesAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityKubernetesAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.KUBERNETES_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityKubernetesAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,- identityAuth: {- kubernetes: {- namespace: targetNamespace,- name: targetName- }+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityKubernetesAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.KUBERNETES_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityKubernetesAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityKubernetesAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityKubernetesAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityKubernetesAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityKubernetesAuth.accessTokenTrustedIps as TIp[],+ identityAuth: {+ kubernetes: {+ namespace: targetNamespace,+ name: targetName}- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ }+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -1544,6 +1540,12 @@ export const identityKubernetesAuthServiceFactory = ({await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.KUBERNETES_AUTH }, tx);return { ...deletedKubernetesAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityKubernetesAuth;};diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.tsindex 5b6a3f4e87..2c5f1ade82 100644--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts@@ -20,7 +20,6 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";-import { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -29,7 +28,7 @@ import {RateLimitError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";@@ -37,10 +36,10 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";import { KmsDataKey } from "../kms/kms-types";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";@@ -59,7 +58,7 @@ import {} from "./identity-ldap-auth-types";type TIdentityLdapAuthServiceFactoryDep = {- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;identityLdapAuthDAL: Pick<TIdentityLdapAuthDALFactory,"findOne" | "transaction" | "create" | "updateById" | "delete"@@ -75,6 +74,10 @@ type TIdentityLdapAuthServiceFactoryDep = {"setItemWithExpiry" | "getItem" | "deleteItem" | "getKeysByPattern" | "deleteItems" | "acquireLock">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityLdapAuthServiceFactory = ReturnType<typeof identityLdapAuthServiceFactory>;@@ -94,7 +97,8 @@ export const identityLdapAuthServiceFactory = ({kmsService,identityAuthTemplateDAL,keyStore,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityLdapAuthServiceFactoryDep) => {const getLdapConfig = async (identityId: string) => {const identity = await identityDAL.findOne({ id: identityId });@@ -221,7 +225,7 @@ export const identityLdapAuthServiceFactory = ({}try {- const identityAccessToken = await identityLdapAuthDAL.transaction(async (tx) => {+ await identityLdapAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -241,36 +245,28 @@ export const identityLdapAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityLdapAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityLdapAuth.accessTokenTTL,- accessTokenMaxTTL: identityLdapAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.LDAP_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityLdapAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityLdapAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.LDAP_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityLdapAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityLdapAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityLdapAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityLdapAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityLdapAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -867,6 +863,12 @@ export const identityLdapAuthServiceFactory = ({return { ...deletedLdapAuth, orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityLdapAuth;};diff --git a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts b/backend/src/services/identity-oci-auth/identity-oci-auth-service.tsindex a9ac998494..bc432609a4 100644--- a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts+++ b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts@@ -15,7 +15,6 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";-import { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -23,17 +22,17 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -49,12 +48,16 @@ import {type TIdentityOciAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;identityOciAuthDAL: Pick<TIdentityOciAuthDALFactory, "findOne" | "transaction" | "create" | "updateById" | "delete">;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityOciAuthServiceFactory = ReturnType<typeof identityOciAuthServiceFactory>;@@ -66,7 +69,8 @@ export const identityOciAuthServiceFactory = ({membershipIdentityDAL,licenseService,permissionService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityOciAuthServiceFactoryDep) => {const login = async ({ identityId, headers, userOcid, organizationSlug }: TLoginOciAuthDTO) => {const appCfg = getConfig();@@ -166,7 +170,7 @@ export const identityOciAuthServiceFactory = ({}// Generate the token- const identityAccessToken = await identityOciAuthDAL.transaction(async (tx) => {+ await identityOciAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -186,35 +190,28 @@ export const identityOciAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityOciAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityOciAuth.accessTokenTTL,- accessTokenMaxTTL: identityOciAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityOciAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.OCI_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityOciAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityOciAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.OCI_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityOciAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityOciAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityOciAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityOciAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityOciAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -590,6 +587,12 @@ export const identityOciAuthServiceFactory = ({return { ...deletedOciAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityOciAuth;};diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.tsindex fb03d4b383..3d0148ccb4 100644--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts@@ -29,7 +29,7 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";@@ -38,10 +38,10 @@ import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } fromimport { getValueByDot } from "@app/lib/template/dot-access";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";import { KmsDataKey } from "../kms/kms-types";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";@@ -61,11 +61,15 @@ type TIdentityOidcAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identityOidcAuthDAL: TIdentityOidcAuthDALFactory;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentityOidcAuthServiceFactory = ReturnType<typeof identityOidcAuthServiceFactory>;@@ -78,7 +82,8 @@ export const identityOidcAuthServiceFactory = ({licenseService,identityAccessTokenDAL,kmsService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityOidcAuthServiceFactoryDep) => {const login = async ({ identityId, jwt: oidcJwt, organizationSlug }: TLoginOidcAuthDTO) => {const appCfg = getConfig();@@ -426,7 +431,7 @@ export const identityOidcAuthServiceFactory = ({}}- const identityAccessToken = await identityOidcAuthDAL.transaction(async (tx) => {+ await identityOidcAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -446,41 +451,33 @@ export const identityOidcAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityOidcAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityOidcAuth.accessTokenTTL,- accessTokenMaxTTL: identityOidcAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityOidcAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.OIDC_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityOidcAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN,- identityAuth: {- oidc: {- claims: filteredClaims- }+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityOidcAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.OIDC_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityOidcAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityOidcAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityOidcAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityOidcAuth.accessTokenPeriod) || 0,+ accessTokenTrustedIps: identityOidcAuth.accessTokenTrustedIps as TIp[],+ identityAuth: {+ oidc: {+ claims: filteredClaims}- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ }+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -910,6 +907,11 @@ export const identityOidcAuthServiceFactory = ({return { ...deletedOidcAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});+ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityOidcAuth;};diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.tsindex 947db86512..d4b5a02afd 100644--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts@@ -19,7 +19,6 @@ import {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 { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -27,7 +26,7 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";@@ -35,10 +34,10 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";import { KmsDataKey } from "../kms/kms-types";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";@@ -67,11 +66,15 @@ type TIdentitySpiffeAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identitySpiffeAuthDAL: TIdentitySpiffeAuthDALFactory;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};export type TIdentitySpiffeAuthServiceFactory = ReturnType<typeof identitySpiffeAuthServiceFactory>;@@ -128,7 +131,8 @@ export const identitySpiffeAuthServiceFactory = ({licenseService,identityAccessTokenDAL,kmsService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentitySpiffeAuthServiceFactoryDep) => {type TFlattenedTrustBundle = {configurationType: string;@@ -395,7 +399,7 @@ export const identitySpiffeAuthServiceFactory = ({}}- const identityAccessToken = await identitySpiffeAuthDAL.transaction(async (tx) => {+ await identitySpiffeAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -415,38 +419,28 @@ export const identitySpiffeAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identitySpiffeAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identitySpiffeAuth.accessTokenTTL,- accessTokenMaxTTL: identitySpiffeAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identitySpiffeAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.SPIFFE_AUTH,- subOrganizationId- },- tx- );-- return newToken;});- let expireyOptions: { expiresIn: number } | undefined;- const accessTokenTTL = Number(identityAccessToken.accessTokenTTL);- if (accessTokenTTL > 0) {- expireyOptions = { expiresIn: accessTokenTTL };- }-- const accessToken = crypto.jwt().sign(- {- identityId: identitySpiffeAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- expireyOptions- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identitySpiffeAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.SPIFFE_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identitySpiffeAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identitySpiffeAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identitySpiffeAuth.accessTokenNumUsesLimit),+ accessTokenPeriod: 0,+ accessTokenTrustedIps: identitySpiffeAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -924,6 +918,11 @@ export const identitySpiffeAuthServiceFactory = ({return deletedSpiffeAuth?.[0];});+ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,orgId: identityMembershipOrg.scopeOrgIddiff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.tsindex ce43d78095..d55528a652 100644--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts@@ -20,16 +20,16 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TKmsServiceFactory } from "../kms/kms-service";import { KmsDataKey } from "../kms/kms-types";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";@@ -40,7 +40,7 @@ import { TIdentityTlsCertAuthServiceFactory } from "./identity-tls-cert-auth-typtype TIdentityTlsCertAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;- identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "create" | "delete">;+ identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;identityTlsCertAuthDAL: Pick<TIdentityTlsCertAuthDALFactory,"findOne" | "transaction" | "create" | "updateById" | "delete"@@ -50,6 +50,10 @@ type TIdentityTlsCertAuthServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;};const parseSubjectDetails = (data: string) => {@@ -71,7 +75,8 @@ export const identityTlsCertAuthServiceFactory = ({licenseService,permissionService,kmsService,- orgDAL+ orgDAL,+ identityAccessTokenService}: TIdentityTlsCertAuthServiceFactoryDep): TIdentityTlsCertAuthServiceFactory => {const login: TIdentityTlsCertAuthServiceFactory["login"] = async ({identityId,@@ -203,7 +208,7 @@ export const identityTlsCertAuthServiceFactory = ({}// Generate the token- const identityAccessToken = await identityTlsCertAuthDAL.transaction(async (tx) => {+ await identityTlsCertAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -223,35 +228,29 @@ export const identityTlsCertAuthServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityTlsCertAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityTlsCertAuth.accessTokenTTL,- accessTokenMaxTTL: identityTlsCertAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityTlsCertAuth.accessTokenNumUsesLimit,- authMethod: IdentityAuthMethod.TLS_CERT_AUTH,- subOrganizationId- },- tx- );- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityTlsCertAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityTlsCertAuth.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.TLS_CERT_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityTlsCertAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityTlsCertAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityTlsCertAuth.accessTokenNumUsesLimit),+ // TLS Cert auth schema has no accessTokenPeriod column.+ accessTokenPeriod: 0,+ accessTokenTrustedIps: identityTlsCertAuth.accessTokenTrustedIps as TIp[]+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -651,6 +650,12 @@ export const identityTlsCertAuthServiceFactory = ({return { ...deletedTlsCertAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityTlsCertAuth;};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.tsindex 7e038b2d72..0e5abfa0ac 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@@ -16,7 +16,6 @@ import {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 { crypto } from "@app/lib/crypto";import {BadRequestError,ForbiddenRequestError,@@ -24,13 +23,13 @@ import {PermissionBoundaryError,UnauthorizedError} from "@app/lib/errors";-import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";+import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -57,6 +56,10 @@ type TIdentityTokenAuthServiceFactoryDep = {TIdentityAccessTokenDALFactory,"create" | "find" | "update" | "findById" | "findOne" | "updateById" | "delete">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity" | "markPerTokenRevocation"+ >;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;@@ -68,6 +71,7 @@ export const identityTokenAuthServiceFactory = ({identityTokenAuthDAL,membershipIdentityDAL,identityAccessTokenDAL,+ identityAccessTokenService,permissionService,licenseService,orgDAL@@ -416,6 +420,12 @@ export const identityTokenAuthServiceFactory = ({return { ...deletedTokenAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Detaching the auth method must invalidate any tokens already issued+ // through it; without this, leaked tokens authenticate up to MAX_AGE+ // even after the admin pulled the auth method.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityTokenAuth;};@@ -540,7 +550,17 @@ export const identityTokenAuthServiceFactory = ({}}- const identityAccessToken = await identityTokenAuthDAL.transaction(async (tx) => {+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ // Token Auth is the only auth method that materializes a real PG row at+ // issuance time — its tokens are admin-managed and listed in the UI, so+ // we hand the helper a transaction so the row insert and the+ // membership-update happen atomically.+ const { accessToken, identityAccessToken } = await identityTokenAuthDAL.transaction(async (tx) => {await membershipIdentityDAL.update(identity.projectId? {@@ -557,38 +577,24 @@ export const identityTokenAuthServiceFactory = ({{ lastLoginAuthMethod: IdentityAuthMethod.TOKEN_AUTH, lastLoginTime: new Date() },tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityTokenAuth.identityId,- isAccessTokenRevoked: false,- accessTokenTTL: identityTokenAuth.accessTokenTTL,- accessTokenMaxTTL: identityTokenAuth.accessTokenMaxTTL,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityTokenAuth.accessTokenNumUsesLimit,- name,- authMethod: IdentityAuthMethod.TOKEN_AUTH,- subOrganizationId- },- tx- );- return newToken;- });- const appCfg = getConfig();- const accessToken = crypto.jwt().sign(- {- identityId: identityTokenAuth.identityId,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ return identityAccessTokenService.issueIdentityAccessToken({+ identityId: identity.id,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.TOKEN_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityTokenAuth.accessTokenTTL),+ accessTokenMaxTTL: Number(identityTokenAuth.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityTokenAuth.accessTokenNumUsesLimit),+ // Token Auth schema has no accessTokenPeriod column.+ accessTokenPeriod: 0,+ accessTokenTrustedIps: identityTokenAuth.accessTokenTrustedIps as TIp[],+ persistToPg: { tx, name }+ });+ });return { accessToken, identityTokenAuth, identityAccessToken, identity };};@@ -888,6 +894,25 @@ 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);+ }+ await identityAccessTokenService.markPerTokenRevocation({+ tokenId: identityAccessToken.id,+ identityId: identityAccessToken.identityId,+ expiresAt+ });+return { revokedToken };};diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.tsindex bd74cd25e1..6438f85db2 100644--- a/backend/src/services/identity-ua/identity-ua-service.ts+++ b/backend/src/services/identity-ua/identity-ua-service.ts@@ -28,10 +28,9 @@ import { RequestContextKey } from "@app/lib/request-context/request-context-keysimport { requestMemoize } from "@app/lib/request-context/request-memoizer";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";-import { ActorType, AuthTokenType } from "../auth/auth-type";+import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";-import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";-import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identity-access-token-types";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TOrgDALFactory } from "../org/org-dal";import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";@@ -54,11 +53,14 @@ type TIdentityUaServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identityUaDAL: TIdentityUaDALFactory;identityUaClientSecretDAL: TIdentityUaClientSecretDALFactory;- identityAccessTokenDAL: TIdentityAccessTokenDALFactory;membershipIdentityDAL: TMembershipIdentityDALFactory;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;+ identityAccessTokenService: Pick<+ TIdentityAccessTokenServiceFactory,+ "issueIdentityAccessToken" | "revokeAllTokensForIdentity"+ >;keyStore: Pick<TKeyStoreFactory,"setItemWithExpiry" | "getItem" | "deleteItem" | "getKeysByPattern" | "deleteItems" | "acquireLock"@@ -75,13 +77,13 @@ type LockoutObject = {export const identityUaServiceFactory = ({identityUaDAL,identityUaClientSecretDAL,- identityAccessTokenDAL,membershipIdentityDAL,permissionService,licenseService,orgDAL,keyStore,- identityDAL+ identityDAL,+ identityAccessTokenService}: TIdentityUaServiceFactoryDep) => {const login = async ({ clientId, clientSecret, ip, organizationSlug }: TLoginUaDTO) => {const appCfg = getConfig();@@ -265,19 +267,6 @@ export const identityUaServiceFactory = ({});}- const accessTokenTTLParams =- Number(identityUa.accessTokenPeriod) === 0- ? {- accessTokenTTL: identityUa.accessTokenTTL,- accessTokenMaxTTL: identityUa.accessTokenMaxTTL- }- : {- accessTokenTTL: identityUa.accessTokenPeriod,- // We set a very large Max TTL for periodic tokens to ensure that clients (even outdated ones) can always renew their token- // without them having to update their SDKs, CLIs, etc. This workaround sets it to 30 years to emulate "forever"- accessTokenMaxTTL: 1000000000- };-if (organizationSlug && org.slug !== organizationSlug) {if (!isSubOrgIdentity) {const subOrg = await orgDAL.findOne({ rootOrgId: org.id, slug: organizationSlug });@@ -309,8 +298,8 @@ export const identityUaServiceFactory = ({}}- const identityAccessToken = await identityUaDAL.transaction(async (tx) => {- const uaClientSecretDoc = await identityUaClientSecretDAL.incrementUsage(validClientSecretInfo!.id, tx);+ await identityUaDAL.transaction(async (tx) => {+ await identityUaClientSecretDAL.incrementUsage(validClientSecretInfo!.id, tx);await membershipIdentityDAL.update(identity.projectId? {@@ -330,39 +319,29 @@ export const identityUaServiceFactory = ({},tx);- const newToken = await identityAccessTokenDAL.create(- {- identityId: identityUa.identityId,- isAccessTokenRevoked: false,- identityUAClientSecretId: uaClientSecretDoc.id,- accessTokenNumUses: 0,- accessTokenNumUsesLimit: identityUa.accessTokenNumUsesLimit,- accessTokenPeriod: identityUa.accessTokenPeriod,- authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,- subOrganizationId,- ...accessTokenTTLParams- },- tx- );-- return newToken;});- const accessToken = crypto.jwt().sign(- {- identityId: identityUa.identityId,- clientSecretId: validClientSecretInfo.id,- identityAccessTokenId: identityAccessToken.id,- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN- } as TIdentityAccessTokenJwtPayload,- appCfg.AUTH_SECRET,- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error- Number(identityAccessToken.accessTokenTTL) === 0- ? undefined- : {- expiresIn: Number(identityAccessToken.accessTokenTTL)- }- );+ const subOrgDetails =+ subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;+ const tokenScopeOrg = subOrgDetails ?? org;+ const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;+ const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;++ const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({+ identityId: identityUa.identityId,+ identityName: identity.name,+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,+ orgId: tokenScopeOrg.id,+ rootOrgId: tokenRootOrgId,+ parentOrgId: tokenParentOrgId,+ subOrganizationId,+ accessTokenTTL: Number(identityUa.accessTokenTTL),+ accessTokenMaxTTL: Number(identityUa.accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(identityUa.accessTokenNumUsesLimit),+ accessTokenPeriod: Number(identityUa.accessTokenPeriod),+ accessTokenTrustedIps: identityUa.accessTokenTrustedIps as TIp[],+ clientSecretId: validClientSecretInfo.id+ });if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {authAttemptCounter.add(1, {@@ -383,7 +362,8 @@ export const identityUaServiceFactory = ({validClientSecretInfo,identityAccessToken,identity,- ...accessTokenTTLParams+ accessTokenTTL: identityAccessToken.accessTokenTTL,+ accessTokenMaxTTL: identityAccessToken.accessTokenMaxTTL};} catch (error) {if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {@@ -794,6 +774,15 @@ export const identityUaServiceFactory = ({const deletedUniversalAuth = await identityUaDAL.delete({ identityId }, tx);return { ...deletedUniversalAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };});++ // Revoking the auth method must invalidate any access tokens already+ // issued via it — without this, leaked tokens keep authenticating up+ // to MAX_MACHINE_IDENTITY_TOKEN_AGE even after an admin pulled the+ // method. The marker is identity-wide (matches the existing semantics+ // of identity deletion) which is acceptable here because detaching an+ // auth method is a high-trust admin action.+ await identityAccessTokenService.revokeAllTokensForIdentity(identityId);+return revokedIdentityUniversalAuth;};diff --git a/backend/src/services/identity-v2/identity-service.ts b/backend/src/services/identity-v2/identity-service.tsindex a0b3bb4a5b..002241c3ec 100644--- a/backend/src/services/identity-v2/identity-service.ts+++ b/backend/src/services/identity-v2/identity-service.ts@@ -6,6 +6,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { getIdentityActiveLockoutAuthMethods } from "@app/services/identity-v2/identity-fns";import { TIdentityMetadataDALFactory } from "../identity/identity-metadata-dal";+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";import { TIdentityV2DALFactory } from "./identity-dal";@@ -26,6 +27,7 @@ type TScopedIdentityV2ServiceFactoryDep = {membershipIdentityDAL: TMembershipIdentityDALFactory;membershipRoleDAL: TMembershipRoleDALFactory;identityMetadataDAL: TIdentityMetadataDALFactory;+ identityAccessTokenService: Pick<TIdentityAccessTokenServiceFactory, "revokeAllTokensForIdentity">;keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;};@@ -38,6 +40,7 @@ export const identityV2ServiceFactory = ({membershipIdentityDAL,membershipRoleDAL,identityMetadataDAL,+ identityAccessTokenService,keyStore}: TScopedIdentityV2ServiceFactoryDep) => {const orgFactory = newOrgIdentityFactory({@@ -206,6 +209,12 @@ export const identityV2ServiceFactory = ({throw new BadRequestError({ message: "Cannot delete identity while delete protection is enabled" });}+ // Set the identity-wide revocation epoch in Redis before removing the+ // row so that any JWT issued for this identity (with iat < now) is+ // immediately rejected on the auth path. The revoke also async-mirrors+ // a sentinel row to PG for the boot-time hydrator.+ await identityAccessTokenService.revokeAllTokensForIdentity(dto.selector.identityId);+const deletedIdentity = await identityDAL.deleteById(dto.selector.identityId);await licenseService.updateSubscriptionOrgMemberCount(scopeData.orgId);diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex c545a18fa1..07f5269799 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -12,6 +12,7 @@ import { TUserNotificationDALFactory } from "@app/services/notification/user-notimport { TApprovalRequestDALFactory, TApprovalRequestGrantsDALFactory } from "../approval-policy/approval-request-dal";import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";+import { TIdentityAccessTokenRevocationDALFactory } from "../identity-access-token/identity-access-token-revocation-dal";import { TIdentityUaClientSecretDALFactory } from "../identity-ua/identity-ua-client-secret-dal";import { TOrgServiceFactory } from "../org/org-service";import { TSecretVersionDALFactory } from "../secret/secret-version-dal";@@ -24,6 +25,7 @@ type TDailyResourceCleanUpQueueServiceFactoryDep = {auditLogDAL: Pick<TAuditLogDALFactory, "pruneAuditLog">;auditLogService: Pick<TAuditLogServiceFactory, "checkPostgresAuditLogVolumeMigrationAlert">;identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "removeExpiredTokens">;+ identityAccessTokenRevocationDAL: Pick<TIdentityAccessTokenRevocationDALFactory, "removeExpiredRevocations">;identityUniversalAuthClientSecretDAL: Pick<TIdentityUaClientSecretDALFactory, "removeExpiredClientSecrets">;secretVersionDAL: Pick<TSecretVersionDALFactory, "pruneExcessVersions">;secretVersionV2DAL: Pick<TSecretVersionV2DALFactory, "pruneExcessVersions">;@@ -54,6 +56,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({secretSharingDAL,secretVersionV2DAL,identityAccessTokenDAL,+ identityAccessTokenRevocationDAL,identityUniversalAuthClientSecretDAL,serviceTokenService,scimService,@@ -98,6 +101,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);}await approvalRequestGrantsDAL.markExpiredGrants();+ await identityAccessTokenRevocationDAL.removeExpiredRevocations();await auditLogDAL.pruneAuditLog();logger.info(`${QueueName.DailyResourceCleanUp}: queue task completed`);} catch (error) {diff --git a/frontend/src/helpers/datetime.ts b/frontend/src/helpers/datetime.tsindex d8a5e90c62..74e272b897 100644--- a/frontend/src/helpers/datetime.ts+++ b/frontend/src/helpers/datetime.ts@@ -23,6 +23,8 @@ export const formatDateTime = ({return format(date, dateFormat);};+export const SECONDS_PER_DAY = 86400;+// Helper function to convert seconds to value and unitexport const getObjectFromSeconds = (totalSeconds: number,diff --git a/frontend/src/helpers/identityAuthSchemas.ts b/frontend/src/helpers/identityAuthSchemas.tsnew file mode 100644index 0000000000..9abba65049--- /dev/null+++ b/frontend/src/helpers/identityAuthSchemas.ts@@ -0,0 +1,15 @@+import { z } from "zod";++import { SECONDS_PER_DAY } from "./datetime";++// Fallback used by identity auth forms when the server's configured+// `MAX_MACHINE_IDENTITY_TOKEN_AGE` is unavailable (e.g. server status hasn't+// loaded yet). 90 days, matching the backend default.+export const MAX_IDENTITY_ACCESS_TOKEN_TTL_FALLBACK = 7_776_000;++// Returns a z.string() with the server-enforced TTL upper-bound refine applied.+// Chain .optional() after for optional fields (e.g. accessTokenPeriod).+export const accessTokenTtlSchema = (maxTTL: number, label: string) =>+ z.string().refine((val) => !val || Number(val) <= maxTTL, {+ message: `${label} cannot exceed ${Math.floor(maxTTL / SECONDS_PER_DAY)} days`+ });diff --git a/frontend/src/hooks/api/serverDetails/types.ts b/frontend/src/hooks/api/serverDetails/types.tsindex d435213829..a8c5f1cb05 100644--- a/frontend/src/hooks/api/serverDetails/types.ts+++ b/frontend/src/hooks/api/serverDetails/types.ts@@ -6,4 +6,5 @@ export type ServerStatus = {redisConfigured: boolean;samlDefaultOrgSlug: string;auditLogStorageDisabled: boolean;+ maxIdentityAccessTokenTTL?: number;};diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsxindex 2e72cdee2a..620780191e 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -18,6 +18,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityAliCloudAuth,useGetIdentityAliCloudAuth,@@ -28,32 +30,23 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z- .object({- allowedArns: z.string().min(1, "Required"),- accessTokenTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token TTL cannot be greater than 315360000"- ),- accessTokenMaxTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token Max TTL cannot be greater than 315360000"- ),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .object({- ipAddress: z.string().max(50)- })- .array()- .min(1)- })- .required();+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ allowedArns: z.string().min(1, "Required"),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .object({+ ipAddress: z.string().max(50)+ })+ .array()+ .min(1)+ })+ .required();-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -66,13 +59,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityAliCloudAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -88,13 +83,16 @@ export const IdentityAliCloudAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {allowedArns: "",accessTokenTTL: "2592000",@@ -221,8 +219,9 @@ export const IdentityAliCloudAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -235,8 +234,9 @@ export const IdentityAliCloudAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsxindex ab667c7582..1c465895c5 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx@@ -6,7 +6,9 @@ import { z } from "zod";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";import { FormControl, Select, SelectItem, Tooltip } from "@app/components/v2";import { Badge } from "@app/components/v3";+import { MAX_IDENTITY_ACCESS_TOKEN_TTL_FALLBACK } from "@app/helpers/identityAuthSchemas";import { IdentityAuthMethod } from "@app/hooks/api/identities";+import { useFetchServerStatus } from "@app/hooks/api/serverDetails";import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityAliCloudAuthForm } from "./IdentityAliCloudAuthForm";@@ -103,6 +105,10 @@ export const IdentityAuthMethodModalContent = ({const watchedAuthMethod = watch("authMethod");+ const { data: serverStatus } = useFetchServerStatus();+ const maxAccessTokenTTL =+ serverStatus?.maxIdentityAccessTokenTTL ?? MAX_IDENTITY_ACCESS_TOKEN_TTL_FALLBACK;+const identityAuthMethodData = {identityId: identity.id,name: identity.name,@@ -125,6 +131,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -134,6 +141,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -144,6 +152,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -154,6 +163,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -164,6 +174,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -174,6 +185,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -184,6 +196,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -194,6 +207,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -204,6 +218,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -214,6 +229,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -224,6 +240,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -234,6 +251,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)},@@ -244,6 +262,7 @@ export const IdentityAuthMethodModalContent = ({identityId={identityAuthMethodData.identityId}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}+ maxAccessTokenTTL={maxAccessTokenTTL}/>)}diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsxindex 38d3fd2d28..72baed4571 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -18,6 +18,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityAwsAuth,useGetIdentityAwsAuth,@@ -28,34 +30,25 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z- .object({- stsEndpoint: z.string(),- allowedPrincipalArns: z.string(),- allowedAccountIds: z.string(),- accessTokenTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token TTL cannot be greater than 315360000"- ),- accessTokenMaxTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token Max TTL cannot be greater than 315360000"- ),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .object({- ipAddress: z.string().max(50)- })- .array()- .min(1)- })- .required();+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ stsEndpoint: z.string(),+ allowedPrincipalArns: z.string(),+ allowedAccountIds: z.string(),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .object({+ ipAddress: z.string().max(50)+ })+ .array()+ .min(1)+ })+ .required();-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -68,13 +61,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityAwsAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -90,13 +85,16 @@ export const IdentityAwsAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {stsEndpoint: "https://sts.amazonaws.com/",allowedPrincipalArns: "",@@ -257,8 +255,9 @@ export const IdentityAwsAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -271,8 +270,9 @@ export const IdentityAwsAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsxindex ca33928288..e2abcc6e46 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -18,6 +18,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityAzureAuth,useGetIdentityAzureAuth,@@ -28,29 +30,26 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z- .object({- tenantId: z.string().min(1),- resource: z.string(),- allowedServicePrincipalIds: z.string(),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1)- })- .required();+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ tenantId: z.string().min(1),+ resource: z.string(),+ allowedServicePrincipalIds: z.string(),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1)+ })+ .required();-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -63,13 +62,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityAzureAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -85,6 +86,9 @@ export const IdentityAzureAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,@@ -92,7 +96,7 @@ export const IdentityAzureAuthForm = ({formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {tenantId: "",resource: "https://management.azure.com/",@@ -255,8 +259,9 @@ export const IdentityAzureAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -269,8 +274,9 @@ export const IdentityAzureAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsxindex 8fda6d3b94..17fc4acdf3 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -20,6 +20,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityGcpAuth,useGetIdentityGcpAuth,@@ -30,30 +32,27 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z- .object({- type: z.enum(["iam", "gce"]),- allowedServiceAccounts: z.string(),- allowedProjects: z.string(),- allowedZones: z.string(),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1)- })- .required();+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ type: z.enum(["iam", "gce"]),+ allowedServiceAccounts: z.string(),+ allowedProjects: z.string(),+ allowedZones: z.string(),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1)+ })+ .required();-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -66,13 +65,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityGcpAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -88,6 +89,9 @@ export const IdentityGcpAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,@@ -95,7 +99,7 @@ export const IdentityGcpAuthForm = ({formState: { isSubmitting },watch} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {type: "gce",allowedServiceAccounts: "",@@ -293,8 +297,9 @@ export const IdentityGcpAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -307,8 +312,9 @@ export const IdentityGcpAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsxindex 3e15556cf1..4085dc01e9 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-regular-svg-icons";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";@@ -24,6 +24,8 @@ import {Tooltip} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import { useAddIdentityJwtAuth, useUpdateIdentityJwtAuth } from "@app/hooks/api";import { IdentityJwtConfigurationType } from "@app/hooks/api/identities/enums";import { useGetIdentityJwtAuth } from "@app/hooks/api/identities/queries";@@ -32,62 +34,60 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const commonSchema = z.object({- accessTokenTrustedIps: z- .array(+const buildSchema = (maxAccessTokenTTL: number) => {+ const common = z.object({+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ boundIssuer: z.string().trim().default(""),+ boundAudiences: z.string().optional().default(""),+ boundClaims: z.array(z.object({- ipAddress: z.string().max(50)+ key: z.string(),+ value: z.string()})- )- .min(1),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- boundIssuer: z.string().trim().default(""),- boundAudiences: z.string().optional().default(""),- boundClaims: z.array(- z.object({- key: z.string(),- value: z.string()- })- ),- boundSubject: z.string().optional().default("")-});+ ),+ boundSubject: z.string().optional().default("")+ });-const schema = z.discriminatedUnion("configurationType", [- z- .object({- configurationType: z.literal(IdentityJwtConfigurationType.JWKS),- jwksUrl: z.string().trim().url(),- jwksCaCert: z.string().trim().default(""),- publicKeys: z- .object({- value: z.string()- })- .array()- .optional()- })- .merge(commonSchema),- z- .object({- configurationType: z.literal(IdentityJwtConfigurationType.STATIC),- jwksUrl: z.string().trim().optional(),- jwksCaCert: z.string().trim().optional().default(""),- publicKeys: z- .object({- value: z.string().min(1)- })- .array()- .min(1)- })- .merge(commonSchema)-]);+ return z.discriminatedUnion("configurationType", [+ z+ .object({+ configurationType: z.literal(IdentityJwtConfigurationType.JWKS),+ jwksUrl: z.string().trim().url(),+ jwksCaCert: z.string().trim().default(""),+ publicKeys: z+ .object({+ value: z.string()+ })+ .array()+ .optional()+ })+ .merge(common),+ z+ .object({+ configurationType: z.literal(IdentityJwtConfigurationType.STATIC),+ jwksUrl: z.string().trim().optional(),+ jwksCaCert: z.string().trim().optional().default(""),+ publicKeys: z+ .object({+ value: z.string().min(1)+ })+ .array()+ .min(1)+ })+ .merge(common)+ ]);+};-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -100,13 +100,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityJwtAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -122,6 +124,9 @@ export const IdentityJwtAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {watch,control,@@ -130,7 +135,7 @@ export const IdentityJwtAuthForm = ({setValue,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {accessTokenTTL: "2592000",accessTokenMaxTTL: "2592000",@@ -554,8 +559,9 @@ export const IdentityJwtAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -568,8 +574,9 @@ export const IdentityJwtAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsxindex f4535ce9ab..ae96540f3c 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faInfoCircle, faPlus, faQuestionCircle, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -29,6 +29,8 @@ import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import { OrgMembershipRole } from "@app/helpers/roles";import {useAddIdentityKubernetesAuth,@@ -49,87 +51,84 @@ import { usePopUp, UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";import { VaultKubernetesAuthImportModal } from "./VaultKubernetesAuthImportModal";-const schema = z- .object({- tokenReviewMode: z- .nativeEnum(IdentityKubernetesAuthTokenReviewMode)- .default(IdentityKubernetesAuthTokenReviewMode.Api),- kubernetesHost: z.string().optional().nullable(),- tokenReviewerJwt: z.string().optional(),- gatewayId: z.string().optional().nullable(),- gatewayPoolId: z.string().optional().nullable(),- allowedNames: z.string(),- allowedNamespaces: z.string(),- allowedAudience: z.string(),- caCert: z.string().optional(),- verifyTlsCertificate: z.boolean().default(true),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1)- })- .superRefine((data, ctx) => {- if (- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&- !data.kubernetesHost?.length- ) {- ctx.addIssue({- path: ["kubernetesHost"],- code: z.ZodIssueCode.custom,- message: "When token review mode is set to API, a Kubernetes host must be provided"- });- }+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ tokenReviewMode: z+ .nativeEnum(IdentityKubernetesAuthTokenReviewMode)+ .default(IdentityKubernetesAuthTokenReviewMode.Api),+ kubernetesHost: z.string().optional().nullable(),+ tokenReviewerJwt: z.string().optional(),+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable(),+ allowedNames: z.string(),+ allowedNamespaces: z.string(),+ allowedAudience: z.string(),+ caCert: z.string().optional(),+ verifyTlsCertificate: z.boolean().default(true),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1)+ })+ .superRefine((data, ctx) => {+ if (+ data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&+ !data.kubernetesHost?.length+ ) {+ ctx.addIssue({+ path: ["kubernetesHost"],+ code: z.ZodIssueCode.custom,+ message: "When token review mode is set to API, a Kubernetes host must be provided"+ });+ }- if (- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&- !data.gatewayId &&- !data.gatewayPoolId- ) {- ctx.addIssue({- path: ["gatewayId"],- code: z.ZodIssueCode.custom,- message:- "When token review mode is set to Gateway, a gateway or gateway pool must be selected"- });- }+ if (+ data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&+ !data.gatewayId &&+ !data.gatewayPoolId+ ) {+ ctx.addIssue({+ path: ["gatewayId"],+ code: z.ZodIssueCode.custom,+ message:+ "When token review mode is set to Gateway, a gateway or gateway pool must be selected"+ });+ }- if (- data.verifyTlsCertificate &&- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&- !data.caCert?.length- ) {- ctx.addIssue({- path: ["caCert"],- code: z.ZodIssueCode.custom,- message: "A CA certificate is required when TLS certificate verification is enabled."- });- }+ if (+ data.verifyTlsCertificate &&+ data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&+ !data.caCert?.length+ ) {+ ctx.addIssue({+ path: ["caCert"],+ code: z.ZodIssueCode.custom,+ message: "A CA certificate is required when TLS certificate verification is enabled."+ });+ }- if (- data.verifyTlsCertificate === false &&- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&- data.caCert?.length- ) {- ctx.addIssue({- path: ["verifyTlsCertificate"],- code: z.ZodIssueCode.custom,- message:- "TLS certificate verification cannot be disabled while a CA certificate is provided. Either remove the CA certificate or enable verification."- });- }- });+ if (+ data.verifyTlsCertificate === false &&+ data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&+ data.caCert?.length+ ) {+ ctx.addIssue({+ path: ["verifyTlsCertificate"],+ code: z.ZodIssueCode.custom,+ message:+ "TLS certificate verification cannot be disabled while a CA certificate is provided. Either remove the CA certificate or enable verification."+ });+ }+ });-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -142,13 +141,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityKubernetesAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -174,6 +175,9 @@ export const IdentityKubernetesAuthForm = ({const { hasOrgRole } = useOrgPermission();const isOrgAdmin = hasOrgRole(OrgMembershipRole.Admin);+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,@@ -183,7 +187,7 @@ export const IdentityKubernetesAuthForm = ({formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,kubernetesHost: "",@@ -672,8 +676,9 @@ export const IdentityKubernetesAuthForm = ({tooltipText="The lifetime for an acccess token in seconds. This value will be referenced at renewal time."isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -687,8 +692,9 @@ export const IdentityKubernetesAuthForm = ({isError={Boolean(error)}errorText={error?.message}tooltipText="The maximum lifetime for an access token in seconds. This value will be referenced at renewal time."+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsxindex eadf123fd9..fbc1c188ed 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faQuestionCircle, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -27,7 +27,8 @@ import {OrgPermissionMachineIdentityAuthTemplateActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";-import { getObjectFromSeconds } from "@app/helpers/datetime";+import { getObjectFromSeconds, SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {MachineIdentityAuthMethod,useAddIdentityLdapAuth,@@ -42,110 +43,107 @@ import { LockoutTab } from "./lockout/LockoutTab";import { superRefineLockout } from "./lockout/super-refine";import { IdentityFormTab } from "./types";-const schema = z- .object({- scope: z.enum(["template", "custom"]),- templateId: z.string().optional(),- url: z.string().optional(),- bindDN: z.string().optional(),- bindPass: z.string().optional(),- searchBase: z.string().optional(),- searchFilter: z.string(), // defaults to (uid={{username}})- ldapCaCertificate: z- .string()- .optional()- .transform((val) => val || undefined),- allowedFields: z- .object({- key: z.string().trim(),- value: z- .string()- .trim()- .transform((val) => val.replace(/\s/g, ""))- })- .array()- .optional(),-- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ scope: z.enum(["template", "custom"]),+ templateId: z.string().optional(),+ url: z.string().optional(),+ bindDN: z.string().optional(),+ bindPass: z.string().optional(),+ searchBase: z.string().optional(),+ searchFilter: z.string(), // defaults to (uid={{username}})+ ldapCaCertificate: z+ .string()+ .optional()+ .transform((val) => val || undefined),+ allowedFields: z+ .object({+ key: z.string().trim(),+ value: z+ .string()+ .trim()+ .transform((val) => val.replace(/\s/g, ""))})- )- .min(1),-- lockoutEnabled: z.boolean().default(true),- lockoutThreshold: z- .string()- .refine(- (value) => Number(value) <= 30 && Number(value) >= 1,- "Lockout threshold must be between 1 and 30"- ),- lockoutDurationValue: z.string(),- lockoutDurationUnit: z.enum(["s", "m", "h", "d"], {- invalid_type_error: "Please select a valid time unit"- }),- lockoutCounterResetValue: z.string(),- lockoutCounterResetUnit: z.enum(["s", "m", "h"], {- invalid_type_error: "Please select a valid time unit"+ .array()+ .optional(),++ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1),++ lockoutEnabled: z.boolean().default(true),+ lockoutThreshold: z+ .string()+ .refine(+ (value) => Number(value) <= 30 && Number(value) >= 1,+ "Lockout threshold must be between 1 and 30"+ ),+ lockoutDurationValue: z.string(),+ lockoutDurationUnit: z.enum(["s", "m", "h", "d"], {+ invalid_type_error: "Please select a valid time unit"+ }),+ lockoutCounterResetValue: z.string(),+ lockoutCounterResetUnit: z.enum(["s", "m", "h"], {+ invalid_type_error: "Please select a valid time unit"+ })})- })- .required()- .superRefine((data, ctx) => {- superRefineLockout(data, ctx);-- // Validation based on scope- if (data.scope === "template") {- if (!data.templateId) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "Template is required when using template scope",- path: ["templateId"]- });+ .required()+ .superRefine((data, ctx) => {+ superRefineLockout(data, ctx);++ // Validation based on scope+ if (data.scope === "template") {+ if (!data.templateId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Template is required when using template scope",+ path: ["templateId"]+ });+ }+ return;}- return;- }- if (data.scope === "custom") {- if (!data.url) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "LDAP URL is required when using custom scope",- path: ["url"]- });- }- if (!data.bindDN) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "Bind DN is required when using custom scope",- path: ["bindDN"]- });- }- if (!data.bindPass) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "Bind Pass is required when using custom scope",- path: ["bindPass"]- });- }- if (!data.searchBase) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: "Search Base is required when using custom scope",- path: ["searchBase"]- });+ if (data.scope === "custom") {+ if (!data.url) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "LDAP URL is required when using custom scope",+ path: ["url"]+ });+ }+ if (!data.bindDN) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Bind DN is required when using custom scope",+ path: ["bindDN"]+ });+ }+ if (!data.bindPass) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Bind Pass is required when using custom scope",+ path: ["bindPass"]+ });+ }+ if (!data.searchBase) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Search Base is required when using custom scope",+ path: ["searchBase"]+ });+ }}- }- });+ });-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -158,13 +156,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityLdapAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -187,6 +187,9 @@ export const IdentityLdapAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,@@ -195,7 +198,7 @@ export const IdentityLdapAuthForm = ({setValue,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {scope: "custom",templateId: "",@@ -743,8 +746,9 @@ export const IdentityLdapAuthForm = ({tooltipText="The lifetime for an acccess token in seconds. This value will be referenced at renewal time."isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -757,8 +761,9 @@ export const IdentityLdapAuthForm = ({isError={Boolean(error)}errorText={error?.message}tooltipText="The maximum lifetime for an access token in seconds. This value will be referenced at renewal time."+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsxindex 804ca8c15f..3294ad428d 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -18,6 +18,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityOciAuth,useGetIdentityOciAuth,@@ -28,40 +30,31 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z- .object({- tenancyOcid: z- .string()- .trim()- .min(1, "Tenancy OCID cannot be empty.")- .refine(- (val) => /^ocid1\.tenancy\.oc1\..+$/.test(val),- "Invalid Tenancy OCID format. Must start with ocid1.tenancy.oc1."- ),- allowedUsernames: z.string().optional(),- accessTokenTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token TTL cannot be greater than 315360000"- ),- accessTokenMaxTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token Max TTL cannot be greater than 315360000"- ),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .object({- ipAddress: z.string().max(50)- })- .array()- .min(1)- })- .required();+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ tenancyOcid: z+ .string()+ .trim()+ .min(1, "Tenancy OCID cannot be empty.")+ .refine(+ (val) => /^ocid1\.tenancy\.oc1\..+$/.test(val),+ "Invalid Tenancy OCID format. Must start with ocid1.tenancy.oc1."+ ),+ allowedUsernames: z.string().optional(),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .object({+ ipAddress: z.string().max(50)+ })+ .array()+ .min(1)+ })+ .required();-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -74,13 +67,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityOciAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -96,13 +91,16 @@ export const IdentityOciAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {tenancyOcid: "",allowedUsernames: "",@@ -240,8 +238,9 @@ export const IdentityOciAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -254,8 +253,9 @@ export const IdentityOciAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsxindex bce3a430f8..8aa3d4525f 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-regular-svg-icons";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";@@ -22,6 +22,8 @@ import {Tooltip} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import { useAddIdentityOidcAuth, useUpdateIdentityOidcAuth } from "@app/hooks/api";import { useGetIdentityOidcAuth } from "@app/hooks/api/identities/queries";import { IdentityTrustedIp } from "@app/hooks/api/identities/types";@@ -29,52 +31,49 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z.object({- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- oidcDiscoveryUrl: z- .string()- .url()- .min(1)- .refine(- (el) => !el.endsWith("/.well-known/openid-configuration"),- "Please remove /.well-known/openid-configuration."- ),- caCert: z.string().trim().default(""),- boundIssuer: z.string().min(1),- boundAudiences: z.string().optional().default(""),- boundClaims: z- .array(- z.object({- key: z.string(),- value: z.string()- })- )- .default([]),- claimMetadataMapping: z- .array(- z.object({- key: z.string(),- value: z.string()- })- )- .default([]),- boundSubject: z.string().optional().default("")-});+const buildSchema = (maxAccessTokenTTL: number) =>+ z.object({+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ oidcDiscoveryUrl: z+ .string()+ .url()+ .min(1)+ .refine(+ (el) => !el.endsWith("/.well-known/openid-configuration"),+ "Please remove /.well-known/openid-configuration."+ ),+ caCert: z.string().trim().default(""),+ boundIssuer: z.string().min(1),+ boundAudiences: z.string().optional().default(""),+ boundClaims: z+ .array(+ z.object({+ key: z.string(),+ value: z.string()+ })+ )+ .default([]),+ claimMetadataMapping: z+ .array(+ z.object({+ key: z.string(),+ value: z.string()+ })+ )+ .default([]),+ boundSubject: z.string().optional().default("")+ });-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -87,13 +86,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityOidcAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -109,13 +110,16 @@ export const IdentityOidcAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {accessTokenTTL: "2592000",accessTokenMaxTTL: "2592000",@@ -437,8 +441,9 @@ export const IdentityOidcAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -451,8 +456,9 @@ export const IdentityOidcAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsxindex 2b1592b3fa..093207073e 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -21,6 +21,8 @@ import {TextArea} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import { useAddIdentitySpiffeAuth, useUpdateIdentitySpiffeAuth } from "@app/hooks/api";import { SpiffeTrustBundleProfile } from "@app/hooks/api/identities/enums";import { useGetIdentitySpiffeAuth } from "@app/hooks/api/identities/queries";@@ -29,26 +31,6 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const commonSchema = z.object({- trustDomain: z.string().trim().min(1, "Trust domain is required"),- allowedSpiffeIds: z.string().trim().min(1, "Allowed SPIFFE IDs are required"),- allowedAudiences: z.string().trim().min(1, "Allowed audiences are required"),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string()-});-const trustBundleDistributionSchema = z.discriminatedUnion("profile", [z.object({profile: z.literal(SpiffeTrustBundleProfile.STATIC),@@ -62,11 +44,26 @@ const trustBundleDistributionSchema = z.discriminatedUnion("profile", [})]);-const schema = commonSchema.extend({- trustBundleDistribution: trustBundleDistributionSchema-});+const buildSchema = (maxAccessTokenTTL: number) => {+ const common = z.object({+ trustDomain: z.string().trim().min(1, "Trust domain is required"),+ allowedSpiffeIds: z.string().trim().min(1, "Allowed SPIFFE IDs are required"),+ allowedAudiences: z.string().trim().min(1, "Allowed audiences are required"),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string()+ });+ return common.extend({ trustBundleDistribution: trustBundleDistributionSchema });+};-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -79,13 +76,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentitySpiffeAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -101,6 +100,9 @@ export const IdentitySpiffeAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {watch,control,@@ -108,7 +110,7 @@ export const IdentitySpiffeAuthForm = ({reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {trustDomain: "",allowedSpiffeIds: "",@@ -411,8 +413,9 @@ export const IdentitySpiffeAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -425,8 +428,9 @@ export const IdentitySpiffeAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsxindex d266075bf7..9e13da360e 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -19,6 +19,8 @@ import {TextArea} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityTlsCertAuth,useGetIdentityTlsCertAuth,@@ -29,26 +31,23 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z.object({- allowedCommonNames: z.string().optional(),- caCertificate: z.string().min(1),- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1)-});+const buildSchema = (maxAccessTokenTTL: number) =>+ z.object({+ allowedCommonNames: z.string().optional(),+ caCertificate: z.string().min(1),+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1)+ });-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -61,13 +60,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityTlsCertAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -83,13 +84,16 @@ export const IdentityTlsCertAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {caCertificate: "",accessTokenTTL: "2592000",@@ -226,8 +230,9 @@ export const IdentityTlsCertAuthForm = ({tooltipText="The lifetime for an access token in seconds. This value will be referenced at renewal time."isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -241,8 +246,9 @@ export const IdentityTlsCertAuthForm = ({isError={Boolean(error)}errorText={error?.message}tooltipText="The maximum lifetime for an access token in seconds. This value will be referenced at renewal time."+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsxindex 2575ed1da2..1acea37923 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -18,6 +18,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";+import { SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityTokenAuth,useGetIdentityTokenAuth,@@ -28,26 +30,23 @@ import { UsePopUpState } from "@app/hooks/usePopUp";import { IdentityFormTab } from "./types";-const schema = z- .object({- accessTokenTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token TTL cannot be greater than 315360000"- }),- accessTokenMaxTTL: z.string().refine((val) => Number(val) <= 315360000, {- message: "Access Token Max TTL cannot be greater than 315360000"- }),- accessTokenNumUsesLimit: z.string(),- accessTokenTrustedIps: z- .array(- z.object({- ipAddress: z.string().max(50)- })- )- .min(1)- })- .required();+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenNumUsesLimit: z.string(),+ accessTokenTrustedIps: z+ .array(+ z.object({+ ipAddress: z.string().max(50)+ })+ )+ .min(1)+ })+ .required();-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -60,13 +59,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityTokenAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { currentOrg } = useOrganization();const orgId = currentOrg?.id || "";@@ -82,13 +83,16 @@ export const IdentityTokenAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,reset,formState: { isSubmitting }} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {accessTokenTTL: "2592000",accessTokenMaxTTL: "2592000",@@ -192,8 +196,9 @@ export const IdentityTokenAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -206,8 +211,9 @@ export const IdentityTokenAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsxindex d5109e5ef2..7c5006da9b 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";@@ -19,7 +19,8 @@ import {Tabs} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";-import { getObjectFromSeconds } from "@app/helpers/datetime";+import { getObjectFromSeconds, SECONDS_PER_DAY } from "@app/helpers/datetime";+import { accessTokenTtlSchema } from "@app/helpers/identityAuthSchemas";import {useAddIdentityUniversalAuth,useGetIdentityUniversalAuth,@@ -32,60 +33,45 @@ import { LockoutTab } from "./lockout/LockoutTab";import { superRefineLockout } from "./lockout/super-refine";import { IdentityFormTab } from "./types";-const schema = z- .object({- accessTokenTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Token TTL cannot be greater than 315360000"- ),- accessTokenMaxTTL: z- .string()- .refine(- (value) => Number(value) <= 315360000,- "Access Max Token TTL cannot be greater than 315360000"- ),- accessTokenPeriod: z- .string()- .optional()- .refine(- (value) => !value || Number(value) <= 315360000,- "Access Token Period cannot be greater than 315360000"- ),- accessTokenNumUsesLimit: z.string(),- clientSecretTrustedIps: z- .object({- ipAddress: z.string().max(50)- })- .array()- .min(1),- accessTokenTrustedIps: z- .object({- ipAddress: z.string().max(50)+const buildSchema = (maxAccessTokenTTL: number) =>+ z+ .object({+ accessTokenTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token TTL"),+ accessTokenMaxTTL: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Max TTL"),+ accessTokenPeriod: accessTokenTtlSchema(maxAccessTokenTTL, "Access Token Period").optional(),+ accessTokenNumUsesLimit: z.string(),+ clientSecretTrustedIps: z+ .object({+ ipAddress: z.string().max(50)+ })+ .array()+ .min(1),+ accessTokenTrustedIps: z+ .object({+ ipAddress: z.string().max(50)+ })+ .array()+ .min(1),+ lockoutEnabled: z.boolean().default(true),+ lockoutThreshold: z+ .string()+ .refine(+ (value) => Number(value) <= 30 && Number(value) >= 1,+ "Lockout threshold must be between 1 and 30"+ ),+ lockoutDurationValue: z.string(),+ lockoutDurationUnit: z.enum(["s", "m", "h", "d"], {+ invalid_type_error: "Please select a valid time unit"+ }),+ lockoutCounterResetValue: z.string(),+ lockoutCounterResetUnit: z.enum(["s", "m", "h"], {+ invalid_type_error: "Please select a valid time unit"})- .array()- .min(1),- lockoutEnabled: z.boolean().default(true),- lockoutThreshold: z- .string()- .refine(- (value) => Number(value) <= 30 && Number(value) >= 1,- "Lockout threshold must be between 1 and 30"- ),- lockoutDurationValue: z.string(),- lockoutDurationUnit: z.enum(["s", "m", "h", "d"], {- invalid_type_error: "Please select a valid time unit"- }),- lockoutCounterResetValue: z.string(),- lockoutCounterResetUnit: z.enum(["s", "m", "h"], {- invalid_type_error: "Please select a valid time unit"})- })- .required()- .superRefine(superRefineLockout);+ .required()+ .superRefine(superRefineLockout);-export type FormData = z.infer<typeof schema>;+export type FormData = z.infer<ReturnType<typeof buildSchema>>;type Props = {handlePopUpOpen: (@@ -98,13 +84,15 @@ type Props = {) => void;identityId?: string;isUpdate?: boolean;+ maxAccessTokenTTL: number;};export const IdentityUniversalAuthForm = ({handlePopUpOpen,handlePopUpToggle,identityId,- isUpdate+ isUpdate,+ maxAccessTokenTTL}: Props) => {const { projectId } = useParams({strict: false@@ -120,6 +108,9 @@ export const IdentityUniversalAuthForm = ({enabled: isUpdate});+ const schema = useMemo(() => buildSchema(maxAccessTokenTTL), [maxAccessTokenTTL]);+ const resolver = useMemo(() => zodResolver(schema), [schema]);+const {control,handleSubmit,@@ -127,7 +118,7 @@ export const IdentityUniversalAuthForm = ({formState: { isSubmitting },watch} = useForm<FormData>({- resolver: zodResolver(schema),+ resolver,defaultValues: {accessTokenTTL: "2592000",accessTokenMaxTTL: "2592000",@@ -325,8 +316,9 @@ export const IdentityUniversalAuthForm = ({label="Access Token TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>@@ -339,8 +331,9 @@ export const IdentityUniversalAuthForm = ({label="Access Token Max TTL (seconds)"isError={Boolean(error)}errorText={error?.message}+ helperText={`Max: ${Math.floor(maxAccessTokenTTL / SECONDS_PER_DAY)} days`}>- <Input {...field} placeholder="2592000" type="number" min="0" step="1" />+ <Input {...field} placeholder="2592000" type="number" min="1" step="1" /></FormControl>)}/>diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityAuth.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityAuth.tsxindex 6d15a83c93..e300c3be31 100644--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityAuth.tsx+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityAuth.tsx@@ -25,6 +25,7 @@ import {ProjectPermissionSub,useOrganization} from "@app/context";+import { MAX_IDENTITY_ACCESS_TOKEN_TTL_FALLBACK } from "@app/helpers/identityAuthSchemas";import { usePopUp } from "@app/hooks";import {IdentityAuthMethod,@@ -41,7 +42,8 @@ import {useDeleteIdentitySpiffeAuth,useDeleteIdentityTlsCertAuth,useDeleteIdentityTokenAuth,- useDeleteIdentityUniversalAuth+ useDeleteIdentityUniversalAuth,+ useFetchServerStatus} from "@app/hooks/api";import { IdentityAliCloudAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm";import { IdentityAwsAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm";@@ -144,6 +146,10 @@ export const Content = ({const { mutateAsync: revokeSpiffeAuth } = useDeleteIdentitySpiffeAuth();const { mutateAsync: revokeLdapAuth } = useDeleteIdentityLdapAuth();+ const { data: serverStatus } = useFetchServerStatus();+ const maxAccessTokenTTL =+ serverStatus?.maxIdentityAccessTokenTTL ?? MAX_IDENTITY_ACCESS_TOKEN_TTL_FALLBACK;+const RemoveAuthMethodMap = {[IdentityAuthMethod.KUBERNETES_AUTH]: revokeKubernetesAuth,[IdentityAuthMethod.GCP_AUTH]: revokeGcpAuth,@@ -297,6 +303,7 @@ export const Content = ({<EditFormidentityId={identityId}isUpdate+ maxAccessTokenTTL={maxAccessTokenTTL}handlePopUpOpen={handlePopUpOpen}handlePopUpToggle={handlePopUpToggle}/>