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
feat: add oidc auth template support for MIs
Scott Wilsonca60221f452c
diff --git a/backend/src/db/migrations/20260831000000_identity-oidc-auth-template.ts b/backend/src/db/migrations/20260831000000_identity-oidc-auth-template.tsnew file mode 100644index 0000000000..8095953b72--- /dev/null+++ b/backend/src/db/migrations/20260831000000_identity-oidc-auth-template.ts@@ -0,0 +1,22 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.IdentityOidcAuth, "templateId"))) {+ await knex.schema.alterTable(TableName.IdentityOidcAuth, (t) => {+ t.uuid("templateId").nullable();+ t.foreign("templateId").references("id").inTable(TableName.IdentityAuthTemplate).onDelete("SET NULL");+ t.index("templateId");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.IdentityOidcAuth, "templateId")) {+ await knex.schema.alterTable(TableName.IdentityOidcAuth, (t) => {+ t.dropForeign(["templateId"]);+ t.dropColumn("templateId");+ });+ }+}diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 97473497ce..edb002b8f4 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -407,6 +407,7 @@ tables:- updatedAt- claimMetadataMapping- accessTokenPeriod+ - templateId- name: identity_tls_cert_authssource: public.identity_tls_cert_authsdiff --git a/backend/src/db/schemas/identity-oidc-auths.ts b/backend/src/db/schemas/identity-oidc-auths.tsindex 5c652b0f81..6492896b0f 100644--- a/backend/src/db/schemas/identity-oidc-auths.ts+++ b/backend/src/db/schemas/identity-oidc-auths.ts@@ -28,7 +28,8 @@ export const IdentityOidcAuthsSchema = z.object({updatedAt: z.date(),encryptedCaCertificate: zodBuffer.nullable().optional(),claimMetadataMapping: z.unknown().nullable().optional(),- accessTokenPeriod: z.coerce.number().default(0)+ accessTokenPeriod: z.coerce.number().default(0),+ templateId: z.string().uuid().nullable().optional()});export type TIdentityOidcAuths = z.infer<typeof IdentityOidcAuthsSchema>;diff --git a/backend/src/ee/routes/v1/identity-template-router.ts b/backend/src/ee/routes/v1/identity-template-router.tsindex e3e719addb..a1454bd2db 100644--- a/backend/src/ee/routes/v1/identity-template-router.ts+++ b/backend/src/ee/routes/v1/identity-template-router.ts@@ -12,7 +12,9 @@ import {kubernetesTemplateFieldsCreateSchema,kubernetesTemplateFieldsResponseSchema,ldapTemplateFieldsResponseSchema,- ldapTemplateFieldsSchema+ ldapTemplateFieldsSchema,+ oidcTemplateFieldsResponseSchema,+ oidcTemplateFieldsSchema} from "@app/ee/services/identity-auth-template/identity-auth-template-schemas";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";@@ -44,6 +46,10 @@ const sanitizedTemplateSchema = z.discriminatedUnion("authMethod", [templateRowSchema.extend({authMethod: z.literal(IdentityAuthTemplateMethod.KUBERNETES),templateFields: kubernetesTemplateFieldsResponseSchema+ }),+ templateRowSchema.extend({+ authMethod: z.literal(IdentityAuthTemplateMethod.OIDC),+ templateFields: oidcTemplateFieldsResponseSchema})]);@@ -73,6 +79,11 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)name: templateNameSchema,authMethod: z.literal(IdentityAuthTemplateMethod.KUBERNETES),templateFields: kubernetesTemplateFieldsCreateSchema+ }),+ z.object({+ name: templateNameSchema,+ authMethod: z.literal(IdentityAuthTemplateMethod.OIDC),+ templateFields: oidcTemplateFieldsSchema})]),response: {@@ -129,7 +140,11 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)// strict partials so the union can discriminate by field names; the service// validates the patch against the template's actual auth methodtemplateFields: z- .union([ldapTemplateFieldsSchema.partial().strict(), kubernetesTemplateFieldsBaseSchema.partial().strict()])+ .union([+ ldapTemplateFieldsSchema.partial().strict(),+ kubernetesTemplateFieldsBaseSchema.partial().strict(),+ oidcTemplateFieldsSchema.partial().strict()+ ]).optional()}),response: {diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 5301ca3c1a..7bab9202b0 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -2213,6 +2213,7 @@ interface AddIdentityOidcAuthEvent {type: EventType.ADD_IDENTITY_OIDC_AUTH;metadata: {identityId: string;+ templateId?: string | null;oidcDiscoveryUrl: string;caCert: string;boundIssuer: string;@@ -2238,6 +2239,9 @@ interface UpdateIdentityOidcAuthEvent {type: EventType.UPDATE_IDENTITY_OIDC_AUTH;metadata: {identityId: string;+ identityName?: string;+ templateId?: string | null;+ templateName?: string;oidcDiscoveryUrl?: string;caCert?: string;boundIssuer?: string;diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.tsindex 0e27f20af5..53ea39a8fc 100644--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-dal.ts@@ -74,6 +74,17 @@ export const identityAuthTemplateDALFactory = (db: TDbClient) => {);const kubernetesDocs = await kubernetesQuery;return kubernetesDocs;+ case IdentityAuthTemplateMethod.OIDC:+ const oidcQuery = (tx || db.replicaNode())(TableName.IdentityOidcAuth)+ .join(TableName.Identity, `${TableName.IdentityOidcAuth}.identityId`, `${TableName.Identity}.id`)+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ .where(buildFindFilter({ templateId }, TableName.IdentityOidcAuth))+ .select(+ db.ref("identityId").withSchema(TableName.IdentityOidcAuth),+ db.ref("name").withSchema(TableName.Identity).as("identityName")+ );+ const oidcDocs = await oidcQuery;+ return oidcDocs;default:// fail loudly so a future auth method cannot silently report zero usagesthrow new BadRequestError({ message: `Templates with auth method '${authMethod}' are not supported` });diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-enums.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-enums.tsindex 3ef21fb1f3..322f8fd52a 100644--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-enums.ts+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-enums.ts@@ -1,6 +1,7 @@export enum IdentityAuthTemplateMethod {LDAP = "ldap",- KUBERNETES = "kubernetes"+ KUBERNETES = "kubernetes",+ OIDC = "oidc"}export const TEMPLATE_VALIDATION_MESSAGES = {@@ -22,6 +23,12 @@ export const TEMPLATE_VALIDATION_MESSAGES = {"A CA certificate is required when TLS certificate verification is enabled. Either paste the Kubernetes API server's CA certificate or disable verification.",TLS_VERIFICATION_CONFLICT:"TLS certificate verification cannot be disabled when a CA certificate is provided. Either remove the CA certificate or enable verification."+ },+ OIDC: {+ DISCOVERY_URL_REQUIRED: "OIDC discovery URL is required",+ DISCOVERY_URL_WELL_KNOWN_SUFFIX:+ "Remove the /.well-known/openid-configuration suffix from the OIDC discovery URL. Infisical appends it automatically.",+ ISSUER_REQUIRED: "Issuer is required"}} as const;@@ -35,5 +42,6 @@ export const TEMPLATE_SUCCESS_MESSAGES = {// template read path strips them, and the edit UI treats them as write-onlyexport const TEMPLATE_SECRET_FIELDS_BY_METHOD: Record<IdentityAuthTemplateMethod, readonly string[]> = {[IdentityAuthTemplateMethod.LDAP]: ["bindPass"],- [IdentityAuthTemplateMethod.KUBERNETES]: ["tokenReviewerJwt"]+ [IdentityAuthTemplateMethod.KUBERNETES]: ["tokenReviewerJwt"],+ [IdentityAuthTemplateMethod.OIDC]: []};diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-schemas.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-schemas.tsindex 0bf99c9aa4..1ab4d0fe57 100644--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-schemas.ts+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-schemas.ts@@ -5,6 +5,7 @@ import {kubernetesHostSchema,superRefineKubernetesConnectionFields} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-validators";+import { formatOidcAudiences } from "@app/services/identity-oidc-auth/identity-oidc-auth-validators";import { TEMPLATE_VALIDATION_MESSAGES } from "./identity-auth-template-enums";@@ -62,6 +63,45 @@ export const kubernetesTemplateFieldsCreateSchema = kubernetesTemplateFieldsBasesuperRefineKubernetesConnectionFields);+export const oidcTemplateFieldsSchema = z.object({+ oidcDiscoveryUrl: z+ .string()+ .trim()+ .url()+ .min(1, TEMPLATE_VALIDATION_MESSAGES.OIDC.DISCOVERY_URL_REQUIRED)+ .max(2048)+ // the login flow appends the suffix itself, so a URL stored with it would fetch+ // <url>/.well-known/openid-configuration/.well-known/openid-configuration and fail+ // at every login; the identity attach route predates this check, but a template is+ // authored once and copied everywhere, so it must not store the broken form+ .refine(+ (val) => !val.endsWith("/.well-known/openid-configuration"),+ TEMPLATE_VALIDATION_MESSAGES.OIDC.DISCOVERY_URL_WELL_KNOWN_SUFFIX+ )+ .describe("The URL used to retrieve the OpenID Connect configuration from the identity provider"),+ boundIssuer: z+ .string()+ .trim()+ .min(1, TEMPLATE_VALIDATION_MESSAGES.OIDC.ISSUER_REQUIRED)+ .max(2048)+ .describe("The unique identifier of the identity provider issuing the JWT"),+ // same normalization as the identity attach route, bounded because a template is a new+ // contract (the shared validator is unbounded only for the pre-existing identity routes)+ boundAudiences: z+ .string()+ .trim()+ .max(2048)+ .default("")+ .transform(formatOidcAudiences)+ .describe("The comma-separated list of intended recipients that JWT tokens must have in their aud claim"),+ caCert: z+ .string()+ .trim()+ .max(102400)+ .optional()+ .describe("The PEM-encoded CA certificate used to validate the identity provider's TLS certificate")+});+// response shapes: each write-only credential is replaced by a boolean presence flag,// mirroring $redactTemplateSecrets. Derived from the request schemas so a new template// field cannot reach the API undocumented, and so the response serializer drops anything@@ -82,7 +122,17 @@ export const kubernetesTemplateFieldsResponseSchema = kubernetesTemplateFieldsBahasTokenReviewerJwt: z.boolean().describe("Whether a token reviewer JWT is stored for this template")});+// OIDC templates hold no write-only credentials, so the response is the stored shape;+// audiences are re-declared as a plain string so the response schema carries no transform+export const oidcTemplateFieldsResponseSchema = oidcTemplateFieldsSchema.extend({+ boundAudiences: z+ .string()+ .default("")+ .describe("The comma-separated list of intended recipients that JWT tokens must have in their aud claim")+});+export const templateFieldPatchKeysByMethod = {ldap: Object.keys(ldapTemplateFieldsSchema.shape),- kubernetes: Object.keys(kubernetesTemplateFieldsBaseSchema.shape)+ kubernetes: Object.keys(kubernetesTemplateFieldsBaseSchema.shape),+ oidc: Object.keys(oidcTemplateFieldsSchema.shape)} as const;diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.tsindex f13f565982..c3c672b621 100644--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts@@ -43,6 +43,9 @@ const createService = ({const identityKubernetesAuthDAL = {updateByTemplateId: vi.fn().mockResolvedValue([{ identityId: "identity-id" }])};+ const identityOidcAuthDAL = {+ updateByTemplateId: vi.fn().mockResolvedValue([{ identityId: "identity-id" }])+ };const templateRow = {id: TEMPLATE_ID,@@ -62,6 +65,7 @@ const createService = ({id,...data})),+ delete: vi.fn().mockResolvedValue([templateRow]),transaction: vi.fn().mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) => cb({}))};@@ -72,11 +76,13 @@ const createService = ({find: vi.fn().mockImplementation(({ id }: { id: string }) => (liveGatewayV2Ids.includes(id) ? [{ id }] : []))};const gatewayPoolDAL = { findById: vi.fn().mockResolvedValue(null) };+ const auditLogCreate = vi.fn();const service = identityAuthTemplateServiceFactory({identityAuthTemplateDAL,identityLdapAuthDAL: { updateByTemplateId: vi.fn().mockResolvedValue([]) },identityKubernetesAuthDAL,+ identityOidcAuthDAL,gatewayDAL,gatewayV2DAL,gatewayPoolDAL,@@ -94,10 +100,10 @@ const createService = ({licenseService: {getPlan: vi.fn().mockResolvedValue({ machineIdentityAuthTemplates: true, gateway: true, gatewayPool: true })},- auditLogService: { createAuditLog: vi.fn() }+ auditLogService: { createAuditLog: auditLogCreate }} as unknown as Parameters<typeof identityAuthTemplateServiceFactory>[0]);- return { service, identityKubernetesAuthDAL, identityAuthTemplateDAL };+ return { service, identityKubernetesAuthDAL, identityOidcAuthDAL, identityAuthTemplateDAL, auditLogCreate };};const patchTemplate = (service: ReturnType<typeof createService>["service"], templateFields: Record<string, unknown>) =>@@ -247,3 +253,95 @@ describe("identityAuthTemplateServiceFactory gateway column storage", () => {);});});++const baseOidcBlobFields = {+ oidcDiscoveryUrl: PUBLIC_HOST,+ boundIssuer: "https://issuer.example.com",+ boundAudiences: "https://github.com/acme",+ caCert: "stored-ca"+};++const createOidcService = (blobFields: Record<string, unknown> = baseOidcBlobFields) =>+ createService({ authMethod: IdentityAuthTemplateMethod.OIDC, blobFields, gatewayColumns: NO_GATEWAY });++describe("identityAuthTemplateServiceFactory oidc templates", () => {+ beforeEach(() => vi.clearAllMocks());++ it("propagates the full merged connection to linked identities, not just the patched keys", async () => {+ const { service, identityOidcAuthDAL } = createOidcService();++ await patchTemplate(service, { boundIssuer: "https://other-issuer.example.com" });++ expect(identityOidcAuthDAL.updateByTemplateId).toHaveBeenCalledWith(+ { templateId: TEMPLATE_ID },+ {+ oidcDiscoveryUrl: PUBLIC_HOST,+ boundIssuer: "https://other-issuer.example.com",+ boundAudiences: "https://github.com/acme",+ encryptedCaCertificate: Buffer.from("stored-ca")+ },+ expect.anything()+ );+ });++ it("clears the propagated CA certificate when the patch empties it", async () => {+ const { service, identityOidcAuthDAL } = createOidcService();++ await patchTemplate(service, { caCert: "" });++ expect(identityOidcAuthDAL.updateByTemplateId).toHaveBeenCalledWith(+ { templateId: TEMPLATE_ID },+ expect.objectContaining({ encryptedCaCertificate: null }),+ expect.anything()+ );+ });++ it("blocks a private discovery URL before anything propagates", async () => {+ const { service, identityOidcAuthDAL } = createOidcService();++ await expect(patchTemplate(service, { oidcDiscoveryUrl: PRIVATE_HOST })).rejects.toThrow(+ "Local IPs not allowed as URL"+ );+ expect(identityOidcAuthDAL.updateByTemplateId).not.toHaveBeenCalled();+ });++ it("blocks even an unrelated edit while a private discovery URL is stored", async () => {+ // create/update both vet the URL, but an operator toggle (dev mode, allow-internal) can+ // let one through; any patch propagates the whole merged connection, so it must re-vet+ const { service, identityOidcAuthDAL } = createOidcService({+ ...baseOidcBlobFields,+ oidcDiscoveryUrl: PRIVATE_HOST+ });++ await expect(patchTemplate(service, { boundAudiences: "aud" })).rejects.toThrow("Local IPs not allowed as URL");+ expect(identityOidcAuthDAL.updateByTemplateId).not.toHaveBeenCalled();+ });++ it("audits the propagation as an OIDC auth update", async () => {+ const { service, auditLogCreate } = createOidcService();++ await patchTemplate(service, { boundIssuer: "https://other-issuer.example.com" });++ expect(auditLogCreate).toHaveBeenCalledTimes(1);+ const [entry] = auditLogCreate.mock.calls[0] as [{ event: { type: string } }];+ expect(entry.event.type).toBe("update-identity-oidc-auth");+ });++ it("unlinks linked identities on delete while keeping their copied config", async () => {+ const { service, identityOidcAuthDAL } = createOidcService();++ await service.deleteTemplate({+ templateId: TEMPLATE_ID,+ actorId: "actor-id",+ actor: "user",+ actorAuthMethod: undefined,+ actorOrgId: ORG_ID+ } as unknown as Parameters<typeof service.deleteTemplate>[0]);++ expect(identityOidcAuthDAL.updateByTemplateId).toHaveBeenCalledWith(+ { templateId: TEMPLATE_ID },+ { templateId: null },+ expect.anything()+ );+ });+});diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.tsindex 02ea1e83bb..ef52c49a32 100644--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts@@ -1,6 +1,6 @@import { ForbiddenError } from "@casl/ability";-import { OrganizationActionScope, TIdentityKubernetesAuthsUpdate } from "@app/db/schemas";+import { OrganizationActionScope, TIdentityKubernetesAuthsUpdate, TIdentityOidcAuthsUpdate } from "@app/db/schemas";import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";@@ -24,6 +24,7 @@ import { withKubernetesHostScheme } from "@app/services/identity-kubernetes-authimport { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";import { validateKubernetesConnectionFields } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-validators";import { TIdentityLdapAuthDALFactory } from "@app/services/identity-ldap-auth/identity-ldap-auth-dal";+import { TIdentityOidcAuthDALFactory } from "@app/services/identity-oidc-auth/identity-oidc-auth-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";@@ -38,6 +39,7 @@ import {TKubernetesTemplateFields,TLdapTemplateFields,TListIdentityAuthTemplatesDTO,+ TOidcTemplateFields,TSanitizedIdentityAuthTemplate,TUnlinkTemplateUsageDTO} from "./identity-auth-template-types";@@ -46,6 +48,7 @@ type TIdentityAuthTemplateServiceFactoryDep = {identityAuthTemplateDAL: TIdentityAuthTemplateDALFactory;identityLdapAuthDAL: Pick<TIdentityLdapAuthDALFactory, "updateByTemplateId">;identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "updateByTemplateId">;+ identityOidcAuthDAL: Pick<TIdentityOidcAuthDALFactory, "updateByTemplateId">;gatewayDAL: Pick<TGatewayDALFactory, "find">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;@@ -63,6 +66,7 @@ export const identityAuthTemplateServiceFactory = ({identityAuthTemplateDAL,identityLdapAuthDAL,identityKubernetesAuthDAL,+ identityOidcAuthDAL,gatewayDAL,gatewayV2DAL,gatewayPoolDAL,@@ -104,6 +108,20 @@ export const identityAuthTemplateServiceFactory = ({// audit the platform-driven rewrite of linked identities; runs after the propagation// transaction commits so the tx never waits on Redis, chunked to bound concurrency+ const $templatePropagationEvent = (+ authMethod: string,+ metadata: { identityId: string; identityName?: string; templateId: string; templateName: string }+ ) => {+ switch (authMethod) {+ case IdentityAuthTemplateMethod.LDAP:+ return { type: EventType.UPDATE_IDENTITY_LDAP_AUTH, metadata } as const;+ case IdentityAuthTemplateMethod.OIDC:+ return { type: EventType.UPDATE_IDENTITY_OIDC_AUTH, metadata } as const;+ default:+ return { type: EventType.UPDATE_IDENTITY_KUBENETES_AUTH, metadata } as const;+ }+ };+const $auditTemplatePropagation = async ({identities,authMethod,@@ -127,16 +145,7 @@ export const identityAuthTemplateServiceFactory = ({metadata: {}},orgId,- event:- authMethod === IdentityAuthTemplateMethod.LDAP- ? {- type: EventType.UPDATE_IDENTITY_LDAP_AUTH,- metadata: { identityId, identityName, templateId, templateName }- }- : {- type: EventType.UPDATE_IDENTITY_KUBENETES_AUTH,- metadata: { identityId, identityName, templateId, templateName }- }+ event: $templatePropagationEvent(authMethod, { identityId, identityName, templateId, templateName })})));@@ -334,6 +343,12 @@ export const identityAuthTemplateServiceFactory = ({fieldsToPersist = normalizedFields;}+ if (authMethod === IdentityAuthTemplateMethod.OIDC) {+ // parity with the identity attach flow: a template-authored discovery URL must not+ // let the backend dial local or private addresses+ await blockLocalAndPrivateIpAddresses((templateFields as TOidcTemplateFields).oidcDiscoveryUrl);+ }+const { encryptor } = await kmsService.createCipherPairWithDataKey({type: KmsDataKey.Organization,orgId: actorOrgId@@ -490,6 +505,24 @@ export const identityAuthTemplateServiceFactory = ({kubernetesPropagationData.gatewayPoolId = effectiveGatewayColumns.gatewayPoolId;}+ let oidcPropagationData: TIdentityOidcAuthsUpdate | undefined;+ if (fieldPatch && template.authMethod === IdentityAuthTemplateMethod.OIDC) {+ const merged = mergedTemplateFields as TOidcTemplateFields;+ // the merged URL propagates to every linked identity on this patch, so vet it on+ // every propagation rather than only when the patch touches it (login re-validates+ // before dialing, but the template must never store a URL its author could not+ // have set directly)+ await blockLocalAndPrivateIpAddresses(merged.oidcDiscoveryUrl);+ oidcPropagationData = {+ oidcDiscoveryUrl: merged.oidcDiscoveryUrl,+ boundIssuer: merged.boundIssuer,+ boundAudiences: merged.boundAudiences ?? "",+ encryptedCaCertificate: merged.caCert+ ? encryptor({ plainText: Buffer.from(merged.caCert) }).cipherTextBlob+ : null+ };+ }+const { updatedTemplate, propagatedIdentityIds } = await identityAuthTemplateDAL.transaction(async (tx) => {const authTemplate = await identityAuthTemplateDAL.updateById(templateId,@@ -555,6 +588,11 @@ export const identityAuthTemplateServiceFactory = ({identityIds = updatedRows.map((row) => row.identityId);}+ if (oidcPropagationData) {+ const updatedRows = await identityOidcAuthDAL.updateByTemplateId({ templateId }, oidcPropagationData, tx);+ identityIds = updatedRows.map((row) => row.identityId);+ }+return { updatedTemplate: authTemplate, propagatedIdentityIds: identityIds };});@@ -618,6 +656,9 @@ export const identityAuthTemplateServiceFactory = ({tx);identityIds = updatedRows.map((row) => row.identityId);+ } else if (template.authMethod === IdentityAuthTemplateMethod.OIDC) {+ const updatedRows = await identityOidcAuthDAL.updateByTemplateId({ templateId }, { templateId: null }, tx);+ identityIds = updatedRows.map((row) => row.identityId);} else {// fail loudly rather than deleting a template whose linked identities we cannot unlinkthrow new BadRequestError({@@ -832,6 +873,12 @@ export const identityAuthTemplateServiceFactory = ({{ templateId: null });unlinkedIdentityIds = updatedRows.map((row) => row.identityId);+ } else if (template.authMethod === IdentityAuthTemplateMethod.OIDC) {+ const updatedRows = await identityOidcAuthDAL.updateByTemplateId(+ { templateId, identityIds },+ { templateId: null }+ );+ unlinkedIdentityIds = updatedRows.map((row) => row.identityId);} else {throw new BadRequestError({message: `Unlinking templates with auth method '${template.authMethod}' is not supported`diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-types.tsindex 913149a044..b79d53e24c 100644--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts@@ -7,7 +7,8 @@ import { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kuimport { IdentityAuthTemplateMethod } from "./identity-auth-template-enums";import {kubernetesTemplateFieldsResponseSchema,- ldapTemplateFieldsResponseSchema+ ldapTemplateFieldsResponseSchema,+ oidcTemplateFieldsResponseSchema} from "./identity-auth-template-schemas";// what every read path returns: the row with its credentials replaced by presence flags.@@ -25,6 +26,10 @@ export type TSanitizedIdentityAuthTemplate = Omit<authMethod: IdentityAuthTemplateMethod.KUBERNETES;templateFields: z.infer<typeof kubernetesTemplateFieldsResponseSchema>;}+ | {+ authMethod: IdentityAuthTemplateMethod.OIDC;+ templateFields: z.infer<typeof oidcTemplateFieldsResponseSchema>;+ });// Method-specific template field types@@ -47,6 +52,13 @@ export type TKubernetesTemplateFields = {allowedAudience?: string;};+export type TOidcTemplateFields = {+ oidcDiscoveryUrl: string;+ boundIssuer: string;+ boundAudiences?: string;+ caCert?: string;+};+export type TDeleteIdentityAuthTemplateDTO = {templateId: string;} & Omit<TProjectPermission, "projectId">;diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 22cf146060..d45814c5d3 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -719,6 +719,8 @@ export const OIDC_AUTH = {},ATTACH: {identityId: "The ID of the machine identity to attach the configuration onto.",+ templateId:+ "The ID of the OIDC auth template to source identity provider settings from. When provided, the OIDC discovery URL, issuer, audiences, and CA certificate are taken from the template and cannot be set individually.",oidcDiscoveryUrl: "The URL used to retrieve the OpenID Connect configuration from the identity provider.",caCert: "The PEM-encoded CA cert for establishing secure communication with the Identity Provider endpoints.",boundIssuer: "The unique identifier of the identity provider issuing the JWT.",@@ -733,6 +735,8 @@ export const OIDC_AUTH = {},UPDATE: {identityId: "The ID of the machine identity to update the auth method for.",+ templateId:+ "The ID of the OIDC auth template to link. While linked, identity provider settings are managed by the template and cannot be set individually. Pass null to unlink the template; the settings copied from it are kept.",oidcDiscoveryUrl: "The new URL used to retrieve the OpenID Connect configuration from the identity provider.",caCert: "The new PEM-encoded CA cert for establishing secure communication with the Identity Provider endpoints.",boundIssuer: "The new unique identifier of the identity provider issuing the JWT.",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e230d1efb5..902ae57a2c 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2561,6 +2561,7 @@ export const registerRoutes = async (identityAuthTemplateDAL,identityLdapAuthDAL,identityKubernetesAuthDAL,+ identityOidcAuthDAL,gatewayDAL,gatewayV2DAL,gatewayPoolDAL,@@ -2703,6 +2704,7 @@ export const registerRoutes = async (const identityOidcAuthService = identityOidcAuthServiceFactory({identityDAL,identityOidcAuthDAL,+ identityAuthTemplateDAL,orgDAL,identityAccessTokenDAL,permissionService,diff --git a/backend/src/server/routes/v1/identity-oidc-auth-router.ts b/backend/src/server/routes/v1/identity-oidc-auth-router.tsindex f3f6beddfd..9c79390008 100644--- a/backend/src/server/routes/v1/identity-oidc-auth-router.ts+++ b/backend/src/server/routes/v1/identity-oidc-auth-router.ts@@ -12,7 +12,9 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { ActorType, AuthMode } from "@app/services/auth/auth-type";import { TIdentityTrustedIp } from "@app/services/identity/identity-types";import {+ rejectTemplateManagedOidcFields,validateOidcAuthAudiencesField,+ validateOidcAuthAudiencesFieldOptional,validateOidcBoundClaimsField} from "@app/services/identity-oidc-auth/identity-oidc-auth-validators";import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";@@ -31,6 +33,7 @@ const IdentityOidcAuthResponseSchema = IdentityOidcAuthsSchema.pick({boundClaims: true,claimMetadataMapping: true,boundSubject: true,+ templateId: true,createdAt: true,updatedAt: true}).extend({@@ -169,10 +172,14 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)}),body: z.object({- oidcDiscoveryUrl: z.string().url().min(1).describe(OIDC_AUTH.ATTACH.oidcDiscoveryUrl),- caCert: z.string().trim().default("").describe(OIDC_AUTH.ATTACH.caCert),- boundIssuer: z.string().min(1).describe(OIDC_AUTH.ATTACH.boundIssuer),- boundAudiences: validateOidcAuthAudiencesField.describe(OIDC_AUTH.ATTACH.boundAudiences),+ templateId: z.string().uuid().optional().describe(OIDC_AUTH.ATTACH.templateId),+ // no zod defaults on the template-managed fields: a default would make them+ // indistinguishable from caller-supplied values, so template attaches could not+ // reject them; the service defaults them on the custom path+ oidcDiscoveryUrl: z.string().url().min(1).optional().describe(OIDC_AUTH.ATTACH.oidcDiscoveryUrl),+ caCert: z.string().trim().optional().describe(OIDC_AUTH.ATTACH.caCert),+ boundIssuer: z.string().min(1).optional().describe(OIDC_AUTH.ATTACH.boundIssuer),+ boundAudiences: validateOidcAuthAudiencesFieldOptional.describe(OIDC_AUTH.ATTACH.boundAudiences),boundClaims: validateOidcBoundClaimsField.describe(OIDC_AUTH.ATTACH.boundClaims),claimMetadataMapping: validateOidcBoundClaimsField.describe(OIDC_AUTH.ATTACH.claimMetadataMapping).optional(),boundSubject: z.string().optional().default("").describe(OIDC_AUTH.ATTACH.boundSubject),@@ -200,10 +207,44 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider).describe(OIDC_AUTH.ATTACH.accessTokenMaxTTL),accessTokenNumUsesLimit: z.number().int().min(0).default(0).describe(OIDC_AUTH.ATTACH.accessTokenNumUsesLimit)})- .refine(- (val) => val.accessTokenTTL <= val.accessTokenMaxTTL,- "Access Token TTL cannot be greater than Access Token Max TTL."- ),+ .superRefine((data, ctx) => {+ if (data.templateId) {+ rejectTemplateManagedOidcFields(data, ctx);+ // the template only pins the issuer; without a per-identity binding, any+ // token that issuer signs could authenticate as this identity+ if (!data.boundSubject && Object.keys(data.boundClaims ?? {}).length === 0) {+ ctx.addIssue({+ path: ["boundSubject"],+ code: z.ZodIssueCode.custom,+ message:+ "When using an auth template, set a subject or at least one claim binding to restrict which workloads can authenticate as this identity."+ });+ }+ } else {+ if (data.oidcDiscoveryUrl === undefined) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "OIDC discovery URL is required when not using an auth template"+ });+ }+ if (data.boundIssuer === undefined) {+ ctx.addIssue({+ path: ["boundIssuer"],+ code: z.ZodIssueCode.custom,+ message: "Issuer is required when not using an auth template"+ });+ }+ }++ if (data.accessTokenTTL > data.accessTokenMaxTTL) {+ ctx.addIssue({+ path: ["accessTokenTTL"],+ code: z.ZodIssueCode.custom,+ message: "Access Token TTL cannot be greater than Access Token Max TTL."+ });+ }+ }),response: {200: z.object({identityOidcAuth: IdentityOidcAuthResponseSchema@@ -228,6 +269,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)type: EventType.ADD_IDENTITY_OIDC_AUTH,metadata: {identityId: identityOidcAuth.identityId,+ templateId: identityOidcAuth.templateId,oidcDiscoveryUrl: identityOidcAuth.oidcDiscoveryUrl,caCert: identityOidcAuth.caCert,boundIssuer: identityOidcAuth.boundIssuer,@@ -318,10 +360,21 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)accessTokenNumUsesLimit: z.number().int().min(0).default(0).describe(OIDC_AUTH.UPDATE.accessTokenNumUsesLimit)}).partial()- .refine(- (val) => (val.accessTokenMaxTTL && val.accessTokenTTL ? val.accessTokenTTL <= val.accessTokenMaxTTL : true),- "Access Token TTL cannot be greater than Access Token Max TTL."- ),+ .extend({+ templateId: z.string().uuid().nullable().optional().describe(OIDC_AUTH.UPDATE.templateId)+ })+ .superRefine((data, ctx) => {+ if (data.templateId) {+ rejectTemplateManagedOidcFields(data, ctx);+ }+ if (data.accessTokenMaxTTL && data.accessTokenTTL ? data.accessTokenTTL > data.accessTokenMaxTTL : false) {+ ctx.addIssue({+ path: ["accessTokenTTL"],+ code: z.ZodIssueCode.custom,+ message: "Access Token TTL cannot be greater than Access Token Max TTL."+ });+ }+ }),response: {200: z.object({identityOidcAuth: IdentityOidcAuthResponseSchema@@ -346,6 +399,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)type: EventType.UPDATE_IDENTITY_OIDC_AUTH,metadata: {identityId: identityOidcAuth.identityId,+ templateId: identityOidcAuth.templateId,oidcDiscoveryUrl: identityOidcAuth.oidcDiscoveryUrl,caCert: identityOidcAuth.caCert,boundIssuer: identityOidcAuth.boundIssuer,diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-dal.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-dal.tsindex 1d8ab3c137..2550ab5397 100644--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-dal.ts+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-dal.ts@@ -1,10 +1,26 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";+import { TableName, TIdentityOidcAuthsUpdate } from "@app/db/schemas";import { ormify } from "@app/lib/knex";export type TIdentityOidcAuthDALFactory = ReturnType<typeof identityOidcAuthDALFactory>;export const identityOidcAuthDALFactory = (db: TDbClient) => {const oidcAuthOrm = ormify(db, TableName.IdentityOidcAuth);- return oidcAuthOrm;++ // narrow returning: template propagation only needs the affected identity ids, not the+ // full rows with their encrypted credential buffers+ const updateByTemplateId = async (+ { templateId, identityIds }: { templateId: string; identityIds?: string[] },+ data: TIdentityOidcAuthsUpdate,+ tx?: Knex+ ): Promise<{ identityId: string }[]> => {+ const query = (tx || db)(TableName.IdentityOidcAuth).where({ templateId });+ if (identityIds) void query.whereIn("identityId", identityIds);+ const docs: { identityId: string }[] = await query.update(data).returning("identityId");+ return docs;+ };++ return { ...oidcAuthOrm, updateByTemplateId };};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 d0a03fbc41..90628cb8c3 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@@ -11,8 +11,16 @@ import {OrganizationActionScope,TIdentityOidcAuthsUpdate} from "@app/db/schemas";+import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";+import { TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template/identity-auth-template-dal";+import { IdentityAuthTemplateMethod } from "@app/ee/services/identity-auth-template/identity-auth-template-enums";+import { TOidcTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";-import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";+import {+ OrgPermissionIdentityActions,+ OrgPermissionMachineIdentityAuthTemplateActions,+ OrgPermissionSubjects+} from "@app/ee/services/permission/org-permission";import {constructPermissionErrorMessage,validatePrivilegeChangeOperation@@ -67,6 +75,7 @@ import {type TIdentityOidcAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identityOidcAuthDAL: TIdentityOidcAuthDALFactory;+ identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId">;membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;@@ -85,6 +94,7 @@ export type TIdentityOidcAuthServiceFactory = ReturnType<typeof identityOidcAuthexport const identityOidcAuthServiceFactory = ({identityDAL,identityOidcAuthDAL,+ identityAuthTemplateDAL,membershipIdentityDAL,keyStore,permissionService,@@ -579,25 +589,26 @@ export const identityOidcAuthServiceFactory = ({}};- const attachOidcAuth = async ({- identityId,- oidcDiscoveryUrl,- caCert,- boundIssuer,- boundAudiences,- boundClaims,- claimMetadataMapping,- boundSubject,- accessTokenTTL,- accessTokenMaxTTL,- accessTokenNumUsesLimit,- accessTokenTrustedIps,- actorId,- actorAuthMethod,- actor,- actorOrgId,- isActorSuperAdmin- }: TAttachOidcAuthDTO) => {+ const attachOidcAuth = async (dto: TAttachOidcAuthDTO) => {+ const {+ identityId,+ templateId,+ boundClaims,+ claimMetadataMapping,+ boundSubject,+ accessTokenTTL,+ accessTokenMaxTTL,+ accessTokenNumUsesLimit,+ accessTokenTrustedIps,+ actorId,+ actorAuthMethod,+ actor,+ actorOrgId,+ isActorSuperAdmin+ } = dto;+ // the route leaves these optional (no zod default) so template-managed values can be+ // detected and rejected when a template is used; defaulted below for the custom path+ let { oidcDiscoveryUrl, caCert, boundIssuer, boundAudiences } = dto;const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({scopeData: {scope: AccessScope.Organization,@@ -655,6 +666,69 @@ export const identityOidcAuthServiceFactory = ({await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: identityMembershipOrg.scopeOrgId+ });++ let template: TIdentityAuthTemplates | undefined;+ if (templateId) {+ if (!plan.machineIdentityAuthTemplates) {+ throw new BadRequestError({+ message:+ "Failed to use identity auth template due to plan restriction. Upgrade plan to access machine identity auth templates."+ });+ }++ const { permission: orgPermission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId: identityMembershipOrg.scopeOrgId,+ actorAuthMethod,+ actorOrgId+ });+ ForbiddenError.from(orgPermission).throwUnlessCan(+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,+ OrgPermissionSubjects.MachineIdentityAuthTemplate+ );++ template = await identityAuthTemplateDAL.findByIdAndOrgId(templateId, identityMembershipOrg.scopeOrgId);+ if (!template || template.authMethod !== IdentityAuthTemplateMethod.OIDC) {+ throw new NotFoundError({ message: `OIDC auth template with ID '${templateId}' not found` });+ }++ const templateFields = JSON.parse(+ decryptor({ cipherTextBlob: template.templateFields }).toString()+ ) as TOidcTemplateFields;++ oidcDiscoveryUrl = templateFields.oidcDiscoveryUrl;+ boundIssuer = templateFields.boundIssuer;+ boundAudiences = templateFields.boundAudiences ?? "";+ caCert = templateFields.caCert || "";++ // a template's bindings identify the issuer, not a workload; with no per-identity+ // binding, any token that issuer signs (e.g. any workflow in the org) could log in+ // as this identity, so require the caller to scope it+ if (!boundSubject && Object.keys(boundClaims).length === 0) {+ throw new BadRequestError({+ message:+ "When using an auth template, set a subject or at least one claim binding to restrict which workloads can authenticate as this identity."+ });+ }+ }++ if (!oidcDiscoveryUrl || !boundIssuer) {+ throw new BadRequestError({+ message: "OIDC discovery URL and issuer are required when not using an auth template."+ });+ }+ // consts so the narrowing survives into the transaction closure below+ const resolvedOidcDiscoveryUrl = oidcDiscoveryUrl;+ const resolvedBoundIssuer = boundIssuer;+ const resolvedCaCert = caCert ?? "";+ const resolvedBoundAudiences = boundAudiences ?? "";+const reformattedAccessTokenTrustedIps = accessTokenTrustedIps.map((accessTokenTrustedIp) => {if (!plan.ipAllowlisting &&@@ -672,21 +746,17 @@ export const identityOidcAuthServiceFactory = ({return extractIPDetails(accessTokenTrustedIp.ipAddress);});- await blockLocalAndPrivateIpAddresses(oidcDiscoveryUrl);-- const { encryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: identityMembershipOrg.scopeOrgId- });+ await blockLocalAndPrivateIpAddresses(resolvedOidcDiscoveryUrl);const identityOidcAuth = await identityOidcAuthDAL.transaction(async (tx) => {const doc = await identityOidcAuthDAL.create({identityId: identityMembershipOrg.identity.id,- oidcDiscoveryUrl,- encryptedCaCertificate: encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob,- boundIssuer,- boundAudiences,+ templateId: template?.id ?? null,+ oidcDiscoveryUrl: resolvedOidcDiscoveryUrl,+ encryptedCaCertificate: encryptor({ plainText: Buffer.from(resolvedCaCert) }).cipherTextBlob,+ boundIssuer: resolvedBoundIssuer,+ boundAudiences: resolvedBoundAudiences,boundClaims,claimMetadataMapping,boundSubject,@@ -700,28 +770,27 @@ export const identityOidcAuthServiceFactory = ({return doc;});await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.OIDC_AUTH);- return { ...identityOidcAuth, orgId: identityMembershipOrg.scopeOrgId, caCert };+ return { ...identityOidcAuth, orgId: identityMembershipOrg.scopeOrgId, caCert: resolvedCaCert };};- const updateOidcAuth = async ({- identityId,- oidcDiscoveryUrl,- caCert,- boundIssuer,- boundAudiences,- boundClaims,- claimMetadataMapping,- boundSubject,- accessTokenTTL,- accessTokenMaxTTL,- accessTokenNumUsesLimit,- accessTokenTrustedIps,- actorId,- actorAuthMethod,- actor,- actorOrgId,- isActorSuperAdmin- }: TUpdateOidcAuthDTO) => {+ const updateOidcAuth = async (dto: TUpdateOidcAuthDTO) => {+ const {+ identityId,+ templateId,+ boundClaims,+ claimMetadataMapping,+ boundSubject,+ accessTokenTTL,+ accessTokenMaxTTL,+ accessTokenNumUsesLimit,+ accessTokenTrustedIps,+ actorId,+ actorAuthMethod,+ actor,+ actorOrgId,+ isActorSuperAdmin+ } = dto;+ let { oidcDiscoveryUrl, caCert, boundIssuer, boundAudiences } = dto;const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({scopeData: {scope: AccessScope.Organization,@@ -782,6 +851,79 @@ export const identityOidcAuthServiceFactory = ({await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: identityMembershipOrg.scopeOrgId+ });++ let template: TIdentityAuthTemplates | undefined;+ // the UI re-sends the current templateId on every save of a linked identity, so only a+ // link CHANGE requires the attach-template permission; a re-assert must stay editable+ // for actors that hold identity EditAuth alone+ if (templateId && templateId !== identityOidcAuth.templateId) {+ if (!plan.machineIdentityAuthTemplates) {+ throw new BadRequestError({+ message:+ "Failed to use identity auth template due to plan restriction. Upgrade plan to access machine identity auth templates."+ });+ }++ const { permission: orgPermission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId: identityMembershipOrg.scopeOrgId,+ actorAuthMethod,+ actorOrgId+ });+ ForbiddenError.from(orgPermission).throwUnlessCan(+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,+ OrgPermissionSubjects.MachineIdentityAuthTemplate+ );++ template = await identityAuthTemplateDAL.findByIdAndOrgId(templateId, identityMembershipOrg.scopeOrgId);+ if (!template || template.authMethod !== IdentityAuthTemplateMethod.OIDC) {+ throw new NotFoundError({ message: `OIDC auth template with ID '${templateId}' not found` });+ }++ const templateFields = JSON.parse(+ decryptor({ cipherTextBlob: template.templateFields }).toString()+ ) as TOidcTemplateFields;++ oidcDiscoveryUrl = templateFields.oidcDiscoveryUrl;+ boundIssuer = templateFields.boundIssuer;+ boundAudiences = templateFields.boundAudiences ?? "";+ caCert = templateFields.caCert ?? "";+ } else if (templateId === undefined && identityOidcAuth.templateId) {+ const hasTemplateManagedFieldChanges =+ oidcDiscoveryUrl !== undefined ||+ boundIssuer !== undefined ||+ boundAudiences !== undefined ||+ caCert !== undefined;+ if (hasTemplateManagedFieldChanges) {+ throw new BadRequestError({+ message:+ "This identity's OIDC identity provider settings are managed by an auth template. Update the template to change them, or unlink the template by setting templateId to null."+ });+ }+ }++ // a linked identity must always carry its own principal binding (see attach); this+ // also covers linking a template onto an identity whose bindings are empty, and a+ // linked identity clearing them, since the template supplies no binding of its own+ const templateIdAfterUpdate = templateId === undefined ? identityOidcAuth.templateId : templateId;+ if (templateIdAfterUpdate) {+ const effectiveBoundSubject = boundSubject !== undefined ? boundSubject : (identityOidcAuth.boundSubject ?? "");+ const effectiveBoundClaims =+ boundClaims !== undefined ? boundClaims : ((identityOidcAuth.boundClaims ?? {}) as Record<string, string>);+ if (!effectiveBoundSubject && Object.keys(effectiveBoundClaims).length === 0) {+ throw new BadRequestError({+ message:+ "When using an auth template, set a subject or at least one claim binding to restrict which workloads can authenticate as this identity."+ });+ }+ }+const reformattedAccessTokenTrustedIps = accessTokenTrustedIps?.map((accessTokenTrustedIp) => {if (!plan.ipAllowlisting &&@@ -810,6 +952,9 @@ export const identityOidcAuthServiceFactory = ({boundClaims,claimMetadataMapping,boundSubject,+ // tri-state passthrough: undefined keeps the current link, null unlinks, a uuid links+ // (a re-assert of the current id skips the template load above, so template is unset)+ templateId,accessTokenMaxTTL,accessTokenTTL,accessTokenNumUsesLimit,@@ -818,11 +963,6 @@ export const identityOidcAuthServiceFactory = ({: undefined};- const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: identityMembershipOrg.scopeOrgId- });-if (caCert !== undefined) {updateQuery.encryptedCaCertificate = encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob;}diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-types.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-types.tsindex a5eca0bac6..5f7751c5e2 100644--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-types.ts+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-types.ts@@ -2,10 +2,11 @@ import { TProjectPermission } from "@app/lib/types";export type TAttachOidcAuthDTO = {identityId: string;- oidcDiscoveryUrl: string;- caCert: string;- boundIssuer: string;- boundAudiences: string;+ templateId?: string;+ oidcDiscoveryUrl?: string;+ caCert?: string;+ boundIssuer?: string;+ boundAudiences?: string;boundClaims: Record<string, string>;claimMetadataMapping?: Record<string, string>;boundSubject: string;@@ -18,6 +19,7 @@ export type TAttachOidcAuthDTO = {export type TUpdateOidcAuthDTO = {identityId: string;+ templateId?: string | null;oidcDiscoveryUrl?: string;caCert?: string;boundIssuer?: string;diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-validators.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-validators.tsindex f20702604f..5051204fb7 100644--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-validators.ts+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-validators.ts@@ -1,16 +1,18 @@import { z } from "zod";-export const validateOidcAuthAudiencesField = z- .string()- .trim()- .default("")- .transform((data) => {- if (data === "") return "";- return data- .split(",")- .map((id) => id.trim())- .join(", ");- });+export const formatOidcAudiences = (data: string) => {+ if (data === "") return "";+ return data+ .split(",")+ .map((id) => id.trim())+ .join(", ");+};++export const validateOidcAuthAudiencesField = z.string().trim().default("").transform(formatOidcAudiences);++// no default so a template attach can tell "caller supplied audiences" apart from+// "field omitted"; the service defaults the custom path to ""+export const validateOidcAuthAudiencesFieldOptional = z.string().trim().transform(formatOidcAudiences).optional();export const validateOidcBoundClaimsField = z.record(z.string()).transform((data) => {const formattedClaims: Record<string, string> = {};@@ -23,3 +25,24 @@ export const validateOidcBoundClaimsField = z.record(z.string()).transform((datareturn formattedClaims;});++// fields the linked auth template owns on an identity's OIDC auth; both the attach+// and update routes reject them so the two endpoints cannot drift apart+export const TEMPLATE_MANAGED_OIDC_AUTH_FIELDS = [+ "oidcDiscoveryUrl",+ "boundIssuer",+ "boundAudiences",+ "caCert"+] as const;++export const rejectTemplateManagedOidcFields = (data: Record<string, unknown>, ctx: z.RefinementCtx) => {+ TEMPLATE_MANAGED_OIDC_AUTH_FIELDS.forEach((field) => {+ if (data[field] !== undefined) {+ ctx.addIssue({+ path: [field],+ code: z.ZodIssueCode.custom,+ message: `${field} is managed by the auth template and cannot be provided`+ });+ }+ });+};diff --git a/docs/documentation/platform/identities/auth-templates.mdx b/docs/documentation/platform/identities/auth-templates.mdxindex 2d9ae7a96d..e7c085106d 100644--- a/docs/documentation/platform/identities/auth-templates.mdx+++ b/docs/documentation/platform/identities/auth-templates.mdx@@ -38,7 +38,7 @@ Auth templates are managed in **Organization Settings > Access Control > Identit- Select the authentication method you want to create a template for (currently supports LDAP Auth and Kubernetes Auth).+ Select the authentication method you want to create a template for (currently supports LDAP Auth, Kubernetes Auth, and OIDC Auth).</Step><Step title="Configure template settings">@@ -78,6 +78,21 @@ Auth templates are managed in **Organization Settings > Access Control > IdentitYou can read more about Kubernetes Auth configuration in the [Kubernetes Auth documentation](/documentation/platform/identities/kubernetes-auth).</Note></Tab>+ <Tab title="OIDC Auth Template">+ **For OIDC Auth templates**, configure the following fields:++ - **Template Name**: A descriptive name for your template+ - **OIDC Discovery URL**: The URL used to retrieve the OpenID Connect configuration from the identity provider, without the `/.well-known/openid-configuration` suffix. For example, `https://token.actions.githubusercontent.com`.+ - **Issuer**: The unique identifier of the identity provider issuing the JWT, checked against the token's `iss` claim.+ - **Audiences**: An optional comma-separated list of values the token's `aud` claim must match. For providers like GitHub Actions, this is constant across your organization (for example, `https://github.com/your-org`), which makes it a good fit for the template.+ - **CA Certificate**: An optional PEM-encoded CA certificate used for secure communication with the identity provider endpoints, for providers behind a private certificate authority.++ Subject, claims, claim metadata mappings, and access token settings are not part of the template. They are configured per identity, since they define which workloads may authenticate as each specific identity. When attaching an OIDC template, each identity must set a subject or at least one claim binding.++ <Note>+ You can read more about OIDC Auth configuration in the [OIDC Auth documentation](/documentation/platform/identities/oidc-auth/general).+ </Note>+ </Tab></Tabs></Step></Steps>diff --git a/frontend/src/hooks/api/identities/mutations.tsx b/frontend/src/hooks/api/identities/mutations.tsxindex f37eadbd37..6c19715bdd 100644--- a/frontend/src/hooks/api/identities/mutations.tsx+++ b/frontend/src/hooks/api/identities/mutations.tsx@@ -939,6 +939,7 @@ export const useUpdateIdentityOidcAuth = () => {return useMutation<IdentityOidcAuth, object, UpdateIdentityOidcAuthDTO>({mutationFn: async ({identityId,+ templateId,accessTokenTTL,accessTokenMaxTTL,accessTokenNumUsesLimit,@@ -956,6 +957,7 @@ export const useUpdateIdentityOidcAuth = () => {} = await apiRequest.patch<{ identityOidcAuth: IdentityOidcAuth }>(`/api/v1/auth/oidc-auth/identities/${identityId}`,{+ templateId,oidcDiscoveryUrl,caCert,boundIssuer,@@ -997,6 +999,7 @@ export const useAddIdentityOidcAuth = () => {return useMutation<IdentityOidcAuth, object, AddIdentityOidcAuthDTO>({mutationFn: async ({identityId,+ templateId,oidcDiscoveryUrl,caCert,boundIssuer,@@ -1014,6 +1017,7 @@ export const useAddIdentityOidcAuth = () => {} = await apiRequest.post<{ identityOidcAuth: IdentityOidcAuth }>(`/api/v1/auth/oidc-auth/identities/${identityId}`,{+ templateId,oidcDiscoveryUrl,caCert,boundIssuer,diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.tsindex 516b6df8a5..ab66f7952f 100644--- a/frontend/src/hooks/api/identities/types.ts+++ b/frontend/src/hooks/api/identities/types.ts@@ -258,6 +258,7 @@ export type DeleteIdentityGcpAuthDTO = {export type IdentityOidcAuth = {identityId: string;+ templateId?: string | null;oidcDiscoveryUrl: string;caCert: string;boundIssuer: string;@@ -275,10 +276,11 @@ export type AddIdentityOidcAuthDTO = {organizationId?: string;projectId?: string;identityId: string;- oidcDiscoveryUrl: string;- caCert: string;- boundIssuer: string;- boundAudiences: string;+ templateId?: string;+ oidcDiscoveryUrl?: string;+ caCert?: string;+ boundIssuer?: string;+ boundAudiences?: string;boundClaims: Record<string, string>;claimMetadataMapping?: Record<string, string>;boundSubject: string;@@ -294,6 +296,7 @@ export type UpdateIdentityOidcAuthDTO = {organizationId?: string;projectId?: string;identityId: string;+ templateId?: string | null;oidcDiscoveryUrl?: string;caCert?: string;boundIssuer?: string;diff --git a/frontend/src/hooks/api/identityAuthTemplates/types.ts b/frontend/src/hooks/api/identityAuthTemplates/types.tsindex 9488130452..83cf9a951b 100644--- a/frontend/src/hooks/api/identityAuthTemplates/types.ts+++ b/frontend/src/hooks/api/identityAuthTemplates/types.ts@@ -2,7 +2,8 @@ import { IdentityKubernetesAuthTokenReviewMode } from "../identities/types";export enum MachineIdentityAuthMethod {LDAP = "ldap",- KUBERNETES = "kubernetes"+ KUBERNETES = "kubernetes",+ OIDC = "oidc"}export interface LdapTemplateFields {@@ -28,9 +29,17 @@ export interface KubernetesTemplateFields {hasTokenReviewerJwt?: boolean;}+export interface OidcTemplateFields {+ oidcDiscoveryUrl: string;+ boundIssuer: string;+ boundAudiences?: string;+ caCert?: string;+}+export type TemplateFieldsByMethod = {[MachineIdentityAuthMethod.LDAP]: LdapTemplateFields;[MachineIdentityAuthMethod.KUBERNETES]: KubernetesTemplateFields;+ [MachineIdentityAuthMethod.OIDC]: OidcTemplateFields;};export interface IdentityAuthTemplateForMethod<@@ -47,20 +56,24 @@ export interface IdentityAuthTemplateForMethod<export type IdentityAuthTemplate =| IdentityAuthTemplateForMethod<MachineIdentityAuthMethod.LDAP>- | IdentityAuthTemplateForMethod<MachineIdentityAuthMethod.KUBERNETES>;+ | IdentityAuthTemplateForMethod<MachineIdentityAuthMethod.KUBERNETES>+ | IdentityAuthTemplateForMethod<MachineIdentityAuthMethod.OIDC>;export interface CreateIdentityAuthTemplateDTO {organizationId: string;name: string;authMethod: MachineIdentityAuthMethod;- templateFields: LdapTemplateFields | KubernetesTemplateFields;+ templateFields: LdapTemplateFields | KubernetesTemplateFields | OidcTemplateFields;}export interface UpdateIdentityAuthTemplateDTO {templateId: string;organizationId: string;name?: string;- templateFields?: Partial<LdapTemplateFields> | Partial<KubernetesTemplateFields>;+ templateFields?:+ | Partial<LdapTemplateFields>+ | Partial<KubernetesTemplateFields>+ | Partial<OidcTemplateFields>;}export interface DeleteIdentityAuthTemplateDTO {diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsxindex 97fd5a8e37..25b00a2b04 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplateModal.tsx@@ -49,6 +49,7 @@ import {type KubernetesTemplateFields,type LdapTemplateFields,MachineIdentityAuthMethod,+ type OidcTemplateFields,useCreateIdentityAuthTemplate,useUpdateIdentityAuthTemplate} from "@app/hooks/api/identityAuthTemplates";@@ -71,6 +72,11 @@ export const templateAuthMethods = [label: "Kubernetes Auth",value: MachineIdentityAuthMethod.KUBERNETES,icon: getMethodIcon(IdentityAuthMethod.KUBERNETES_AUTH)+ },+ {+ label: "OIDC Auth",+ value: MachineIdentityAuthMethod.OIDC,+ icon: getMethodIcon(IdentityAuthMethod.OIDC_AUTH)}];@@ -99,9 +105,45 @@ const schema = zgatewayPoolId: z.string().optional().nullable(),caCert: z.string().optional(),verifyTlsCertificate: z.boolean().default(true),- allowedAudience: z.string().optional()+ allowedAudience: z.string().optional(),+ oidcDiscoveryUrl: z.string().optional(),+ boundIssuer: z.string().optional(),+ boundAudiences: z.string().optional()}).superRefine((data, ctx) => {+ if (data.method === MachineIdentityAuthMethod.OIDC) {+ if (!data.oidcDiscoveryUrl) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "OIDC discovery URL is required"+ });+ } else {+ if (!z.string().url().safeParse(data.oidcDiscoveryUrl).success) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "OIDC discovery URL must be a valid URL"+ });+ }+ if (data.oidcDiscoveryUrl.endsWith("/.well-known/openid-configuration")) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "Please remove /.well-known/openid-configuration."+ });+ }+ }+ if (!data.boundIssuer) {+ ctx.addIssue({+ path: ["boundIssuer"],+ code: z.ZodIssueCode.custom,+ message: "Issuer is required"+ });+ }+ return;+ }+if (data.method === MachineIdentityAuthMethod.LDAP) {if (!data.url) {ctx.addIssue({@@ -156,7 +198,10 @@ const emptyFormValues: FormData = {gatewayPoolId: null,caCert: "",verifyTlsCertificate: true,- allowedAudience: ""+ allowedAudience: "",+ oidcDiscoveryUrl: "",+ boundIssuer: "",+ boundAudiences: ""};type Props = {@@ -208,6 +253,18 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =verifyTlsCertificate: fields?.verifyTlsCertificate ?? Boolean(fields?.caCert),allowedAudience: fields?.allowedAudience || ""});+ } else if (template.authMethod === MachineIdentityAuthMethod.OIDC) {+ const fields = template.templateFields;+ reset({+ ...emptyFormValues,+ name: template.name || "",+ method: MachineIdentityAuthMethod.OIDC,+ isEdit: true,+ oidcDiscoveryUrl: fields?.oidcDiscoveryUrl || "",+ boundIssuer: fields?.boundIssuer || "",+ boundAudiences: fields?.boundAudiences || "",+ caCert: fields?.caCert || ""+ });} else {reset({...emptyFormValues,@@ -236,35 +293,45 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =const onFormSubmit = async (data: FormData) => {const isApiMode = data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api;- const templateFields: LdapTemplateFields | KubernetesTemplateFields =- data.method === MachineIdentityAuthMethod.LDAP- ? {- url: data.url || "",- bindDN: data.bindDN || "",- bindPass: data.bindPass || "",- searchBase: data.searchBase || "",- // send an explicit empty string so clearing the field persists through the- // merge-on-update semantics (an absent key means "keep the stored value")- ldapCaCertificate: data.ldapCaCertificate || ""- }- : ({- tokenReviewMode: data.tokenReviewMode,- kubernetesHost: isApiMode ? data.kubernetesHost || null : null,- caCert: isApiMode ? data.caCert || "" : "",- verifyTlsCertificate: isApiMode- ? Boolean(data.caCert) || data.verifyTlsCertificate- : false,- tokenReviewerJwt: isApiMode ? data.tokenReviewerJwt || "" : "",- gatewayId: data.gatewayPoolId ? null : data.gatewayId || null,- gatewayPoolId: data.gatewayPoolId || null,- allowedAudience: data.allowedAudience || ""- } satisfies KubernetesTemplateFields);+ let templateFields: LdapTemplateFields | KubernetesTemplateFields | OidcTemplateFields;+ if (data.method === MachineIdentityAuthMethod.LDAP) {+ templateFields = {+ url: data.url || "",+ bindDN: data.bindDN || "",+ bindPass: data.bindPass || "",+ searchBase: data.searchBase || "",+ // send an explicit empty string so clearing the field persists through the+ // merge-on-update semantics (an absent key means "keep the stored value")+ ldapCaCertificate: data.ldapCaCertificate || ""+ };+ } else if (data.method === MachineIdentityAuthMethod.OIDC) {+ templateFields = {+ oidcDiscoveryUrl: data.oidcDiscoveryUrl || "",+ boundIssuer: data.boundIssuer || "",+ boundAudiences: data.boundAudiences || "",+ caCert: data.caCert || ""+ } satisfies OidcTemplateFields;+ } else {+ templateFields = {+ tokenReviewMode: data.tokenReviewMode,+ kubernetesHost: isApiMode ? data.kubernetesHost || null : null,+ caCert: isApiMode ? data.caCert || "" : "",+ verifyTlsCertificate: isApiMode ? Boolean(data.caCert) || data.verifyTlsCertificate : false,+ tokenReviewerJwt: isApiMode ? data.tokenReviewerJwt || "" : "",+ gatewayId: data.gatewayPoolId ? null : data.gatewayId || null,+ gatewayPoolId: data.gatewayPoolId || null,+ allowedAudience: data.allowedAudience || ""+ } satisfies KubernetesTemplateFields;+ }if (isEdit && template) {// secrets are write-only, so an empty field on edit means "keep the stored value"// and the key must be omitted from the patch (an explicit "" would clear it and// propagate the cleared credential to every linked identity)- const patchFields: Partial<LdapTemplateFields> | Partial<KubernetesTemplateFields> = {+ const patchFields:+ | Partial<LdapTemplateFields>+ | Partial<KubernetesTemplateFields>+ | Partial<OidcTemplateFields> = {...templateFields};if (data.method === MachineIdentityAuthMethod.LDAP && !data.bindPass) {@@ -322,6 +389,9 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =| "kubernetesHost"| "tokenReviewerJwt"| "allowedAudience"+ | "oidcDiscoveryUrl"+ | "boundIssuer"+ | "boundAudiences">(id: string,label: string,@@ -730,6 +800,87 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =)}</>)}++ {selectedMethod === MachineIdentityAuthMethod.OIDC && (+ <>+ <Controller+ control={control}+ name="oidcDiscoveryUrl"+ render={({ field, fieldState: { error } }) =>+ renderField(+ "identity-auth-template-oidc-discovery-url",+ "OIDC Discovery URL",+ field,+ error,+ { placeholder: "https://token.actions.githubusercontent.com" }+ )+ }+ />++ <Controller+ control={control}+ name="boundIssuer"+ render={({ field, fieldState: { error } }) =>+ renderField("identity-auth-template-bound-issuer", "Issuer", field, error, {+ placeholder: "https://token.actions.githubusercontent.com"+ })+ }+ />++ <Controller+ control={control}+ name="boundAudiences"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="identity-auth-template-bound-audiences">+ Audiences (optional)+ </FieldLabel>+ <Input+ {...field}+ id="identity-auth-template-bound-audiences"+ placeholder="service1, service2"+ aria-invalid={Boolean(error)}+ aria-describedby="identity-auth-template-bound-audiences-description"+ />+ <p+ id="identity-auth-template-bound-audiences-description"+ className="text-xs text-muted"+ >+ A comma-separated list of values the token's aud claim must match.+ </p>+ <FieldError errors={[error]} />+ </Field>+ )}+ />++ <Controller+ control={control}+ name="caCert"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="identity-auth-template-oidc-ca-certificate">+ CA Certificate (optional)+ </FieldLabel>+ <TextArea+ {...field}+ id="identity-auth-template-oidc-ca-certificate"+ placeholder="-----BEGIN CERTIFICATE----- ..."+ aria-invalid={Boolean(error)}+ aria-describedby="identity-auth-template-oidc-ca-certificate-description"+ />+ <p+ id="identity-auth-template-oidc-ca-certificate-description"+ className="text-xs text-muted"+ >+ An optional PEM-encoded CA certificate used for secure communication with+ the identity provider endpoints.+ </p>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ </>+ )}</FieldGroup><SheetFooter className="border-t"><Buttondiff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplatesTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplatesTable.tsxindex d11b140db6..fa07c142b2 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplatesTable.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplatesTable.tsx@@ -45,6 +45,7 @@ import {import { usePagination, useResetPageHelper } from "@app/hooks";import { OrderByDirection } from "@app/hooks/api/generic/types";import {+ type IdentityAuthTemplate,MachineIdentityAuthMethod,TEMPLATE_UI_LABELS,useGetIdentityAuthTemplates@@ -58,6 +59,16 @@ enum TemplatesOrderBy {AuthMethod = "authMethod"}+const getTemplateEndpoint = (template: IdentityAuthTemplate) => {+ if (template.authMethod === MachineIdentityAuthMethod.KUBERNETES) {+ return template.templateFields.kubernetesHost || "Gateway";+ }+ if (template.authMethod === MachineIdentityAuthMethod.OIDC) {+ return template.templateFields.oidcDiscoveryUrl;+ }+ return template.templateFields.url;+};+type Props = {onEmptyStateChange?: (isEmpty: boolean) => void;handlePopUpOpen: (@@ -239,11 +250,7 @@ export const IdentityAuthTemplatesTable = ({ handlePopUpOpen, onEmptyStateChange{methodOption?.label ?? template.authMethod}</span></TableCell>- <TableCell isTruncatable>- {template.authMethod === MachineIdentityAuthMethod.KUBERNETES- ? template.templateFields.kubernetesHost || "Gateway"- : template.templateFields.url}- </TableCell>+ <TableCell isTruncatable>{getTemplateEndpoint(template)}</TableCell><TableCell variant="action"><DropdownMenu><DropdownMenuTrigger asChild>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 c121b5796a..91e4365b0b 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@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from "react";import { Controller, useFieldArray, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { useParams } from "@tanstack/react-router";-import { HelpCircleIcon, PlusIcon, XIcon } from "lucide-react";+import { HelpCircleIcon, InfoIcon, PlusIcon, XIcon } from "lucide-react";import { z } from "zod";import { createNotification } from "@app/components/notifications";@@ -13,6 +13,7 @@ import {FieldError,FieldGroup,FieldLabel,+ FilterableSelect,IconButton,Input,Tabs,@@ -24,7 +25,11 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";-import { useOrganization, useSubscription } from "@app/context";+import { useOrganization, useOrgPermission, useSubscription } from "@app/context";+import {+ OrgPermissionMachineIdentityAuthTemplateActions,+ OrgPermissionSubjects+} from "@app/context/OrgPermissionContext/types";import {accessTokenTtlSchema,DEFAULT_TRUSTED_IPS,@@ -35,6 +40,8 @@ import {import { useScopeVariant } from "@app/hooks";import { useAddIdentityOidcAuth, useUpdateIdentityOidcAuth } from "@app/hooks/api";import { useGetIdentityOidcAuth } from "@app/hooks/api/identities/queries";+import { MachineIdentityAuthMethod } from "@app/hooks/api/identityAuthTemplates";+import { useGetAvailableTemplates } from "@app/hooks/api/identityAuthTemplates/queries";import { UsePopUpState } from "@app/hooks/usePopUp";import { AccessTokenNumUsesLimitField } from "./shared/AccessTokenNumUsesLimitField";@@ -45,20 +52,15 @@ import { IDENTITY_AUTH_FORM_ID, IdentityFormTab } from "./types";const buildSchema = (maxAccessTokenTTL: number) =>z.object({+ scope: z.enum(["template", "custom"]),+ templateId: z.string().optional(),accessTokenTrustedIps: trustedIpsSchema,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."- ),+ oidcDiscoveryUrl: z.string().optional(),caCert: z.string().trim().default(""),- boundIssuer: z.string().min(1),+ boundIssuer: z.string().optional(),boundAudiences: z.string().optional().default(""),boundClaims: z.array(@@ -78,10 +80,69 @@ const buildSchema = (maxAccessTokenTTL: number) =>.default([]),boundSubject: z.string().optional().default("")})+ .superRefine((data, ctx) => {+ if (data.scope === "template") {+ if (!data.templateId) {+ ctx.addIssue({+ path: ["templateId"],+ code: z.ZodIssueCode.custom,+ message: "Template is required when using template scope"+ });+ }+ // the template only pins the issuer; a subject or claim binding is what scopes+ // this identity to specific workloads (mirrors the backend rule)+ const hasClaimBinding = data.boundClaims.some((claim) => claim.key.trim());+ if (!data.boundSubject && !hasClaimBinding) {+ ctx.addIssue({+ path: ["boundSubject"],+ code: z.ZodIssueCode.custom,+ message:+ "Set a subject or at least one claim binding to restrict which workloads can authenticate as this identity."+ });+ }+ return;+ }++ if (!data.oidcDiscoveryUrl) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "OIDC discovery URL is required"+ });+ } else {+ if (!z.string().url().safeParse(data.oidcDiscoveryUrl).success) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "OIDC discovery URL must be a valid URL"+ });+ }+ if (data.oidcDiscoveryUrl.endsWith("/.well-known/openid-configuration")) {+ ctx.addIssue({+ path: ["oidcDiscoveryUrl"],+ code: z.ZodIssueCode.custom,+ message: "Please remove /.well-known/openid-configuration."+ });+ }+ }+ if (!data.boundIssuer) {+ ctx.addIssue({+ path: ["boundIssuer"],+ code: z.ZodIssueCode.custom,+ message: "Issuer is required"+ });+ }+ }).superRefine(superRefineAccessTokenTtl);export type FormData = z.infer<ReturnType<typeof buildSchema>>;+type ConfigurationOption = {+ group: "Configuration" | "Templates";+ label: string;+ value: string;+};+type Props = {handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>,@@ -115,6 +176,17 @@ export const IdentityOidcAuthForm = ({const { mutateAsync: addMutateAsync } = useAddIdentityOidcAuth();const { mutateAsync: updateMutateAsync } = useUpdateIdentityOidcAuth();const [tabValue, setTabValue] = useState<IdentityFormTab>(IdentityFormTab.Configuration);+ const { permission } = useOrgPermission();++ const canAttachTemplates = permission.can(+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,+ OrgPermissionSubjects.MachineIdentityAuthTemplate+ );++ const { data: templates, isLoading: isTemplatesLoading } = useGetAvailableTemplates(+ MachineIdentityAuthMethod.OIDC,+ { enabled: canAttachTemplates && Boolean(subscription?.machineIdentityAuthTemplates) }+ );const { data } = useGetIdentityOidcAuth(identityId ?? "", {enabled: isUpdate@@ -126,10 +198,15 @@ export const IdentityOidcAuthForm = ({control,handleSubmit,reset,- formState: { isSubmitting }+ watch,+ setValue,+ clearErrors,+ formState: { errors, isSubmitting }} = useForm<FormData>({resolver,defaultValues: {+ scope: "custom",+ templateId: "",accessTokenTTL: "2592000",accessTokenMaxTTL: "2592000",accessTokenNumUsesLimit: "",@@ -138,6 +215,30 @@ export const IdentityOidcAuthForm = ({claimMetadataMapping: []}});++ const scope = watch("scope");+ const templateId = watch("templateId");++ const configurationOptions = useMemo<ConfigurationOption[]>(+ () => [+ {+ group: "Configuration",+ label: "Custom Configuration",+ value: "custom"+ },+ ...(templates ?? []).map((template) => ({+ group: "Templates" as const,+ label: template.name,+ value: template.id+ }))+ ],+ [templates]+ );++ const selectedConfiguration = configurationOptions.find(+ ({ value }) => value === (scope === "template" ? templateId : "custom")+ );+const {fields: boundClaimsFields,append: appendBoundClaimField,@@ -159,6 +260,8 @@ export const IdentityOidcAuthForm = ({useEffect(() => {if (data) {reset({+ scope: data.templateId ? "template" : "custom",+ templateId: data.templateId || "",oidcDiscoveryUrl: data.oidcDiscoveryUrl,caCert: data.caCert,boundIssuer: data.boundIssuer,@@ -183,6 +286,8 @@ export const IdentityOidcAuthForm = ({});} else {reset({+ scope: "custom",+ templateId: "",oidcDiscoveryUrl: "",caCert: "",boundIssuer: "",@@ -203,6 +308,8 @@ export const IdentityOidcAuthForm = ({}, [isSubmitting, onSubmittingChange]);const onFormSubmit = async ({+ scope: submissionScope,+ templateId: submissionTemplateId,accessTokenTrustedIps,accessTokenTTL,accessTokenMaxTTL,@@ -219,42 +326,48 @@ export const IdentityOidcAuthForm = ({return;}+ const basePayload = {+ identityId,+ ...(projectId ? { projectId } : { organizationId: orgId }),+ boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])),+ claimMetadataMapping: claimMetadataMapping+ ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value]))+ : undefined,+ boundSubject,+ accessTokenTTL: Number(accessTokenTTL),+ accessTokenMaxTTL: Number(accessTokenMaxTTL),+ accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit || "0"),+ accessTokenTrustedIps+ };++ // the identity provider settings are template-managed while linked, so the template+ // payload must not carry them (the API rejects them alongside a templateId)if (data) {- await updateMutateAsync({- identityId,- ...(projectId ? { projectId } : { organizationId: orgId }),- oidcDiscoveryUrl,- caCert,- boundIssuer,- boundAudiences,- boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])),- claimMetadataMapping: claimMetadataMapping- ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value]))- : undefined,- boundSubject,- accessTokenTTL: Number(accessTokenTTL),- accessTokenMaxTTL: Number(accessTokenMaxTTL),- accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit || "0"),- accessTokenTrustedIps- });+ await updateMutateAsync(+ submissionScope === "template"+ ? { ...basePayload, templateId: submissionTemplateId }+ : {+ ...basePayload,+ // unlink an existing template so the custom values are accepted+ ...(data.templateId ? { templateId: null } : {}),+ oidcDiscoveryUrl,+ caCert,+ boundIssuer,+ boundAudiences+ }+ );} else {- await addMutateAsync({- identityId,- oidcDiscoveryUrl,- caCert,- boundIssuer,- boundAudiences,- boundClaims: Object.fromEntries(boundClaims.map((entry) => [entry.key, entry.value])),- claimMetadataMapping: claimMetadataMapping- ? Object.fromEntries(claimMetadataMapping.map((entry) => [entry.key, entry.value]))- : undefined,- boundSubject,- ...(projectId ? { projectId } : { organizationId: orgId }),- accessTokenTTL: Number(accessTokenTTL),- accessTokenMaxTTL: Number(accessTokenMaxTTL),- accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit || "0"),- accessTokenTrustedIps- });+ await addMutateAsync(+ submissionScope === "template"+ ? { ...basePayload, templateId: submissionTemplateId }+ : {+ ...basePayload,+ oidcDiscoveryUrl,+ caCert,+ boundIssuer,+ boundAudiences+ }+ );}handlePopUpToggle("identityAuthMethod", false);@@ -266,6 +379,10 @@ export const IdentityOidcAuthForm = ({reset();};+ const templateTooltipText =+ scope === "template" ? "This field cannot be modified when using a template" : null;+ const templateDisabledClass = scope === "template" ? "opacity-55" : "";+return (<formid={IDENTITY_AUTH_FORM_ID}@@ -286,17 +403,82 @@ export const IdentityOidcAuthForm = ({</TabsList><TabsContent value={IdentityFormTab.Configuration}><FieldGroup>+ {canAttachTemplates && (+ <Controller+ control={control}+ name="scope"+ render={({ field: { onChange }, fieldState: { error } }) => (+ <Field>+ <FieldLabel htmlFor="oidc-configuration">Configuration</FieldLabel>+ <FilterableSelect<ConfigurationOption>+ inputId="oidc-configuration"+ value={selectedConfiguration}+ options={configurationOptions}+ groupBy="group"+ getOptionLabel={(option) => option.label}+ getOptionValue={(option) => option.value}+ placeholder="Select or search configurations..."+ isLoading={isTemplatesLoading}+ isError={Boolean(error || errors.templateId)}+ onChange={(option) => {+ const selectedOption = option as ConfigurationOption | null;+ if (!selectedOption) return;++ if (selectedOption.value === "custom") {+ onChange("custom");+ setValue("templateId", "");+ clearErrors("templateId");+ setValue("oidcDiscoveryUrl", data?.oidcDiscoveryUrl || "");+ setValue("boundIssuer", data?.boundIssuer || "");+ setValue("boundAudiences", data?.boundAudiences || "");+ setValue("caCert", data?.caCert || "");+ return;+ }++ const template = templates?.find(({ id }) => id === selectedOption.value);+ if (!template) return;++ onChange("template");+ setValue("templateId", template.id);+ // template-managed fields become disabled, so any validation errors+ // pinned to them are no longer actionable+ clearErrors(["templateId", "oidcDiscoveryUrl", "boundIssuer", "caCert"]);+ setValue("oidcDiscoveryUrl", template.templateFields.oidcDiscoveryUrl);+ setValue("boundIssuer", template.templateFields.boundIssuer);+ setValue("boundAudiences", template.templateFields.boundAudiences ?? "");+ setValue("caCert", template.templateFields.caCert ?? "");+ }}+ />+ <FieldError>{error?.message || errors.templateId?.message}</FieldError>+ </Field>+ )}+ />+ )}<Controllercontrol={control}name="oidcDiscoveryUrl"render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel htmlFor="oidcDiscoveryUrl">OIDC Discovery URL</FieldLabel>+ <Field className={templateDisabledClass}>+ <FieldLabel+ htmlFor="oidcDiscoveryUrl"+ className="inline-flex items-center gap-1.5"+ >+ OIDC Discovery URL+ {templateTooltipText && (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent className="max-w-md">{templateTooltipText}</TooltipContent>+ </Tooltip>+ )}+ </FieldLabel><Input{...field}id="oidcDiscoveryUrl"placeholder="https://token.actions.githubusercontent.com"type="text"+ disabled={scope === "template"}isError={Boolean(error)}/><FieldError>{error?.message}</FieldError>@@ -307,13 +489,24 @@ export const IdentityOidcAuthForm = ({control={control}name="boundIssuer"render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel htmlFor="boundIssuer">Issuer</FieldLabel>+ <Field className={templateDisabledClass}>+ <FieldLabel htmlFor="boundIssuer" className="inline-flex items-center gap-1.5">+ Issuer+ {templateTooltipText && (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent className="max-w-md">{templateTooltipText}</TooltipContent>+ </Tooltip>+ )}+ </FieldLabel><Input{...field}id="boundIssuer"type="text"placeholder="https://token.actions.githubusercontent.com"+ disabled={scope === "template"}isError={Boolean(error)}/><FieldError>{error?.message}</FieldError>@@ -345,7 +538,7 @@ export const IdentityOidcAuthForm = ({control={control}name="boundAudiences"render={({ field, fieldState: { error } }) => (- <Field>+ <Field className={templateDisabledClass}><FieldLabel htmlFor="boundAudiences" className="inline-flex items-center gap-1.5">Audiences (optional)<Tooltip>@@ -353,7 +546,7 @@ export const IdentityOidcAuthForm = ({<HelpCircleIcon className="size-3.5 text-muted" /></TooltipTrigger><TooltipContent className="max-w-md">- <BashGlobPatternTooltip />+ {templateTooltipText || <BashGlobPatternTooltip />}</TooltipContent></Tooltip></FieldLabel>@@ -362,6 +555,7 @@ export const IdentityOidcAuthForm = ({id="boundAudiences"type="text"placeholder="service1, service2"+ disabled={scope === "template"}isError={Boolean(error)}/><FieldError>{error?.message}</FieldError>@@ -463,12 +657,23 @@ export const IdentityOidcAuthForm = ({control={control}name="caCert"render={({ field, fieldState: { error } }) => (- <Field>- <FieldLabel htmlFor="caCert">CA Certificate (optional)</FieldLabel>+ <Field className={templateDisabledClass}>+ <FieldLabel htmlFor="caCert" className="inline-flex items-center gap-1.5">+ CA Certificate (optional)+ {templateTooltipText && (+ <Tooltip>+ <TooltipTrigger asChild>+ <InfoIcon className="size-3.5 text-muted" />+ </TooltipTrigger>+ <TooltipContent className="max-w-md">{templateTooltipText}</TooltipContent>+ </Tooltip>+ )}+ </FieldLabel><TextArea{...field}id="caCert"placeholder="-----BEGIN CERTIFICATE----- ..."+ disabled={scope === "template"}isError={Boolean(error)}/><FieldError>{error?.message}</FieldError>diff --git a/frontend/src/views/IdentityAuthMethods/content/IdentityOidcAuthContent.tsx b/frontend/src/views/IdentityAuthMethods/content/IdentityOidcAuthContent.tsxindex 628e54bdf6..abeb194a80 100644--- a/frontend/src/views/IdentityAuthMethods/content/IdentityOidcAuthContent.tsx+++ b/frontend/src/views/IdentityAuthMethods/content/IdentityOidcAuthContent.tsx@@ -12,14 +12,36 @@ import {TooltipContent,TooltipTrigger} from "@app/components/v3";+import { useOrgPermission, useSubscription } from "@app/context";+import {+ OrgPermissionMachineIdentityAuthTemplateActions,+ OrgPermissionSubjects+} from "@app/context/OrgPermissionContext/types";import { useGetIdentityOidcAuth } from "@app/hooks/api";+import { MachineIdentityAuthMethod } from "@app/hooks/api/identityAuthTemplates";+import { useGetAvailableTemplates } from "@app/hooks/api/identityAuthTemplates/queries";import { IdentityAuthAccessTokenFields, IdentityAuthFieldDisplay } from "../helpers";import { ViewAuthMethodProps } from "../types";export const IdentityOidcAuthContent = ({ identityId }: ViewAuthMethodProps) => {+ const { subscription } = useSubscription();+ const { permission } = useOrgPermission();++ const canAttachTemplates = permission.can(+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,+ OrgPermissionSubjects.MachineIdentityAuthTemplate+ );+const { data, isPending } = useGetIdentityOidcAuth(identityId);+ const { data: templates } = useGetAvailableTemplates(MachineIdentityAuthMethod.OIDC, {+ enabled:+ canAttachTemplates &&+ Boolean(subscription?.machineIdentityAuthTemplates) &&+ Boolean(data?.templateId)+ });+if (isPending) {return <PageLoader />;}@@ -37,8 +59,16 @@ export const IdentityOidcAuthContent = ({ identityId }: ViewAuthMethodProps) =>);}+ const linkedTemplateName = templates?.find((template) => template.id === data.templateId)?.name;+ const configurationLabel = data.templateId+ ? (linkedTemplateName ?? "Linked template")+ : "Custom Configuration";+return (<DetailGroup className="grid grid-cols-2 gap-x-6 gap-y-5">+ <IdentityAuthFieldDisplay className="col-span-2" label="Configuration">+ {configurationLabel}+ </IdentityAuthFieldDisplay><IdentityAuthAccessTokenFieldsaccessTokenTTL={data.accessTokenTTL}accessTokenMaxTTL={data.accessTokenMaxTTL}