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
fix: build and address review feedback
Tre Dubravaf2f10f91671f
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex e8793fc2a3..8293d3acdb 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -93,13 +93,13 @@ import { TIdentityAwsAuthServiceFactory } from "@app/services/identity-aws-auth/import { TIdentityAzureAuthServiceFactory } from "@app/services/identity-azure-auth/identity-azure-auth-service";import { TIdentityGcpAuthServiceFactory } from "@app/services/identity-gcp-auth/identity-gcp-auth-service";import { TIdentityJwtAuthServiceFactory } from "@app/services/identity-jwt-auth/identity-jwt-auth-service";-import { TIdentitySpiffeAuthServiceFactory } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-service";import { TIdentityKubernetesAuthServiceFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-service";import { TIdentityLdapAuthServiceFactory } from "@app/services/identity-ldap-auth/identity-ldap-auth-service";import { TAllowedFields } from "@app/services/identity-ldap-auth/identity-ldap-auth-types";import { TIdentityOciAuthServiceFactory } from "@app/services/identity-oci-auth/identity-oci-auth-service";import { TIdentityOidcAuthServiceFactory } from "@app/services/identity-oidc-auth/identity-oidc-auth-service";import { TIdentityProjectServiceFactory } from "@app/services/identity-project/identity-project-service";+import { TIdentitySpiffeAuthServiceFactory } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-service";import { TIdentityTlsCertAuthServiceFactory } from "@app/services/identity-tls-cert-auth/identity-tls-cert-auth-types";import { TIdentityTokenAuthServiceFactory } from "@app/services/identity-token-auth/identity-token-auth-service";import { TIdentityUaServiceFactory } from "@app/services/identity-ua/identity-ua-service";diff --git a/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.ts b/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.tsindex 8029d6c26e..e7bca61e41 100644--- a/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.ts+++ b/backend/src/db/migrations/20260305201413_add-spiffe-machine-auth.ts@@ -15,7 +15,6 @@ export async function up(knex: Knex): Promise<void> {t.string("configurationType").notNullable();t.binary("encryptedCaBundleJwks").nullable();t.string("bundleEndpointUrl").nullable();- t.string("bundleEndpointProfile").nullable();t.binary("encryptedBundleEndpointCaCert").nullable();t.binary("encryptedCachedBundleJwks").nullable();t.datetime("cachedBundleLastRefreshedAt").nullable();diff --git a/backend/src/db/schemas/identity-spiffe-auths.ts b/backend/src/db/schemas/identity-spiffe-auths.tsindex 5073ea7f2e..be63071d72 100644--- a/backend/src/db/schemas/identity-spiffe-auths.ts+++ b/backend/src/db/schemas/identity-spiffe-auths.ts@@ -18,11 +18,10 @@ export const IdentitySpiffeAuthsSchema = z.object({configurationType: z.string(),encryptedCaBundleJwks: zodBuffer.nullable().optional(),bundleEndpointUrl: z.string().nullable().optional(),- bundleEndpointProfile: z.string().nullable().optional(),encryptedBundleEndpointCaCert: zodBuffer.nullable().optional(),encryptedCachedBundleJwks: zodBuffer.nullable().optional(),cachedBundleLastRefreshedAt: z.date().nullable().optional(),- bundleRefreshHintSeconds: z.coerce.number().default(300),+ bundleRefreshHintSeconds: z.number().default(300),accessTokenTTL: z.coerce.number().default(7200),accessTokenMaxTTL: z.coerce.number().default(7200),accessTokenNumUsesLimit: z.coerce.number().default(0),diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex f58a597b39..66b939b36c 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -64,7 +64,6 @@ export * from "./identity-azure-auths";export * from "./identity-gcp-auths";export * from "./identity-group-membership";export * from "./identity-jwt-auths";-export * from "./identity-spiffe-auths";export * from "./identity-kubernetes-auths";export * from "./identity-metadata";export * from "./identity-oci-auths";@@ -73,6 +72,7 @@ export * from "./identity-org-memberships";export * from "./identity-project-additional-privilege";export * from "./identity-project-membership-role";export * from "./identity-project-memberships";+export * from "./identity-spiffe-auths";export * from "./identity-tls-cert-auths";export * from "./identity-token-auths";export * from "./identity-ua-client-secrets";diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex a382e5fa33..43f084e72a 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -758,17 +758,16 @@ export const SPIFFE_AUTH = {allowedSpiffeIds:"Comma-separated list of allowed SPIFFE ID patterns. Supports picomatch glob patterns (e.g. spiffe://prod.example.com/**).",allowedAudiences: "Comma-separated list of allowed audiences for JWT-SVID validation.",- configurationType:- "The configuration type for trust bundle management. Must be one of: 'static' (admin uploads JWKS), 'remote' (auto-refresh from SPIRE bundle endpoint).",- caBundleJwks:- "The JWKS JSON containing public keys for JWT-SVID verification. Required if configurationType is 'static'.",- bundleEndpointUrl:- "The SPIRE bundle endpoint URL for automatic trust bundle retrieval. Required if configurationType is 'remote'.",- bundleEndpointProfile:- "The bundle endpoint authentication profile. Must be one of: 'https_web' (standard HTTPS), 'https_spiffe' (mTLS with SPIFFE auth).",- bundleEndpointCaCert:- "The PEM-encoded CA certificate for verifying the bundle endpoint TLS connection. Required when bundleEndpointProfile is 'https_spiffe'.",- bundleRefreshHintSeconds: "The interval in seconds between bundle refresh attempts. Defaults to 300.",+ trustBundleDistribution: {+ profile:+ "The trust bundle distribution profile. Must be one of: 'static' (admin uploads JWKS), 'https_web_bundle' (auto-refresh from HTTPS endpoint).",+ bundle: "The JWKS JSON containing public keys for JWT-SVID verification. Required when profile is 'static'.",+ endpointUrl:+ "The SPIRE bundle endpoint URL for automatic trust bundle retrieval. Required when profile is 'https_web_bundle'.",+ caCert:+ "Optional PEM-encoded root CA certificate for verifying the bundle endpoint TLS connection. Defaults to system root CAs when not provided.",+ refreshHintSeconds: "The interval in seconds between bundle refresh attempts. Defaults to 3600."+ },accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",accessTokenTTL: "The lifetime for an access token in seconds.",accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",@@ -779,12 +778,13 @@ export const SPIFFE_AUTH = {trustDomain: "The new SPIFFE trust domain.",allowedSpiffeIds: "The new comma-separated list of allowed SPIFFE ID patterns.",allowedAudiences: "The new comma-separated list of allowed audiences.",- configurationType: "The new configuration type for trust bundle management.",- caBundleJwks: "The new JWKS JSON containing public keys.",- bundleEndpointUrl: "The new SPIRE bundle endpoint URL.",- bundleEndpointProfile: "The new bundle endpoint authentication profile.",- bundleEndpointCaCert: "The new PEM-encoded CA certificate for the bundle endpoint.",- bundleRefreshHintSeconds: "The new interval in seconds between bundle refresh attempts.",+ trustBundleDistribution: {+ profile: "The new trust bundle distribution profile.",+ bundle: "The new JWKS JSON containing public keys.",+ endpointUrl: "The new SPIRE bundle endpoint URL.",+ caCert: "The new PEM-encoded CA certificate for the bundle endpoint.",+ refreshHintSeconds: "The new interval in seconds between bundle refresh attempts."+ },accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",accessTokenTTL: "The new lifetime for an access token in seconds.",accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 6906d30c9f..f4e806d2dd 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -285,8 +285,6 @@ import { identityGcpAuthDALFactory } from "@app/services/identity-gcp-auth/identimport { identityGcpAuthServiceFactory } from "@app/services/identity-gcp-auth/identity-gcp-auth-service";import { identityJwtAuthDALFactory } from "@app/services/identity-jwt-auth/identity-jwt-auth-dal";import { identityJwtAuthServiceFactory } from "@app/services/identity-jwt-auth/identity-jwt-auth-service";-import { identitySpiffeAuthDALFactory } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-dal";-import { identitySpiffeAuthServiceFactory } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-service";import { identityKubernetesAuthDALFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-dal";import { identityKubernetesAuthServiceFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-service";import { identityLdapAuthDALFactory } from "@app/services/identity-ldap-auth/identity-ldap-auth-dal";@@ -297,6 +295,8 @@ import { identityOidcAuthDALFactory } from "@app/services/identity-oidc-auth/ideimport { identityOidcAuthServiceFactory } from "@app/services/identity-oidc-auth/identity-oidc-auth-service";import { identityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";import { identityProjectServiceFactory } from "@app/services/identity-project/identity-project-service";+import { identitySpiffeAuthDALFactory } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-dal";+import { identitySpiffeAuthServiceFactory } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-service";import { identityTlsCertAuthDALFactory } from "@app/services/identity-tls-cert-auth/identity-tls-cert-auth-dal";import { identityTlsCertAuthServiceFactory } from "@app/services/identity-tls-cert-auth/identity-tls-cert-auth-service";import { identityTokenAuthDALFactory } from "@app/services/identity-token-auth/identity-token-auth-dal";@@ -1972,7 +1972,6 @@ export const registerRoutes = async (membershipIdentityDAL});-const identityLdapAuthService = identityLdapAuthServiceFactory({identityLdapAuthDAL,orgDAL,diff --git a/backend/src/server/routes/v1/identity-spiffe-auth-router.ts b/backend/src/server/routes/v1/identity-spiffe-auth-router.tsindex be27caaf48..f275197bd9 100644--- a/backend/src/server/routes/v1/identity-spiffe-auth-router.ts+++ b/backend/src/server/routes/v1/identity-spiffe-auth-router.ts@@ -8,10 +8,7 @@ import { slugSchema } from "@app/server/lib/schemas";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { TIdentityTrustedIp } from "@app/services/identity/identity-types";-import {- SpiffeBundleEndpointProfile,- SpiffeConfigurationType-} from "@app/services/identity-spiffe-auth/identity-spiffe-auth-types";+import { SpiffeTrustBundleProfile } from "@app/services/identity-spiffe-auth/identity-spiffe-auth-types";import {validateSpiffeAllowedAudiencesField,validateSpiffeAllowedIdsField,@@ -19,19 +16,71 @@ import {} from "@app/services/identity-spiffe-auth/identity-spiffe-auth-validators";import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";-const IdentitySpiffeAuthResponseSchema = IdentitySpiffeAuthsSchema.omit({- encryptedCaBundleJwks: true,- encryptedBundleEndpointCaCert: true,- encryptedCachedBundleJwks: true+const StaticTrustBundleSchema = z.object({+ profile: z.literal(SpiffeTrustBundleProfile.STATIC).describe(SPIFFE_AUTH.ATTACH.trustBundleDistribution.profile),+ bundle: z.string().min(1).describe(SPIFFE_AUTH.ATTACH.trustBundleDistribution.bundle)+});++const HttpsWebBundleSchema = z.object({+ profile: z+ .literal(SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE)+ .describe(SPIFFE_AUTH.ATTACH.trustBundleDistribution.profile),+ endpointUrl: z+ .string()+ .trim()+ .url()+ .refine((url) => url.startsWith("https://"), "Bundle endpoint URL must use HTTPS")+ .describe(SPIFFE_AUTH.ATTACH.trustBundleDistribution.endpointUrl),+ caCert: z.string().optional().describe(SPIFFE_AUTH.ATTACH.trustBundleDistribution.caCert),+ refreshHintSeconds: z+ .number()+ .int()+ .min(0)+ .default(3600)+ .describe(SPIFFE_AUTH.ATTACH.trustBundleDistribution.refreshHintSeconds)+});++const TrustBundleDistributionSchema = z.discriminatedUnion("profile", [StaticTrustBundleSchema, HttpsWebBundleSchema]);++const StaticTrustBundleResponseSchema = z.object({+ profile: z.literal(SpiffeTrustBundleProfile.STATIC),+ bundle: z.string()+});++const HttpsWebBundleResponseSchema = z.object({+ profile: z.literal(SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE),+ endpointUrl: z.string(),+ caCert: z.string(),+ refreshHintSeconds: z.number(),+ cachedBundleLastRefreshedAt: z.date().nullable().optional()+});++const TrustBundleDistributionResponseSchema = z.discriminatedUnion("profile", [+ StaticTrustBundleResponseSchema,+ HttpsWebBundleResponseSchema+]);++const IdentitySpiffeAuthResponseSchema = IdentitySpiffeAuthsSchema.pick({+ id: true,+ identityId: true,+ trustDomain: true,+ allowedSpiffeIds: true,+ allowedAudiences: true,+ accessTokenTTL: true,+ accessTokenMaxTTL: true,+ accessTokenNumUsesLimit: true,+ accessTokenTrustedIps: true,+ createdAt: true,+ updatedAt: true}).extend({- caBundleJwks: z.string(),- bundleEndpointCaCert: z.string()+ trustBundleDistribution: TrustBundleDistributionResponseSchema});const CommonCreateFields = z.object({trustDomain: validateTrustDomain.describe(SPIFFE_AUTH.ATTACH.trustDomain),allowedSpiffeIds: validateSpiffeAllowedIdsField.describe(SPIFFE_AUTH.ATTACH.allowedSpiffeIds),allowedAudiences: validateSpiffeAllowedAudiencesField.describe(SPIFFE_AUTH.ATTACH.allowedAudiences),+ trustBundleDistribution: TrustBundleDistributionSchema,accessTokenTrustedIps: z.object({ipAddress: z.string().trim()@@ -51,68 +100,7 @@ const CommonCreateFields = z.object({accessTokenNumUsesLimit: z.number().int().min(0).default(0).describe(SPIFFE_AUTH.ATTACH.accessTokenNumUsesLimit)});-const CommonUpdateFields = z- .object({- trustDomain: validateTrustDomain.describe(SPIFFE_AUTH.UPDATE.trustDomain),- allowedSpiffeIds: validateSpiffeAllowedIdsField.describe(SPIFFE_AUTH.UPDATE.allowedSpiffeIds),- allowedAudiences: validateSpiffeAllowedAudiencesField.describe(SPIFFE_AUTH.UPDATE.allowedAudiences),- accessTokenTrustedIps: z- .object({- ipAddress: z.string().trim()- })- .array()- .min(1)- .describe(SPIFFE_AUTH.UPDATE.accessTokenTrustedIps),- accessTokenTTL: z- .number()- .int()- .min(0)- .max(315360000)- .describe(SPIFFE_AUTH.UPDATE.accessTokenTTL),- accessTokenMaxTTL: z- .number()- .int()- .min(0)- .max(315360000)- .describe(SPIFFE_AUTH.UPDATE.accessTokenMaxTTL),- accessTokenNumUsesLimit: z.number().int().min(0).describe(SPIFFE_AUTH.UPDATE.accessTokenNumUsesLimit)- })- .partial();--const StaticConfigurationSchema = z.object({- configurationType: z- .literal(SpiffeConfigurationType.STATIC)- .describe(SPIFFE_AUTH.ATTACH.configurationType),- caBundleJwks: z.string().min(1).describe(SPIFFE_AUTH.ATTACH.caBundleJwks),- bundleEndpointUrl: z.string().optional().default(""),- bundleEndpointProfile: z.nativeEnum(SpiffeBundleEndpointProfile).optional(),- bundleEndpointCaCert: z.string().optional().default(""),- bundleRefreshHintSeconds: z.number().int().min(0).optional().default(3600)-});--const RemoteConfigurationSchema = z.object({- configurationType: z- .literal(SpiffeConfigurationType.REMOTE)- .describe(SPIFFE_AUTH.ATTACH.configurationType),- caBundleJwks: z.string().optional().default(""),- bundleEndpointUrl: z- .string()- .trim()- .url()- .refine((url) => url.startsWith("https://"), "Bundle endpoint URL must use HTTPS")- .describe(SPIFFE_AUTH.ATTACH.bundleEndpointUrl),- bundleEndpointProfile: z- .nativeEnum(SpiffeBundleEndpointProfile)- .default(SpiffeBundleEndpointProfile.HTTPS_WEB)- .describe(SPIFFE_AUTH.ATTACH.bundleEndpointProfile),- bundleEndpointCaCert: z.string().optional().default("").describe(SPIFFE_AUTH.ATTACH.bundleEndpointCaCert),- bundleRefreshHintSeconds: z- .number()- .int()- .min(0)- .default(3600)- .describe(SPIFFE_AUTH.ATTACH.bundleRefreshHintSeconds)-});+const CommonUpdateFields = CommonCreateFields.partial();export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvider) => {server.route({@@ -185,10 +173,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvideparams: z.object({identityId: z.string().trim().describe(SPIFFE_AUTH.ATTACH.identityId)}),- body: z.discriminatedUnion("configurationType", [- StaticConfigurationSchema.merge(CommonCreateFields),- RemoteConfigurationSchema.merge(CommonCreateFields)- ]),+ body: CommonCreateFields,response: {200: z.object({identitySpiffeAuth: IdentitySpiffeAuthResponseSchema@@ -216,7 +201,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvidetrustDomain: identitySpiffeAuth.trustDomain,allowedSpiffeIds: identitySpiffeAuth.allowedSpiffeIds,allowedAudiences: identitySpiffeAuth.allowedAudiences,- configurationType: identitySpiffeAuth.configurationType,+ configurationType: identitySpiffeAuth.trustBundleDistribution.profile,accessTokenTTL: identitySpiffeAuth.accessTokenTTL,accessTokenMaxTTL: identitySpiffeAuth.accessTokenMaxTTL,accessTokenTrustedIps: identitySpiffeAuth.accessTokenTrustedIps as TIdentityTrustedIp[],@@ -251,10 +236,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvideparams: z.object({identityId: z.string().trim().describe(SPIFFE_AUTH.UPDATE.identityId)}),- body: z.discriminatedUnion("configurationType", [- StaticConfigurationSchema.merge(CommonUpdateFields),- RemoteConfigurationSchema.merge(CommonUpdateFields)- ]),+ body: CommonUpdateFields,response: {200: z.object({identitySpiffeAuth: IdentitySpiffeAuthResponseSchema@@ -281,7 +263,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvidetrustDomain: identitySpiffeAuth.trustDomain,allowedSpiffeIds: identitySpiffeAuth.allowedSpiffeIds,allowedAudiences: identitySpiffeAuth.allowedAudiences,- configurationType: identitySpiffeAuth.configurationType,+ configurationType: identitySpiffeAuth.trustBundleDistribution.profile,accessTokenTTL: identitySpiffeAuth.accessTokenTTL,accessTokenMaxTTL: identitySpiffeAuth.accessTokenMaxTTL,accessTokenTrustedIps: identitySpiffeAuth.accessTokenTrustedIps as TIdentityTrustedIp[],@@ -416,10 +398,7 @@ export const registerIdentitySpiffeAuthRouter = async (server: FastifyZodProvide}),response: {200: z.object({- identitySpiffeAuth: IdentitySpiffeAuthResponseSchema.omit({- caBundleJwks: true,- bundleEndpointCaCert: true- })+ identitySpiffeAuth: IdentitySpiffeAuthResponseSchema})}},diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.tsindex f93d8457de..6b69c2c7ea 100644--- a/backend/src/server/routes/v1/index.ts+++ b/backend/src/server/routes/v1/index.ts@@ -38,7 +38,6 @@ import { registerIdentityAwsAuthRouter } from "./identity-aws-iam-auth-router";import { registerIdentityAzureAuthRouter } from "./identity-azure-auth-router";import { registerIdentityGcpAuthRouter } from "./identity-gcp-auth-router";import { registerIdentityJwtAuthRouter } from "./identity-jwt-auth-router";-import { registerIdentitySpiffeAuthRouter } from "./identity-spiffe-auth-router";import { registerIdentityKubernetesRouter } from "./identity-kubernetes-auth-router";import { registerIdentityLdapAuthRouter } from "./identity-ldap-auth-router";import { registerIdentityOciAuthRouter } from "./identity-oci-auth-router";@@ -46,6 +45,7 @@ import { registerIdentityOidcAuthRouter } from "./identity-oidc-auth-router";import { registerIdentityOrgMembershipRouter } from "./identity-org-membership-router";import { registerIdentityProjectMembershipRouter } from "./identity-project-membership-router";import { registerIdentityRouter } from "./identity-router";+import { registerIdentitySpiffeAuthRouter } from "./identity-spiffe-auth-router";import { registerIdentityTlsCertAuthRouter } from "./identity-tls-cert-auth-router";import { registerIdentityTokenAuthRouter } from "./identity-token-auth-router";import { registerIdentityUaRouter } from "./identity-universal-auth-router";diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.tsindex 3b507f394a..cb0a41b628 100644--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-fns.ts@@ -1,15 +1,17 @@import https from "https";-import picomatch from "picomatch";+import RE2 from "re2";++import { request } from "@app/lib/config/request";-const SPIFFE_ID_REGEX = /^spiffe:\/\/([^/]+)(\/.*)?$/;+const SPIFFE_ID_REGEX = new RE2("^spiffe:\\/\\/([^/]+)(\\/.*)?");export const isValidSpiffeId = (value: string): boolean => {return SPIFFE_ID_REGEX.test(value);};export const extractTrustDomainFromSpiffeId = (spiffeId: string): string => {- const match = spiffeId.match(SPIFFE_ID_REGEX);+ const match = SPIFFE_ID_REGEX.exec(spiffeId);if (!match) {throw new Error(`Invalid SPIFFE ID: ${spiffeId}`);}@@ -25,70 +27,17 @@ export const doesSpiffeIdMatchPattern = (spiffeId: string, patterns: string): boreturn patternList.some((pattern) => picomatch.isMatch(spiffeId, pattern));};-export const findSigningKeyInJwks = (jwksJson: string, kid: string) => {- const jwks = JSON.parse(jwksJson) as { keys: Array<{ kid?: string; use?: string; kty: string; [key: string]: unknown }> };-- if (!jwks.keys || !Array.isArray(jwks.keys)) {- throw new Error("Invalid JWKS: missing keys array");- }-- const matchingKey = jwks.keys.find((key) => key.kid === kid);-- if (!matchingKey) {- throw new Error(`No key found in JWKS matching kid: ${kid}`);- }-- return matchingKey;-};-const BUNDLE_FETCH_TIMEOUT_MS = 10_000;const MAX_BUNDLE_SIZE_BYTES = 1_048_576; // 1 MB-export const fetchRemoteBundleJwks = (url: string, caCert?: string): Promise<string> => {- const parsedUrl = new URL(url);-- return new Promise<string>((resolve, reject) => {- let totalBytes = 0;- const chunks: Buffer[] = [];-- const req = https.request(- {- hostname: parsedUrl.hostname,- port: parsedUrl.port || 443,- path: parsedUrl.pathname + parsedUrl.search,- method: "GET",- agent: caCert ? new https.Agent({ ca: caCert, rejectUnauthorized: true }) : undefined,- timeout: BUNDLE_FETCH_TIMEOUT_MS- },- (res) => {- if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {- req.destroy(new Error(`Failed to fetch SPIFFE trust bundle: HTTP ${res.statusCode}`));- return;- }-- const contentLengthHeader = res.headers["content-length"];- if (contentLengthHeader && parseInt(contentLengthHeader, 10) > MAX_BUNDLE_SIZE_BYTES) {- req.destroy(new Error("SPIFFE trust bundle response exceeds maximum allowed size"));- return;- }-- res.on("data", (chunk: Buffer) => {- totalBytes += chunk.length;- if (totalBytes > MAX_BUNDLE_SIZE_BYTES) {- req.destroy(new Error("SPIFFE trust bundle response exceeds maximum allowed size"));- return;- }- chunks.push(chunk);- });-- res.on("end", () => {- resolve(Buffer.concat(chunks).toString());- });- }- );-- req.on("timeout", () => req.destroy(new Error("SPIFFE trust bundle fetch timed out")));- req.on("error", reject);- req.end();+export const fetchRemoteBundleJwks = async (url: string, caCert?: string): Promise<string> => {+ const response = await request.get<string>(url, {+ responseType: "text",+ timeout: BUNDLE_FETCH_TIMEOUT_MS,+ maxContentLength: MAX_BUNDLE_SIZE_BYTES,+ maxBodyLength: MAX_BUNDLE_SIZE_BYTES,+ httpsAgent: caCert ? new https.Agent({ ca: caCert, rejectUnauthorized: true }) : undefined});++ return response.data;};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 af964ef532..372f07e22f 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@@ -1,12 +1,13 @@import { ForbiddenError, subject } from "@casl/ability";import { requestContext } from "@fastify/request-context";-import { decodeProtectedHeader, errors as joseErrors, importJWK, jwtVerify } from "jose";+import { createLocalJWKSet, errors as joseErrors, JSONWebKeySet, jwtVerify } from "jose";import {AccessScope,ActionProjectType,IdentityAuthMethod,OrganizationActionScope,+ TIdentitySpiffeAuths,TIdentitySpiffeAuthsUpdate} from "@app/db/schemas";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";@@ -28,8 +29,8 @@ import {} from "@app/lib/errors";import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";import { logger } from "@app/lib/logger";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";import { ActorType, AuthTokenType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";@@ -45,15 +46,17 @@ import {doesSpiffeIdMatchPattern,extractTrustDomainFromSpiffeId,fetchRemoteBundleJwks,- findSigningKeyInJwks,isValidSpiffeId} from "./identity-spiffe-auth-fns";import {- SpiffeConfigurationType,+ FIPS_APPROVED_JWT_ALGORITHMS,+ SpiffeTrustBundleProfile,TAttachSpiffeAuthDTO,TGetSpiffeAuthDTO,TLoginSpiffeAuthDTO,TRevokeSpiffeAuthDTO,+ TSpiffeTrustBundleDistribution,+ TSpiffeTrustBundleDistributionResponse,TUpdateSpiffeAuthDTO} from "./identity-spiffe-auth-types";@@ -70,23 +73,15 @@ type TIdentitySpiffeAuthServiceFactoryDep = {export type TIdentitySpiffeAuthServiceFactory = ReturnType<typeof identitySpiffeAuthServiceFactory>;-const verifyJwtSvid = async (jwtValue: string, jwksJson: string) => {- const header = decodeProtectedHeader(jwtValue);- if (!header.kid) {- throw new UnauthorizedError({ message: "JWT missing kid header" });- }-- let jwk;- try {- jwk = findSigningKeyInJwks(jwksJson, header.kid);- } catch {- throw new UnauthorizedError({ message: `No key found in JWKS matching kid: ${header.kid}` });- }- const key = await importJWK(jwk, header.alg);+const verifyJwtSvid = async (jwtValue: string, jwksJson: string, allowedAudiences: string[]) => {+ const jwks = createLocalJWKSet(JSON.parse(jwksJson) as JSONWebKeySet);try {- const { payload } = await jwtVerify(jwtValue, key);- return { tokenData: payload as Record<string, unknown>, kid: header.kid };+ const { payload } = await jwtVerify(jwtValue, jwks, {+ audience: allowedAudiences,+ algorithms: FIPS_APPROVED_JWT_ALGORITHMS+ });+ return payload as Record<string, unknown>;} catch (error) {if (error instanceof joseErrors.JWTExpired) {throw new UnauthorizedError({ message: "JWT-SVID has expired" });@@ -94,31 +89,30 @@ const verifyJwtSvid = async (jwtValue: string, jwksJson: string) => {if (error instanceof joseErrors.JWSSignatureVerificationFailed) {throw new UnauthorizedError({ message: "JWT-SVID signature verification failed" });}+ if (error instanceof joseErrors.JWTClaimValidationFailed) {+ throw new UnauthorizedError({ message: "JWT-SVID audience validation failed" });+ }throw new UnauthorizedError({ message: "JWT-SVID verification failed" });}};const validateSpiffeClaims = (tokenData: Record<string, unknown>,- config: { allowedAudiences: string; trustDomain: string; allowedSpiffeIds: string }+ config: { trustDomain: string; allowedSpiffeIds: string }): boolean => {- if (!tokenData.aud) return false;-- const tokenAudiences: string[] = Array.isArray(tokenData.aud) ? tokenData.aud : [tokenData.aud as string];- const allowedAudiences = config.allowedAudiences- .split(", ")- .map((a) => a.trim())- .filter(Boolean);-- if (!tokenAudiences.some((aud) => allowedAudiences.includes(aud))) return false;-const tokenSub = tokenData.sub as string;- if (!tokenSub || !isValidSpiffeId(tokenSub)) return false;+ if (!tokenSub || !isValidSpiffeId(tokenSub)) {+ return false;+ }const tokenTrustDomain = extractTrustDomainFromSpiffeId(tokenSub);- if (tokenTrustDomain !== config.trustDomain) return false;+ if (tokenTrustDomain !== config.trustDomain) {+ return false;+ }- if (!doesSpiffeIdMatchPattern(tokenSub, config.allowedSpiffeIds)) return false;+ if (!doesSpiffeIdMatchPattern(tokenSub, config.allowedSpiffeIds)) {+ return false;+ }return true;};@@ -133,22 +127,91 @@ export const identitySpiffeAuthServiceFactory = ({kmsService,orgDAL}: TIdentitySpiffeAuthServiceFactoryDep) => {- const resolveJwks = async ({+ type TFlattenedTrustBundle = {+ configurationType: string;+ caBundleJwks: string | null;+ bundleEndpointUrl: string | null;+ bundleEndpointCaCert: string | null;+ bundleRefreshHintSeconds: number | undefined;+ };++ const $flattenTrustBundleDistribution = (dist: TSpiffeTrustBundleDistribution): TFlattenedTrustBundle => {+ if (dist.profile === SpiffeTrustBundleProfile.STATIC) {+ return {+ configurationType: dist.profile,+ caBundleJwks: dist.bundle,+ bundleEndpointUrl: null,+ bundleEndpointCaCert: null,+ bundleRefreshHintSeconds: undefined+ };+ }+ return {+ configurationType: dist.profile,+ caBundleJwks: null,+ bundleEndpointUrl: dist.endpointUrl,+ bundleEndpointCaCert: dist.caCert || null,+ bundleRefreshHintSeconds: dist.refreshHintSeconds+ };+ };++ const $buildTrustBundleDistributionResponse = (+ dbRow: Pick<+ TIdentitySpiffeAuths,+ "configurationType" | "bundleEndpointUrl" | "cachedBundleLastRefreshedAt" | "bundleRefreshHintSeconds"+ >,+ decryptedJwks: string,+ decryptedCaCert: string+ ): TSpiffeTrustBundleDistributionResponse => {+ if (dbRow.configurationType === SpiffeTrustBundleProfile.STATIC) {+ return { profile: SpiffeTrustBundleProfile.STATIC, bundle: decryptedJwks };+ }+ return {+ profile: SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE,+ endpointUrl: dbRow.bundleEndpointUrl || "",+ caCert: decryptedCaCert,+ refreshHintSeconds: dbRow.bundleRefreshHintSeconds,+ cachedBundleLastRefreshedAt: dbRow.cachedBundleLastRefreshedAt+ };+ };++ const $validateSpiffeConfig = async (dist: TSpiffeTrustBundleDistribution) => {+ if (dist.profile === SpiffeTrustBundleProfile.STATIC) {+ try {+ createLocalJWKSet(JSON.parse(dist.bundle) as JSONWebKeySet);+ } catch {+ throw new BadRequestError({ message: "The provided CA Bundle JWKS is not valid JWKS" });+ }+ return;+ }++ try {+ const bundleJwks = await fetchRemoteBundleJwks(dist.endpointUrl, dist.caCert);+ createLocalJWKSet(JSON.parse(bundleJwks) as JSONWebKeySet);+ } catch (error) {+ if (error instanceof BadRequestError) throw error;+ throw new BadRequestError({+ message:+ "Failed to fetch or validate the remote SPIFFE trust bundle. Verify the bundle endpoint URL and CA certificate are correct."+ });+ }+ };++ const $resolveJwks = async ({config,orgId,forceRefresh}: {- config: {- id: string;- configurationType: string;- encryptedCaBundleJwks: Buffer | null;- encryptedCachedBundleJwks: Buffer | null;- bundleEndpointUrl: string | null;- bundleEndpointProfile: string | null;- encryptedBundleEndpointCaCert: Buffer | null;- bundleRefreshHintSeconds: number | null;- cachedBundleLastRefreshedAt: Date | string | null;- };+ config: Pick<+ TIdentitySpiffeAuths,+ | "id"+ | "configurationType"+ | "encryptedCaBundleJwks"+ | "encryptedCachedBundleJwks"+ | "bundleEndpointUrl"+ | "encryptedBundleEndpointCaCert"+ | "bundleRefreshHintSeconds"+ | "cachedBundleLastRefreshedAt"+ >;orgId: string;forceRefresh?: boolean;}): Promise<{ jwksJson: string; fromCache: boolean }> => {@@ -158,11 +221,11 @@ export const identitySpiffeAuthServiceFactory = ({orgId});- if (config.configurationType === SpiffeConfigurationType.STATIC) {+ if (config.configurationType === SpiffeTrustBundleProfile.STATIC) {if (!config.encryptedCaBundleJwks) {throw new BadRequestError({ message: "Static SPIFFE auth has no CA bundle JWKS configured" });}-+return {jwksJson: orgDataKeyDecryptor({ cipherTextBlob: config.encryptedCaBundleJwks }).toString(),fromCache: false@@ -192,7 +255,7 @@ export const identitySpiffeAuthServiceFactory = ({await blockLocalAndPrivateIpAddresses(config.bundleEndpointUrl);let caCert: string | undefined;- if (config.bundleEndpointProfile === "https_spiffe" && config.encryptedBundleEndpointCaCert) {+ if (config.encryptedBundleEndpointCaCert) {caCert = orgDataKeyDecryptor({ cipherTextBlob: config.encryptedBundleEndpointCaCert }).toString();}@@ -236,20 +299,25 @@ export const identitySpiffeAuthServiceFactory = ({try {// Resolve JWKS (lazy fetch for remote, decrypt for static)- let { jwksJson, fromCache } = await resolveJwks({ config: identitySpiffeAuth, orgId: identity.orgId });+ let { jwksJson, fromCache } = await $resolveJwks({ config: identitySpiffeAuth, orgId: identity.orgId });++ const allowedAudiences = identitySpiffeAuth.allowedAudiences+ .split(",")+ .map((a) => a.trim())+ .filter(Boolean);let tokenData: Record<string, unknown>;try {- ({ tokenData } = await verifyJwtSvid(jwtValue, jwksJson));+ tokenData = await verifyJwtSvid(jwtValue, jwksJson, allowedAudiences);} catch (verifyError) {// Kid-miss retry: if we used a cached JWKS and the kid wasn't found, force-refresh onceif (fromCache && verifyError instanceof Error && verifyError.message.includes("No key found in JWKS")) {- ({ jwksJson, fromCache } = await resolveJwks({+ ({ jwksJson, fromCache } = await $resolveJwks({config: identitySpiffeAuth,orgId: identity.orgId,forceRefresh: true}));- ({ tokenData } = await verifyJwtSvid(jwtValue, jwksJson));+ tokenData = await verifyJwtSvid(jwtValue, jwksJson, allowedAudiences);} else {throw verifyError;}@@ -320,7 +388,7 @@ export const identitySpiffeAuthServiceFactory = ({return newToken;});- let expireyOptions: { expiresIn: number } | undefined = undefined;+ let expireyOptions: { expiresIn: number } | undefined;const accessTokenTTL = Number(identityAccessToken.accessTokenTTL);if (accessTokenTTL > 0) {expireyOptions = { expiresIn: accessTokenTTL };@@ -372,12 +440,7 @@ export const identitySpiffeAuthServiceFactory = ({trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds,+ trustBundleDistribution,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,@@ -459,21 +522,25 @@ export const identitySpiffeAuthServiceFactory = ({return extractIPDetails(accessTokenTrustedIp.ipAddress);});- if (bundleEndpointUrl) {- await blockLocalAndPrivateIpAddresses(bundleEndpointUrl);+ const flatBundle = $flattenTrustBundleDistribution(trustBundleDistribution);++ if (flatBundle.bundleEndpointUrl) {+ await blockLocalAndPrivateIpAddresses(flatBundle.bundleEndpointUrl);}+ await $validateSpiffeConfig(trustBundleDistribution);+const { encryptor: orgDataKeyEncryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,orgId: actorOrgId});- const encryptedCaBundleJwks = caBundleJwks- ? orgDataKeyEncryptor({ plainText: Buffer.from(caBundleJwks) }).cipherTextBlob+ const encryptedCaBundleJwks = flatBundle.caBundleJwks+ ? orgDataKeyEncryptor({ plainText: Buffer.from(flatBundle.caBundleJwks) }).cipherTextBlob: null;- const encryptedBundleEndpointCaCert = bundleEndpointCaCert- ? orgDataKeyEncryptor({ plainText: Buffer.from(bundleEndpointCaCert) }).cipherTextBlob+ const encryptedBundleEndpointCaCert = flatBundle.bundleEndpointCaCert+ ? orgDataKeyEncryptor({ plainText: Buffer.from(flatBundle.bundleEndpointCaCert) }).cipherTextBlob: null;const identitySpiffeAuth = await identitySpiffeAuthDAL.transaction(async (tx) => {@@ -483,12 +550,11 @@ export const identitySpiffeAuthServiceFactory = ({trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,+ configurationType: flatBundle.configurationType,encryptedCaBundleJwks,- bundleEndpointUrl: bundleEndpointUrl || null,- bundleEndpointProfile: bundleEndpointProfile || null,+ bundleEndpointUrl: flatBundle.bundleEndpointUrl || null,encryptedBundleEndpointCaCert,- bundleRefreshHintSeconds: bundleRefreshHintSeconds || 300,+ bundleRefreshHintSeconds: flatBundle.bundleRefreshHintSeconds || 300,accessTokenMaxTTL,accessTokenTTL,accessTokenNumUsesLimit,@@ -503,8 +569,11 @@ export const identitySpiffeAuthServiceFactory = ({return {...identitySpiffeAuth,orgId: identityMembershipOrg.scopeOrgId,- caBundleJwks: caBundleJwks || "",- bundleEndpointCaCert: bundleEndpointCaCert || ""+ trustBundleDistribution: $buildTrustBundleDistributionResponse(+ identitySpiffeAuth,+ flatBundle.caBundleJwks || "",+ flatBundle.bundleEndpointCaCert || ""+ )};};@@ -513,12 +582,7 @@ export const identitySpiffeAuthServiceFactory = ({trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds,+ trustBundleDistribution,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,@@ -599,18 +663,10 @@ export const identitySpiffeAuthServiceFactory = ({return extractIPDetails(accessTokenTrustedIp.ipAddress);});- if (bundleEndpointUrl) {- await blockLocalAndPrivateIpAddresses(bundleEndpointUrl);- }-const updateQuery: TIdentitySpiffeAuthsUpdate = {trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- bundleEndpointUrl,- bundleEndpointProfile,- bundleRefreshHintSeconds,accessTokenMaxTTL,accessTokenTTL,accessTokenNumUsesLimit,@@ -625,15 +681,23 @@ export const identitySpiffeAuthServiceFactory = ({orgId: actorOrgId});- if (caBundleJwks !== undefined) {- updateQuery.encryptedCaBundleJwks = caBundleJwks- ? orgDataKeyEncryptor({ plainText: Buffer.from(caBundleJwks) }).cipherTextBlob- : null;- }+ if (trustBundleDistribution) {+ const flatBundle = $flattenTrustBundleDistribution(trustBundleDistribution);++ if (flatBundle.bundleEndpointUrl) {+ await blockLocalAndPrivateIpAddresses(flatBundle.bundleEndpointUrl);+ }++ await $validateSpiffeConfig(trustBundleDistribution);- if (bundleEndpointCaCert !== undefined) {- updateQuery.encryptedBundleEndpointCaCert = bundleEndpointCaCert- ? orgDataKeyEncryptor({ plainText: Buffer.from(bundleEndpointCaCert) }).cipherTextBlob+ updateQuery.configurationType = flatBundle.configurationType;+ updateQuery.bundleEndpointUrl = flatBundle.bundleEndpointUrl;+ updateQuery.bundleRefreshHintSeconds = flatBundle.bundleRefreshHintSeconds;+ updateQuery.encryptedCaBundleJwks = flatBundle.caBundleJwks+ ? orgDataKeyEncryptor({ plainText: Buffer.from(flatBundle.caBundleJwks) }).cipherTextBlob+ : null;+ updateQuery.encryptedBundleEndpointCaCert = flatBundle.bundleEndpointCaCert+ ? orgDataKeyEncryptor({ plainText: Buffer.from(flatBundle.bundleEndpointCaCert) }).cipherTextBlob: null;}@@ -649,8 +713,11 @@ export const identitySpiffeAuthServiceFactory = ({return {...updatedSpiffeAuth,orgId: identityMembershipOrg.scopeOrgId,- caBundleJwks: decryptedCaBundleJwks,- bundleEndpointCaCert: decryptedBundleEndpointCaCert+ trustBundleDistribution: $buildTrustBundleDistributionResponse(+ updatedSpiffeAuth,+ decryptedCaBundleJwks,+ decryptedBundleEndpointCaCert+ )};};@@ -715,8 +782,11 @@ export const identitySpiffeAuthServiceFactory = ({return {...identitySpiffeAuth,orgId: identityMembershipOrg.scopeOrgId,- caBundleJwks: decryptedCaBundleJwks,- bundleEndpointCaCert: decryptedBundleEndpointCaCert+ trustBundleDistribution: $buildTrustBundleDistributionResponse(+ identitySpiffeAuth,+ decryptedCaBundleJwks,+ decryptedBundleEndpointCaCert+ )};};@@ -804,13 +874,39 @@ export const identitySpiffeAuthServiceFactory = ({const deletedSpiffeAuth = await identitySpiffeAuthDAL.delete({ identityId }, tx);await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.SPIFFE_AUTH }, tx);- return { ...deletedSpiffeAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };+ return deletedSpiffeAuth?.[0];+ });++ const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: identityMembershipOrg.scopeOrgId});- return revokedIdentitySpiffeAuth;+ const decryptedCaBundleJwks = revokedIdentitySpiffeAuth.encryptedCaBundleJwks+ ? orgDataKeyDecryptor({ cipherTextBlob: revokedIdentitySpiffeAuth.encryptedCaBundleJwks }).toString()+ : "";+ const decryptedBundleEndpointCaCert = revokedIdentitySpiffeAuth.encryptedBundleEndpointCaCert+ ? orgDataKeyDecryptor({ cipherTextBlob: revokedIdentitySpiffeAuth.encryptedBundleEndpointCaCert }).toString()+ : "";++ return {+ ...revokedIdentitySpiffeAuth,+ orgId: identityMembershipOrg.scopeOrgId,+ trustBundleDistribution: $buildTrustBundleDistributionResponse(+ revokedIdentitySpiffeAuth,+ decryptedCaBundleJwks,+ decryptedBundleEndpointCaCert+ )+ };};- const refreshSpiffeBundle = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetSpiffeAuthDTO) => {+ const refreshSpiffeBundle = async ({+ identityId,+ actorId,+ actor,+ actorAuthMethod,+ actorOrgId+ }: TGetSpiffeAuthDTO) => {const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({scopeData: {scope: AccessScope.Organization,@@ -856,33 +952,41 @@ export const identitySpiffeAuthServiceFactory = ({const identitySpiffeAuth = await identitySpiffeAuthDAL.findOne({ identityId });- if (identitySpiffeAuth.configurationType !== SpiffeConfigurationType.REMOTE) {+ if (identitySpiffeAuth.configurationType === SpiffeTrustBundleProfile.STATIC) {throw new BadRequestError({message: "Bundle refresh is only applicable to identities with remote SPIFFE Auth configuration"});}- await resolveJwks({ config: identitySpiffeAuth, orgId: identityMembershipOrg.scopeOrgId, forceRefresh: true });-- const refreshed = await identitySpiffeAuthDAL.findOne({ identityId });+ const { jwksJson } = await $resolveJwks({+ config: identitySpiffeAuth,+ orgId: identityMembershipOrg.scopeOrgId,+ forceRefresh: true+ });const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,orgId: actorOrgId});- const decryptedCaBundleJwks = refreshed.encryptedCaBundleJwks- ? orgDataKeyDecryptor({ cipherTextBlob: refreshed.encryptedCaBundleJwks }).toString()- : "";- const decryptedBundleEndpointCaCert = refreshed.encryptedBundleEndpointCaCert- ? orgDataKeyDecryptor({ cipherTextBlob: refreshed.encryptedBundleEndpointCaCert }).toString()+ const decryptedBundleEndpointCaCert = identitySpiffeAuth.encryptedBundleEndpointCaCert+ ? orgDataKeyDecryptor({ cipherTextBlob: identitySpiffeAuth.encryptedBundleEndpointCaCert }).toString(): "";+ // Use the existing row with the refresh timestamp set to now, avoiding a redundant DB read.+ const refreshedRow = {+ ...identitySpiffeAuth,+ cachedBundleLastRefreshedAt: new Date()+ };+return {- ...refreshed,+ ...refreshedRow,orgId: identityMembershipOrg.scopeOrgId,- caBundleJwks: decryptedCaBundleJwks,- bundleEndpointCaCert: decryptedBundleEndpointCaCert+ trustBundleDistribution: $buildTrustBundleDistributionResponse(+ refreshedRow,+ jwksJson,+ decryptedBundleEndpointCaCert+ )};};diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-types.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-types.tsindex e75c5f7fae..bb582db74f 100644--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-types.ts+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-types.ts@@ -1,14 +1,49 @@import { TProjectPermission } from "@app/lib/types";-export enum SpiffeConfigurationType {+export enum SpiffeTrustBundleProfile {STATIC = "static",- REMOTE = "remote"+ HTTPS_WEB_BUNDLE = "https_web_bundle"}-export enum SpiffeBundleEndpointProfile {- HTTPS_WEB = "https_web",- HTTPS_SPIFFE = "https_spiffe"-}+// FIPS 140-2 approved JWT signing algorithms only.+// EdDSA (Ed25519) and other non-NIST algorithms are excluded to avoid+// opaque internal errors when running in FIPS-compliant environments.+export const FIPS_APPROVED_JWT_ALGORITHMS = [+ "RS256",+ "RS384",+ "RS512",+ "PS256",+ "PS384",+ "PS512",+ "ES256",+ "ES384",+ "ES512"+];++export type TSpiffeTrustBundleDistribution =+ | {+ profile: SpiffeTrustBundleProfile.STATIC;+ bundle: string;+ }+ | {+ profile: SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE;+ endpointUrl: string;+ caCert?: string;+ refreshHintSeconds?: number;+ };++export type TSpiffeTrustBundleDistributionResponse =+ | {+ profile: SpiffeTrustBundleProfile.STATIC;+ bundle: string;+ }+ | {+ profile: SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE;+ endpointUrl: string;+ caCert: string;+ refreshHintSeconds: number;+ cachedBundleLastRefreshedAt: Date | null | undefined;+ };export type TLoginSpiffeAuthDTO = {identityId: string;@@ -21,12 +56,7 @@ export type TAttachSpiffeAuthDTO = {trustDomain: string;allowedSpiffeIds: string;allowedAudiences: string;- configurationType: SpiffeConfigurationType;- caBundleJwks?: string;- bundleEndpointUrl?: string;- bundleEndpointProfile?: SpiffeBundleEndpointProfile;- bundleEndpointCaCert?: string;- bundleRefreshHintSeconds?: number;+ trustBundleDistribution: TSpiffeTrustBundleDistribution;accessTokenTTL: number;accessTokenMaxTTL: number;accessTokenNumUsesLimit: number;@@ -39,12 +69,7 @@ export type TUpdateSpiffeAuthDTO = {trustDomain?: string;allowedSpiffeIds?: string;allowedAudiences?: string;- configurationType?: SpiffeConfigurationType;- caBundleJwks?: string;- bundleEndpointUrl?: string;- bundleEndpointProfile?: SpiffeBundleEndpointProfile;- bundleEndpointCaCert?: string;- bundleRefreshHintSeconds?: number;+ trustBundleDistribution?: TSpiffeTrustBundleDistribution;accessTokenTTL?: number;accessTokenMaxTTL?: number;accessTokenNumUsesLimit?: number;diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-validators.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-validators.tsindex c635997f4c..cffcc6c8a7 100644--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-validators.ts+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-validators.ts@@ -1,3 +1,4 @@+import RE2 from "re2";import { z } from "zod";export const validateSpiffeAllowedAudiencesField = z@@ -24,8 +25,10 @@ export const validateSpiffeAllowedIdsField = z.join(", ");});+const TRUST_DOMAIN_REGEX = new RE2("^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$");+export const validateTrustDomain = z.string().trim().min(1, "Trust domain is required")- .regex(/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/, "Invalid trust domain format");+ .refine((val) => TRUST_DOMAIN_REGEX.test(val), "Invalid trust domain format");diff --git a/backend/src/services/identity/identity-org-dal.ts b/backend/src/services/identity/identity-org-dal.tsindex 62569f6219..893fcaa69a 100644--- a/backend/src/services/identity/identity-org-dal.ts+++ b/backend/src/services/identity/identity-org-dal.ts@@ -12,6 +12,7 @@ import {TIdentityKubernetesAuths,TIdentityOciAuths,TIdentityOidcAuths,+ TIdentitySpiffeAuths,TIdentityTlsCertAuths,TIdentityTokenAuths,TIdentityUniversalAuths,@@ -257,7 +258,7 @@ export const identityOrgDALFactory = (db: TDbClient) => {"paginatedIdentity.actorIdentityId",`${TableName.IdentityTlsCertAuth}.identityId`)- .leftJoin(+ .leftJoin<TIdentitySpiffeAuths>(TableName.IdentitySpiffeAuth,"paginatedIdentity.actorIdentityId",`${TableName.IdentitySpiffeAuth}.identityId`diff --git a/docs/documentation/platform/identities/spiffe-auth.mdx b/docs/documentation/platform/identities/spiffe-auth.mdxindex 602ba1566f..06282c8a73 100644--- a/docs/documentation/platform/identities/spiffe-auth.mdx+++ b/docs/documentation/platform/identities/spiffe-auth.mdx@@ -36,18 +36,22 @@ sequenceDiagramAt a high level, Infisical authenticates a workload by verifying its JWT-SVID and checking that it meets specific requirements (e.g. its SPIFFE ID matches an allowed pattern, it belongs to the expected trust domain) at the `/api/v1/auth/spiffe-auth/login` endpoint. If successful, Infisical returns a short-lived access token that can be used to make authenticated requests to the Infisical API.+<Note>+ SPIFFE Auth currently supports JWT-SVID verification only. X.509-SVID (certificate-based) authentication is not supported at this time. If you require X.509-SVID support, please open a feature request.+</Note>+To be more specific:1. The workload requests a JWT-SVID from its local SPIRE Agent (via the SPIFFE Workload API).2. The JWT-SVID is sent to Infisical at the `/api/v1/auth/spiffe-auth/login` endpoint.3. Infisical verifies the JWT-SVID signature using either:- - Pre-configured JWKS (Static configuration)- - JWKS fetched from a SPIRE bundle endpoint (Remote configuration)+ - Pre-configured JWKS (Static trust bundle profile)+ - JWKS fetched from a SPIRE bundle endpoint (HTTPS Web Bundle profile)4. Infisical validates that the token's trust domain matches the configured trust domain, the SPIFFE ID (`sub` claim) matches at least one of the allowed SPIFFE ID patterns, and the audience (`aud` claim) is in the allowed audiences list.5. If all checks pass, Infisical returns a short-lived access token that the workload can use to make authenticated requests to the Infisical API.<Note>- For Remote configuration, Infisical needs network-level access to the configured SPIRE bundle endpoint. The trust bundle is fetched on-demand at login time and cached. If the cache is older than the configured refresh interval (default: 1 hour), Infisical fetches a fresh bundle before verifying the JWT-SVID. You can also force an immediate refresh via the API without waiting for the cache to expire.+ For the HTTPS Web Bundle profile, Infisical needs network-level access to the configured SPIRE bundle endpoint. The trust bundle is fetched on-demand at login time and cached. If the cache is older than the configured refresh interval (default: 1 hour), Infisical fetches a fresh bundle before verifying the JWT-SVID. You can also force an immediate refresh via the API without waiting for the cache to expire.</Note>## Guide@@ -85,20 +89,22 @@ In the following steps, we explore how to create and use identities to access thHere's some information about each field:- **Configuration Type:**- - **Static:** You provide the SPIRE JWKS JSON directly. Best for environments where the trust bundle is managed externally or does not change frequently.- - **Remote:** Infisical automatically fetches and caches the trust bundle from a SPIRE bundle endpoint. Best for dynamic environments where keys rotate regularly.+ **Trust Bundle Profile:**++ <Tabs>+ <Tab title="Static">+ Best for air-gapped environments or environments where the trust bundle does not change frequently. You provide the SPIRE JWKS JSON directly.- **Static configuration fields:**- - **CA Bundle JWKS (required):** The JWKS JSON containing the public keys used to verify JWT-SVID signatures. You can obtain this from your SPIRE server's bundle endpoint or via `spire-server bundle show -format jwks`.+ - **CA Bundle JWKS (required):** The JWKS JSON containing the public keys used to verify JWT-SVID signatures. You can obtain this from your SPIRE server's bundle endpoint or via `spire-server bundle show -format jwks`.+ </Tab>+ <Tab title="HTTPS Web Bundle">+ Best for dynamic environments where keys rotate regularly. Infisical automatically fetches and caches the trust bundle from a SPIRE bundle endpoint.- **Remote configuration fields:**- - **Bundle Endpoint URL (required):** The URL of the SPIRE bundle endpoint (e.g. `https://spire-server:8443`). Must use HTTPS. Infisical fetches the trust bundle on-demand at login time and caches it for the configured refresh interval.- - **Bundle Endpoint Profile:** The authentication profile for the bundle endpoint.- - `HTTPS Web` — Standard HTTPS with publicly trusted certificates.- - `HTTPS SPIFFE` — HTTPS with a custom CA certificate for mTLS-secured endpoints.- - **Bundle Endpoint CA Certificate:** The PEM-encoded CA certificate for verifying the bundle endpoint TLS connection. Required when using the `HTTPS SPIFFE` profile.- - **Bundle Refresh Hint (seconds):** How long the cached trust bundle is considered fresh before Infisical re-fetches it on the next login. Defaults to `3600` (1 hour). You can force an immediate refresh at any time using the [refresh bundle API endpoint](/api-reference/endpoints/machine-identities/spiffe-auth/refresh-bundle).+ - **Bundle Endpoint URL (required):** The URL of the SPIRE bundle endpoint (e.g. `https://spire-server:8443`). Must use HTTPS. Infisical fetches the trust bundle on-demand at login time and caches it for the configured refresh interval.+ - **Root CA Certificate (optional):** A PEM-encoded root CA certificate for verifying the bundle endpoint's TLS connection. When not provided, the system's default root CAs are used.+ - **Bundle Refresh Hint (seconds):** How long the cached trust bundle is considered fresh before Infisical re-fetches it on the next login. Defaults to `3600` (1 hour). You can force an immediate refresh at any time using the [refresh bundle API endpoint](/api-reference/endpoints/machine-identities/spiffe-auth/refresh-bundle).+ </Tab>+ </Tabs>**Common fields for both configurations:**- **Trust Domain (required):** The SPIFFE trust domain that authenticating workloads must belong to (e.g. `example.org` or `prod.example.com`).@@ -125,7 +131,7 @@ In the following steps, we explore how to create and use identities to access thTo access the Infisical API as the identity, you need to obtain a JWT-SVID from your SPIRE Agent that meets the validation requirements configured in the previous step.The JWT-SVID must:- - Be signed by a key present in the configured JWKS (static or remote).+ - Be signed by a key present in the configured JWKS (static or fetched via HTTPS web bundle).- Have a `sub` claim containing a valid SPIFFE ID that matches one of the allowed SPIFFE ID patterns.- Have an `aud` claim containing at least one of the allowed audiences.- Belong to the configured trust domain.diff --git a/frontend/src/hooks/api/identities/enums.tsx b/frontend/src/hooks/api/identities/enums.tsxindex 22c9ca1dc9..5f1738b758 100644--- a/frontend/src/hooks/api/identities/enums.tsx+++ b/frontend/src/hooks/api/identities/enums.tsx@@ -19,12 +19,7 @@ export enum IdentityJwtConfigurationType {STATIC = "static"}-export enum IdentitySpiffeConfigurationType {+export enum SpiffeTrustBundleProfile {STATIC = "static",- REMOTE = "remote"-}--export enum SpiffeBundleEndpointProfile {- HTTPS_WEB = "https_web",- HTTPS_SPIFFE = "https_spiffe"+ HTTPS_WEB_BUNDLE = "https_web_bundle"}diff --git a/frontend/src/hooks/api/identities/mutations.tsx b/frontend/src/hooks/api/identities/mutations.tsxindex 289d75151b..8a39b2fb06 100644--- a/frontend/src/hooks/api/identities/mutations.tsx+++ b/frontend/src/hooks/api/identities/mutations.tsx@@ -12,10 +12,10 @@ import {AddIdentityGcpAuthDTO,AddIdentityJwtAuthDTO,AddIdentityKubernetesAuthDTO,- AddIdentitySpiffeAuthDTO,AddIdentityLdapAuthDTO,AddIdentityOciAuthDTO,AddIdentityOidcAuthDTO,+ AddIdentitySpiffeAuthDTO,AddIdentityTlsCertAuthDTO,AddIdentityTokenAuthDTO,AddIdentityUniversalAuthDTO,@@ -32,10 +32,10 @@ import {DeleteIdentityGcpAuthDTO,DeleteIdentityJwtAuthDTO,DeleteIdentityKubernetesAuthDTO,- DeleteIdentitySpiffeAuthDTO,DeleteIdentityLdapAuthDTO,DeleteIdentityOciAuthDTO,DeleteIdentityOidcAuthDTO,+ DeleteIdentitySpiffeAuthDTO,DeleteIdentityTlsCertAuthDTO,DeleteIdentityTokenAuthDTO,DeleteIdentityUniversalAuthClientSecretDTO,@@ -47,10 +47,10 @@ import {IdentityGcpAuth,IdentityJwtAuth,IdentityKubernetesAuth,- IdentitySpiffeAuth,IdentityLdapAuth,IdentityOciAuth,IdentityOidcAuth,+ IdentitySpiffeAuth,IdentityTlsCertAuth,IdentityTokenAuth,IdentityUniversalAuth,@@ -62,10 +62,10 @@ import {UpdateIdentityGcpAuthDTO,UpdateIdentityJwtAuthDTO,UpdateIdentityKubernetesAuthDTO,- UpdateIdentitySpiffeAuthDTO,UpdateIdentityLdapAuthDTO,UpdateIdentityOciAuthDTO,UpdateIdentityOidcAuthDTO,+ UpdateIdentitySpiffeAuthDTO,UpdateIdentityTlsCertAuthDTO,UpdateIdentityTokenAuthDTO,UpdateIdentityUniversalAuthDTO,@@ -1221,12 +1221,7 @@ export const useAddIdentitySpiffeAuth = () => {trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds,+ trustBundleDistribution,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,@@ -1240,12 +1235,7 @@ export const useAddIdentitySpiffeAuth = () => {trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds,+ trustBundleDistribution,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,@@ -1283,12 +1273,7 @@ export const useUpdateIdentitySpiffeAuth = () => {trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds,+ trustBundleDistribution,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,@@ -1302,12 +1287,7 @@ export const useUpdateIdentitySpiffeAuth = () => {trustDomain,allowedSpiffeIds,allowedAudiences,- configurationType,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds,+ trustBundleDistribution,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,diff --git a/frontend/src/hooks/api/identities/queries.tsx b/frontend/src/hooks/api/identities/queries.tsxindex 68d75787fe..5614802ceb 100644--- a/frontend/src/hooks/api/identities/queries.tsx+++ b/frontend/src/hooks/api/identities/queries.tsx@@ -12,12 +12,12 @@ import {IdentityGcpAuth,IdentityJwtAuth,IdentityKubernetesAuth,- IdentitySpiffeAuth,IdentityLdapAuth,IdentityMembershipOrg,IdentityOciAuth,IdentityOidcAuth,IdentityProjectMembershipV1,+ IdentitySpiffeAuth,IdentityTlsCertAuth,IdentityTokenAuth,IdentityUniversalAuth,diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.tsindex 66b6e03200..38d8f9b8ec 100644--- a/frontend/src/hooks/api/identities/types.ts+++ b/frontend/src/hooks/api/identities/types.ts@@ -833,18 +833,37 @@ export type DeleteIdentityJwtAuthDTO = {identityId: string;} & ({ organizationId: string } | { projectId: string });+export type SpiffeTrustBundleDistributionInput =+ | {+ profile: "static";+ bundle: string;+ }+ | {+ profile: "https_web_bundle";+ endpointUrl: string;+ caCert?: string;+ refreshHintSeconds?: number;+ };++export type SpiffeTrustBundleDistribution =+ | {+ profile: "static";+ bundle: string;+ }+ | {+ profile: "https_web_bundle";+ endpointUrl: string;+ caCert: string;+ refreshHintSeconds: number;+ cachedBundleLastRefreshedAt: string | null;+ };+export type IdentitySpiffeAuth = {identityId: string;trustDomain: string;allowedSpiffeIds: string;allowedAudiences: string;- configurationType: string;- caBundleJwks: string;- bundleEndpointUrl: string | null;- bundleEndpointProfile: string | null;- bundleEndpointCaCert: string;- cachedBundleLastRefreshedAt: string | null;- bundleRefreshHintSeconds: number;+ trustBundleDistribution: SpiffeTrustBundleDistribution;accessTokenTTL: number;accessTokenMaxTTL: number;accessTokenNumUsesLimit: number;@@ -858,12 +877,7 @@ export type AddIdentitySpiffeAuthDTO = {trustDomain: string;allowedSpiffeIds: string;allowedAudiences: string;- configurationType: string;- caBundleJwks?: string;- bundleEndpointUrl?: string;- bundleEndpointProfile?: string;- bundleEndpointCaCert?: string;- bundleRefreshHintSeconds?: number;+ trustBundleDistribution: SpiffeTrustBundleDistributionInput;accessTokenTTL: number;accessTokenMaxTTL: number;accessTokenNumUsesLimit: number;@@ -879,12 +893,7 @@ export type UpdateIdentitySpiffeAuthDTO = {trustDomain?: string;allowedSpiffeIds?: string;allowedAudiences?: string;- configurationType?: string;- caBundleJwks?: string;- bundleEndpointUrl?: string;- bundleEndpointProfile?: string;- bundleEndpointCaCert?: string;- bundleRefreshHintSeconds?: number;+ trustBundleDistribution?: SpiffeTrustBundleDistributionInput;accessTokenTTL?: number;accessTokenMaxTTL?: number;accessTokenNumUsesLimit?: number;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 a7b5a08073..ab667c7582 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@@ -14,11 +14,11 @@ import { IdentityAwsAuthForm } from "./IdentityAwsAuthForm";import { IdentityAzureAuthForm } from "./IdentityAzureAuthForm";import { IdentityGcpAuthForm } from "./IdentityGcpAuthForm";import { IdentityJwtAuthForm } from "./IdentityJwtAuthForm";-import { IdentitySpiffeAuthForm } from "./IdentitySpiffeAuthForm";import { IdentityKubernetesAuthForm } from "./IdentityKubernetesAuthForm";import { IdentityLdapAuthForm } from "./IdentityLdapAuthForm";import { IdentityOciAuthForm } from "./IdentityOciAuthForm";import { IdentityOidcAuthForm } from "./IdentityOidcAuthForm";+import { IdentitySpiffeAuthForm } from "./IdentitySpiffeAuthForm";import { IdentityTlsCertAuthForm } from "./IdentityTlsCertAuthForm";import { IdentityTokenAuthForm } from "./IdentityTokenAuthForm";import { IdentityUniversalAuthForm } from "./IdentityUniversalAuthForm";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 f289c6e287..8e661e1fea 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@@ -22,10 +22,7 @@ import {} from "@app/components/v2";import { useOrganization, useSubscription } from "@app/context";import { useAddIdentitySpiffeAuth, useUpdateIdentitySpiffeAuth } from "@app/hooks/api";-import {- IdentitySpiffeConfigurationType,- SpiffeBundleEndpointProfile-} from "@app/hooks/api/identities/enums";+import { SpiffeTrustBundleProfile } from "@app/hooks/api/identities/enums";import { useGetIdentitySpiffeAuth } from "@app/hooks/api/identities/queries";import { IdentityTrustedIp } from "@app/hooks/api/identities/types";import { UsePopUpState } from "@app/hooks/usePopUp";@@ -52,34 +49,23 @@ const commonSchema = z.object({accessTokenNumUsesLimit: z.string()});-const schema = z.discriminatedUnion("configurationType", [- z- .object({- configurationType: z.literal(IdentitySpiffeConfigurationType.STATIC),- caBundleJwks: z.string().trim().min(1, "CA Bundle JWKS is required for static configuration"),- bundleEndpointUrl: z.string().trim().optional().default(""),- bundleEndpointProfile: z- .nativeEnum(SpiffeBundleEndpointProfile)- .optional()- .default(SpiffeBundleEndpointProfile.HTTPS_WEB),- bundleEndpointCaCert: z.string().trim().optional().default(""),- bundleRefreshHintSeconds: z.string().optional().default("300")- })- .merge(commonSchema),- z- .object({- configurationType: z.literal(IdentitySpiffeConfigurationType.REMOTE),- caBundleJwks: z.string().trim().optional().default(""),- bundleEndpointUrl: z.string().trim().url("Must be a valid URL"),- bundleEndpointProfile: z- .nativeEnum(SpiffeBundleEndpointProfile)- .default(SpiffeBundleEndpointProfile.HTTPS_WEB),- bundleEndpointCaCert: z.string().trim().optional().default(""),- bundleRefreshHintSeconds: z.string().default("300")- })- .merge(commonSchema)+const trustBundleDistributionSchema = z.discriminatedUnion("profile", [+ z.object({+ profile: z.literal(SpiffeTrustBundleProfile.STATIC),+ bundle: z.string().trim().min(1, "CA Bundle JWKS is required for static configuration")+ }),+ z.object({+ profile: z.literal(SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE),+ endpointUrl: z.string().trim().url("Must be a valid URL"),+ caCert: z.string().trim().optional().default(""),+ refreshHintSeconds: z.string().default("3600")+ })]);+const schema = commonSchema.extend({+ trustBundleDistribution: trustBundleDistributionSchema+});+export type FormData = z.infer<typeof schema>;type Props = {@@ -124,15 +110,13 @@ export const IdentitySpiffeAuthForm = ({} = useForm<FormData>({resolver: zodResolver(schema),defaultValues: {- configurationType: IdentitySpiffeConfigurationType.STATIC,trustDomain: "",allowedSpiffeIds: "",allowedAudiences: "",- caBundleJwks: "",- bundleEndpointUrl: "",- bundleEndpointProfile: SpiffeBundleEndpointProfile.HTTPS_WEB,- bundleEndpointCaCert: "",- bundleRefreshHintSeconds: "300",+ trustBundleDistribution: {+ profile: SpiffeTrustBundleProfile.STATIC,+ bundle: ""+ },accessTokenTTL: "2592000",accessTokenMaxTTL: "2592000",accessTokenNumUsesLimit: "0",@@ -140,8 +124,7 @@ export const IdentitySpiffeAuthForm = ({}});- const selectedConfigurationType = watch("configurationType") as IdentitySpiffeConfigurationType;- const selectedBundleEndpointProfile = watch("bundleEndpointProfile");+ const selectedProfile = watch("trustBundleDistribution.profile");const {fields: accessTokenTrustedIpsFields,@@ -151,20 +134,36 @@ export const IdentitySpiffeAuthForm = ({useEffect(() => {if (data) {+ const dist = data.trustBundleDistribution;+ let trustBundleDistribution: FormData["trustBundleDistribution"];++ switch (dist.profile) {+ case SpiffeTrustBundleProfile.STATIC:+ trustBundleDistribution = {+ profile: SpiffeTrustBundleProfile.STATIC,+ bundle: dist.bundle || ""+ };+ break;+ case SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE:+ trustBundleDistribution = {+ profile: SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE,+ endpointUrl: dist.endpointUrl || "",+ caCert: dist.caCert || "",+ refreshHintSeconds: String(dist.refreshHintSeconds ?? 3600)+ };+ break;+ default:+ trustBundleDistribution = {+ profile: SpiffeTrustBundleProfile.STATIC,+ bundle: ""+ };+ }+reset({- configurationType:- (data.configurationType as IdentitySpiffeConfigurationType) ||- IdentitySpiffeConfigurationType.STATIC,trustDomain: data.trustDomain,allowedSpiffeIds: data.allowedSpiffeIds,allowedAudiences: data.allowedAudiences,- caBundleJwks: data.caBundleJwks || "",- bundleEndpointUrl: data.bundleEndpointUrl || "",- bundleEndpointProfile:- (data.bundleEndpointProfile as SpiffeBundleEndpointProfile) ||- SpiffeBundleEndpointProfile.HTTPS_WEB,- bundleEndpointCaCert: data.bundleEndpointCaCert || "",- bundleRefreshHintSeconds: String(data.bundleRefreshHintSeconds ?? 300),+ trustBundleDistribution,accessTokenTTL: String(data.accessTokenTTL),accessTokenMaxTTL: String(data.accessTokenMaxTTL),accessTokenNumUsesLimit: String(data.accessTokenNumUsesLimit),@@ -184,33 +183,43 @@ export const IdentitySpiffeAuthForm = ({accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,- configurationType,trustDomain,allowedSpiffeIds,allowedAudiences,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds+ trustBundleDistribution}: FormData) => {if (!identityId) {return;}+ // Build the trust bundle distribution with correct number types+ const buildDistribution = () => {+ switch (trustBundleDistribution.profile) {+ case SpiffeTrustBundleProfile.STATIC:+ return {+ profile: trustBundleDistribution.profile,+ bundle: trustBundleDistribution.bundle+ };+ case SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE:+ return {+ profile: trustBundleDistribution.profile,+ endpointUrl: trustBundleDistribution.endpointUrl,+ caCert: trustBundleDistribution.caCert,+ refreshHintSeconds: Number(trustBundleDistribution.refreshHintSeconds)+ };+ default:+ return { profile: SpiffeTrustBundleProfile.STATIC as const, bundle: "" };+ }+ };+if (data) {await updateMutateAsync({identityId,...(projectId ? { projectId } : { organizationId: orgId }),- configurationType,trustDomain,allowedSpiffeIds,allowedAudiences,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds: Number(bundleRefreshHintSeconds),+ trustBundleDistribution: buildDistribution(),accessTokenTTL: Number(accessTokenTTL),accessTokenMaxTTL: Number(accessTokenMaxTTL),accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),@@ -219,16 +228,11 @@ export const IdentitySpiffeAuthForm = ({} else {await addMutateAsync({identityId,- configurationType,+ ...(projectId ? { projectId } : { organizationId: orgId }),trustDomain,allowedSpiffeIds,allowedAudiences,- caBundleJwks,- bundleEndpointUrl,- bundleEndpointProfile,- bundleEndpointCaCert,- bundleRefreshHintSeconds: Number(bundleRefreshHintSeconds),- ...(projectId ? { projectId } : { organizationId: orgId }),+ trustBundleDistribution: buildDistribution(),accessTokenTTL: Number(accessTokenTTL),accessTokenMaxTTL: Number(accessTokenMaxTTL),accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),@@ -263,10 +267,10 @@ export const IdentitySpiffeAuthForm = ({<TabPanel value={IdentityFormTab.Configuration}><Controllercontrol={control}- name="configurationType"+ name="trustBundleDistribution.profile"render={({ field: { onChange, ...field }, fieldState: { error } }) => (<FormControl- label="Configuration Type"+ label="Trust Bundle Profile"isError={Boolean(error)}errorText={error?.message}>@@ -278,11 +282,14 @@ export const IdentitySpiffeAuthForm = ({}}className="w-full">- <SelectItem value={IdentitySpiffeConfigurationType.STATIC} key="static">+ <SelectItem value={SpiffeTrustBundleProfile.STATIC} key="static">Static</SelectItem>- <SelectItem value={IdentitySpiffeConfigurationType.REMOTE} key="remote">- Remote+ <SelectItem+ value={SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE}+ key="https_web_bundle"+ >+ HTTPS Web Bundle</SelectItem></Select></FormControl>@@ -333,10 +340,10 @@ export const IdentitySpiffeAuthForm = ({</FormControl>)}/>- {selectedConfigurationType === IdentitySpiffeConfigurationType.STATIC && (+ {selectedProfile === SpiffeTrustBundleProfile.STATIC && (<Controllercontrol={control}- name="caBundleJwks"+ name="trustBundleDistribution.bundle"render={({ field, fieldState: { error } }) => (<FormControlisRequired@@ -349,11 +356,11 @@ export const IdentitySpiffeAuthForm = ({)}/>)}- {selectedConfigurationType === IdentitySpiffeConfigurationType.REMOTE && (+ {selectedProfile === SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE && (<><Controllercontrol={control}- name="bundleEndpointUrl"+ name="trustBundleDistribution.endpointUrl"render={({ field, fieldState: { error } }) => (<FormControlisRequired@@ -361,72 +368,33 @@ export const IdentitySpiffeAuthForm = ({isError={Boolean(error)}errorText={error?.message}>- <Input- {...field}- type="text"- placeholder="https://spire-server:8443"- />+ <Input {...field} type="text" placeholder="https://spire-server:8443" /></FormControl>)}/><Controllercontrol={control}- name="bundleEndpointProfile"- render={({ field: { onChange, ...field }, fieldState: { error } }) => (+ name="trustBundleDistribution.caCert"+ render={({ field, fieldState: { error } }) => (<FormControl- label="Bundle Endpoint Profile"+ label="Root CA Certificate (optional)"isError={Boolean(error)}errorText={error?.message}>- <Select- defaultValue={field.value}- {...field}- onValueChange={(e) => {- onChange(e);- }}- className="w-full"- >- <SelectItem- value={SpiffeBundleEndpointProfile.HTTPS_WEB}- key="https_web"- >- HTTPS Web- </SelectItem>- <SelectItem- value={SpiffeBundleEndpointProfile.HTTPS_SPIFFE}- key="https_spiffe"- >- HTTPS SPIFFE- </SelectItem>- </Select>+ <TextArea {...field} placeholder="-----BEGIN CERTIFICATE----- ..." /></FormControl>)}/>- {selectedBundleEndpointProfile === SpiffeBundleEndpointProfile.HTTPS_SPIFFE && (- <Controller- control={control}- name="bundleEndpointCaCert"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Bundle Endpoint CA Certificate"- isError={Boolean(error)}- errorText={error?.message}- >- <TextArea {...field} placeholder="-----BEGIN CERTIFICATE----- ..." />- </FormControl>- )}- />- )}<Controllercontrol={control}- name="bundleRefreshHintSeconds"+ name="trustBundleDistribution.refreshHintSeconds"render={({ field, fieldState: { error } }) => (<FormControllabel="Bundle Refresh Hint (seconds)"isError={Boolean(error)}errorText={error?.message}>- <Input {...field} placeholder="300" type="number" min="0" step="1" />+ <Input {...field} placeholder="3600" type="number" min="0" 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 8085484c45..8b4a8cb82a 100644--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityAuth.tsx+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityAuth.tsx@@ -35,10 +35,10 @@ import {useDeleteIdentityGcpAuth,useDeleteIdentityJwtAuth,useDeleteIdentityKubernetesAuth,- useDeleteIdentitySpiffeAuth,useDeleteIdentityLdapAuth,useDeleteIdentityOciAuth,useDeleteIdentityOidcAuth,+ useDeleteIdentitySpiffeAuth,useDeleteIdentityTlsCertAuth,useDeleteIdentityTokenAuth,useDeleteIdentityUniversalAuth@@ -49,10 +49,10 @@ import { IdentityAzureAuthForm } from "@app/pages/organization/AccessManagementPimport { IdentityGcpAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm";import { IdentityJwtAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm";import { IdentityKubernetesAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm";-import { IdentitySpiffeAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm";import { IdentityLdapAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm";import { IdentityOciAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm";import { IdentityOidcAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm";+import { IdentitySpiffeAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySpiffeAuthForm";import { IdentityTlsCertAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm";import { IdentityTokenAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm";import { IdentityUniversalAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm";@@ -63,10 +63,10 @@ import { ViewIdentityAzureAuthContent } from "./ViewIdentityAzureAuthContent";import { ViewIdentityGcpAuthContent } from "./ViewIdentityGcpAuthContent";import { ViewIdentityJwtAuthContent } from "./ViewIdentityJwtAuthContent";import { ViewIdentityKubernetesAuthContent } from "./ViewIdentityKubernetesAuthContent";-import { ViewIdentitySpiffeAuthContent } from "./ViewIdentitySpiffeAuthContent";import { ViewIdentityLdapAuthContent } from "./ViewIdentityLdapAuthContent";import { ViewIdentityOciAuthContent } from "./ViewIdentityOciAuthContent";import { ViewIdentityOidcAuthContent } from "./ViewIdentityOidcAuthContent";+import { ViewIdentitySpiffeAuthContent } from "./ViewIdentitySpiffeAuthContent";import { ViewIdentityTlsCertAuthContent } from "./ViewIdentityTlsCertAuthContent";import { ViewIdentityTokenAuthContent } from "./ViewIdentityTokenAuthContent";import { ViewIdentityUniversalAuthContent } from "./ViewIdentityUniversalAuthContent";diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentitySpiffeAuthContent.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentitySpiffeAuthContent.tsxindex 65c59b28f0..ccf35b3ae1 100644--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentitySpiffeAuthContent.tsx+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentitySpiffeAuthContent.tsx@@ -4,12 +4,17 @@ import { EyeIcon } from "lucide-react";import { EmptyState, Spinner, Tooltip } from "@app/components/v2";import { Badge } from "@app/components/v3";import { useGetIdentitySpiffeAuth } from "@app/hooks/api";-import { IdentitySpiffeConfigurationType } from "@app/hooks/api/identities/enums";+import { SpiffeTrustBundleProfile } from "@app/hooks/api/identities/enums";import { ViewIdentityContentWrapper } from "@app/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuth/ViewIdentityContentWrapper";import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";import { ViewAuthMethodProps } from "./types";+const PROFILE_DISPLAY_MAP: Record<string, string> = {+ [SpiffeTrustBundleProfile.STATIC]: "Static",+ [SpiffeTrustBundleProfile.HTTPS_WEB_BUNDLE]: "HTTPS Web Bundle"+};+export const ViewIdentitySpiffeAuthContent = ({identityId,onEdit,@@ -27,14 +32,11 @@ export const ViewIdentitySpiffeAuthContent = ({if (!data) {return (- <EmptyState- icon={faBan}- title="Could not find SPIFFE Auth associated with this Identity."- />+ <EmptyState icon={faBan} title="Could not find SPIFFE Auth associated with this Identity." />);}- const isRemote = data.configurationType === IdentitySpiffeConfigurationType.REMOTE;+ const { trustBundleDistribution: dist } = data;return (<ViewIdentityContentWrapper onEdit={onEdit} onDelete={onDelete} identityId={identityId}>@@ -53,26 +55,40 @@ export const ViewIdentitySpiffeAuthContent = ({.map((aud) => aud.trim()).join(", ")}</IdentityAuthFieldDisplay>- <IdentityAuthFieldDisplay label="Configuration Type">- {isRemote ? "Remote" : "Static"}+ <IdentityAuthFieldDisplay label="Trust Bundle Profile">+ {PROFILE_DISPLAY_MAP[dist.profile] || dist.profile}</IdentityAuthFieldDisplay>- {isRemote ? (+ {dist.profile === SpiffeTrustBundleProfile.STATIC ? (+ <IdentityAuthFieldDisplay className="col-span-2" label="CA Bundle JWKS">+ {dist.bundle && (+ <Tooltip+ side="right"+ className="max-w-xl p-2"+ content={+ <pre className="rounded-sm bg-mineshaft-600 p-2 break-words whitespace-pre-wrap">+ {dist.bundle}+ </pre>+ }+ >+ <Badge variant="neutral">+ <EyeIcon />+ Reveal+ </Badge>+ </Tooltip>+ )}+ </IdentityAuthFieldDisplay>+ ) : (<><IdentityAuthFieldDisplay className="col-span-2" label="Bundle Endpoint URL">- {data.bundleEndpointUrl}+ {dist.endpointUrl}</IdentityAuthFieldDisplay>- <IdentityAuthFieldDisplay label="Bundle Endpoint Profile">- {data.bundleEndpointProfile}- </IdentityAuthFieldDisplay>- <IdentityAuthFieldDisplay className="col-span-2" label="Bundle Endpoint CA Certificate">- {data.bundleEndpointCaCert && (+ <IdentityAuthFieldDisplay className="col-span-2" label="Root CA Certificate">+ {dist.caCert && (<Tooltipside="right"className="max-w-xl p-2"content={- <p className="rounded-sm bg-mineshaft-600 p-2 break-words">- {data.bundleEndpointCaCert}- </p>+ <p className="rounded-sm bg-mineshaft-600 p-2 break-words">{dist.caCert}</p>}><Badge variant="neutral">@@ -83,33 +99,14 @@ export const ViewIdentitySpiffeAuthContent = ({)}</IdentityAuthFieldDisplay><IdentityAuthFieldDisplay label="Last Refreshed">- {data.cachedBundleLastRefreshedAt- ? new Date(data.cachedBundleLastRefreshedAt).toLocaleString()+ {dist.cachedBundleLastRefreshedAt+ ? new Date(dist.cachedBundleLastRefreshedAt).toLocaleString(): null}</IdentityAuthFieldDisplay><IdentityAuthFieldDisplay label="Bundle Refresh Hint (seconds)">- {data.bundleRefreshHintSeconds}+ {dist.refreshHintSeconds}</IdentityAuthFieldDisplay></>- ) : (- <IdentityAuthFieldDisplay className="col-span-2" label="CA Bundle JWKS">- {data.caBundleJwks && (- <Tooltip- side="right"- className="max-w-xl p-2"- content={- <pre className="rounded-sm bg-mineshaft-600 p-2 whitespace-pre-wrap break-words">- {data.caBundleJwks}- </pre>- }- >- <Badge variant="neutral">- <EyeIcon />- Reveal- </Badge>- </Tooltip>- )}- </IdentityAuthFieldDisplay>)}<IdentityAuthFieldDisplay label="Access Token TTL (seconds)">{data.accessTokenTTL}