Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: add kubernetes MI auth template support

Scott Wilsonec4c726767ec
diff --git a/backend/src/db/migrations/20260818000000_identity-kubernetes-auth-template.ts b/backend/src/db/migrations/20260818000000_identity-kubernetes-auth-template.ts
new file mode 100644
index 0000000000..a1cfe7590c
--- /dev/null
+++ b/backend/src/db/migrations/20260818000000_identity-kubernetes-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.IdentityKubernetesAuth, "templateId"))) {
+ await knex.schema.alterTable(TableName.IdentityKubernetesAuth, (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.IdentityKubernetesAuth, "templateId")) {
+ await knex.schema.alterTable(TableName.IdentityKubernetesAuth, (t) => {
+ t.dropForeign(["templateId"]);
+ t.dropColumn("templateId");
+ });
+ }
+}
diff --git a/backend/src/db/migrations/20260818000001_identity-ldap-auth-template-index.ts b/backend/src/db/migrations/20260818000001_identity-ldap-auth-template-index.ts
new file mode 100644
index 0000000000..a887a50b56
--- /dev/null
+++ b/backend/src/db/migrations/20260818000001_identity-ldap-auth-template-index.ts
@@ -0,0 +1,16 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+// the ldap templateId FK shipped without an index; template update/delete fan-outs and the
+// FK's RI trigger both filter identity_ldap_auths by it. Separate from the kubernetes
+// template migration so rolling that feature back cannot drop an index LDAP depends on.
+export async function up(knex: Knex): Promise<void> {
+ await knex.raw(
+ `CREATE INDEX IF NOT EXISTS "identity_ldap_auths_templateid_index" ON ${TableName.IdentityLdapAuth} ("templateId")`
+ );
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX IF EXISTS "identity_ldap_auths_templateid_index"`);
+}
diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yaml
index 34c74cd208..ad0e08f9e6 100644
--- a/backend/src/db/sanitized-schema.yaml
+++ b/backend/src/db/sanitized-schema.yaml
@@ -332,6 +332,7 @@ tables:
- accessTokenPeriod
- tokenReviewMode
- gatewayV2Id
+ - templateId
- name: identity_ldap_auths
source: public.identity_ldap_auths
diff --git a/backend/src/db/schemas/identity-kubernetes-auths.ts b/backend/src/db/schemas/identity-kubernetes-auths.ts
index e03d8e6253..8641e99205 100644
--- a/backend/src/db/schemas/identity-kubernetes-auths.ts
+++ b/backend/src/db/schemas/identity-kubernetes-auths.ts
@@ -35,7 +35,8 @@ export const IdentityKubernetesAuthsSchema = z.object({
tokenReviewMode: z.string().default("api"),
gatewayV2Id: z.string().uuid().nullable().optional(),
gatewayPoolId: z.string().uuid().nullable().optional(),
- verifyTlsCertificate: z.boolean().default(false)
+ verifyTlsCertificate: z.boolean().default(false),
+ templateId: z.string().uuid().nullable().optional()
});
export type TIdentityKubernetesAuths = z.infer<typeof IdentityKubernetesAuthsSchema>;
diff --git a/backend/src/ee/routes/v1/identity-template-router.ts b/backend/src/ee/routes/v1/identity-template-router.ts
index b300696439..2ded410fe0 100644
--- a/backend/src/ee/routes/v1/identity-template-router.ts
+++ b/backend/src/ee/routes/v1/identity-template-router.ts
@@ -7,17 +7,24 @@ import {
TEMPLATE_SUCCESS_MESSAGES,
TEMPLATE_VALIDATION_MESSAGES
} from "@app/ee/services/identity-auth-template/identity-auth-template-enums";
+import {
+ kubernetesTemplateFieldsBaseSchema,
+ kubernetesTemplateFieldsCreateSchema,
+ ldapTemplateFieldsSchema
+} 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";
import { AuthMode } from "@app/services/auth/auth-type";
-const ldapTemplateFieldsSchema = z.object({
- url: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.URL_REQUIRED),
- bindDN: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.BIND_DN_REQUIRED),
- bindPass: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.BIND_PASSWORD_REQUIRED),
- searchBase: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.SEARCH_BASE_REQUIRED),
- ldapCaCertificate: z.string().trim().optional()
-});
+const templateNameSchema = z
+ .string()
+ .trim()
+ .min(1, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_NAME_REQUIRED)
+ .max(64, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_NAME_MAX_LENGTH);
+
+// template credential fields (LDAP bindPass, Kubernetes tokenReviewerJwt) are stripped
+// server-side and never appear in responses
+const templateFieldsResponseSchema = z.record(z.string(), z.unknown());
export const registerIdentityTemplateRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -35,15 +42,18 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)
bearerAuth: []
}
],
- body: z.object({
- name: z
- .string()
- .trim()
- .min(1, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_NAME_REQUIRED)
- .max(64, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_NAME_MAX_LENGTH),
- authMethod: z.nativeEnum(IdentityAuthTemplateMethod),
- templateFields: ldapTemplateFieldsSchema
- }),
+ body: z.discriminatedUnion("authMethod", [
+ z.object({
+ name: templateNameSchema,
+ authMethod: z.literal(IdentityAuthTemplateMethod.LDAP),
+ templateFields: ldapTemplateFieldsSchema
+ }),
+ z.object({
+ name: templateNameSchema,
+ authMethod: z.literal(IdentityAuthTemplateMethod.KUBERNETES),
+ templateFields: kubernetesTemplateFieldsCreateSchema
+ })
+ ]),
response: {
200: IdentityAuthTemplatesSchema.extend({
templateFields: z.record(z.string(), z.unknown())
@@ -96,13 +106,12 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)
templateId: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_ID_REQUIRED)
}),
body: z.object({
- name: z
- .string()
- .trim()
- .min(1, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_NAME_REQUIRED)
- .max(64, TEMPLATE_VALIDATION_MESSAGES.TEMPLATE_NAME_MAX_LENGTH)
- .optional(),
- templateFields: ldapTemplateFieldsSchema.partial().optional()
+ name: templateNameSchema.optional(),
+ // strict partials so the union can discriminate by field names; the service
+ // validates the patch against the template's actual auth method
+ templateFields: z
+ .union([ldapTemplateFieldsSchema.partial().strict(), kubernetesTemplateFieldsBaseSchema.partial().strict()])
+ .optional()
}),
response: {
200: IdentityAuthTemplatesSchema.extend({
@@ -206,7 +215,7 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)
}),
response: {
200: IdentityAuthTemplatesSchema.extend({
- templateFields: ldapTemplateFieldsSchema
+ templateFields: templateFieldsResponseSchema
})
}
},
@@ -246,7 +255,7 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)
response: {
200: z.object({
templates: IdentityAuthTemplatesSchema.extend({
- templateFields: ldapTemplateFieldsSchema
+ templateFields: templateFieldsResponseSchema
}).array(),
totalCount: z.number()
})
@@ -287,7 +296,7 @@ export const registerIdentityTemplateRouter = async (server: FastifyZodProvider)
}),
response: {
200: IdentityAuthTemplatesSchema.extend({
- templateFields: ldapTemplateFieldsSchema
+ templateFields: templateFieldsResponseSchema
}).array()
}
},
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 0c3209a863..7a0655b6ba 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -1590,6 +1590,7 @@ interface AddIdentityKubernetesAuthEvent {
type: EventType.ADD_IDENTITY_KUBERNETES_AUTH;
metadata: {
identityId: string;
+ templateId?: string | null;
kubernetesHost: string;
allowedNamespaces: string;
allowedNames: string;
@@ -1618,6 +1619,7 @@ interface UpdateIdentityKubernetesAuthEvent {
accessTokenMaxTTL?: number;
accessTokenNumUsesLimit?: number;
accessTokenTrustedIps?: Array<TIdentityTrustedIp>;
+ templateId?: string | null;
};
}
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.ts
index 736f0f0333..0e27f20af5 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
@@ -3,6 +3,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
+import { BadRequestError } from "@app/lib/errors";
import { buildFindFilter, ormify } from "@app/lib/knex";
import { IdentityAuthTemplateMethod } from "./identity-auth-template-enums";
@@ -62,8 +63,20 @@ export const identityAuthTemplateDALFactory = (db: TDbClient) => {
);
const docs = await query;
return docs;
+ case IdentityAuthTemplateMethod.KUBERNETES:
+ const kubernetesQuery = (tx || db.replicaNode())(TableName.IdentityKubernetesAuth)
+ .join(TableName.Identity, `${TableName.IdentityKubernetesAuth}.identityId`, `${TableName.Identity}.id`)
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ .where(buildFindFilter({ templateId }, TableName.IdentityKubernetesAuth))
+ .select(
+ db.ref("identityId").withSchema(TableName.IdentityKubernetesAuth),
+ db.ref("name").withSchema(TableName.Identity).as("identityName")
+ );
+ const kubernetesDocs = await kubernetesQuery;
+ return kubernetesDocs;
default:
- return [];
+ // fail loudly so a future auth method cannot silently report zero usages
+ throw 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.ts
index c5b47b1581..3ef21fb1f3 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,5 +1,6 @@
export enum IdentityAuthTemplateMethod {
- LDAP = "ldap"
+ LDAP = "ldap",
+ KUBERNETES = "kubernetes"
}
export const TEMPLATE_VALIDATION_MESSAGES = {
@@ -12,6 +13,15 @@ export const TEMPLATE_VALIDATION_MESSAGES = {
BIND_DN_REQUIRED: "Bind DN is required",
BIND_PASSWORD_REQUIRED: "Bind password is required",
SEARCH_BASE_REQUIRED: "Search base is required"
+ },
+ KUBERNETES: {
+ HOST_REQUIRED: "When token review mode is set to API, a Kubernetes host must be provided",
+ GATEWAY_REQUIRED: "When token review mode is set to Gateway, a gateway or gateway pool must be selected",
+ GATEWAY_CONFLICT: "Cannot specify both a gateway and a gateway pool",
+ CA_CERT_REQUIRED:
+ "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."
}
} as const;
@@ -20,3 +30,10 @@ export const TEMPLATE_SUCCESS_MESSAGES = {
UPDATED: "Template updated successfully",
DELETED: "Template deleted successfully"
} as const;
+
+// credentials stored inside templateFields that must never leave the backend; every
+// template read path strips them, and the edit UI treats them as write-only
+export const TEMPLATE_SECRET_FIELDS_BY_METHOD: Record<IdentityAuthTemplateMethod, readonly string[]> = {
+ [IdentityAuthTemplateMethod.LDAP]: ["bindPass"],
+ [IdentityAuthTemplateMethod.KUBERNETES]: ["tokenReviewerJwt"]
+};
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.ts
new file mode 100644
index 0000000000..203b26d2f0
--- /dev/null
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-schemas.ts
@@ -0,0 +1,68 @@
+import { z } from "zod";
+
+import { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
+import {
+ kubernetesHostSchema,
+ superRefineKubernetesConnectionFields
+} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-validators";
+
+import { TEMPLATE_VALIDATION_MESSAGES } from "./identity-auth-template-enums";
+
+export const ldapTemplateFieldsSchema = z.object({
+ url: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.URL_REQUIRED),
+ bindDN: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.BIND_DN_REQUIRED),
+ bindPass: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.BIND_PASSWORD_REQUIRED),
+ searchBase: z.string().min(1, TEMPLATE_VALIDATION_MESSAGES.LDAP.SEARCH_BASE_REQUIRED),
+ ldapCaCertificate: z.string().trim().optional()
+});
+
+export const kubernetesTemplateFieldsBaseSchema = z.object({
+ tokenReviewMode: z
+ .nativeEnum(IdentityKubernetesAuthTokenReviewMode)
+ .default(IdentityKubernetesAuthTokenReviewMode.Api)
+ .describe("The mode to use for token review. Must be one of: 'api', 'gateway'"),
+ kubernetesHost: kubernetesHostSchema
+ .nullish()
+ .describe("The host string, host:port pair, or URL to the base of the Kubernetes API server"),
+ caCert: z
+ .string()
+ .trim()
+ .max(102400)
+ .optional()
+ .describe("The PEM-encoded CA certificate used to validate the Kubernetes API server's TLS certificate"),
+ verifyTlsCertificate: z
+ .boolean()
+ .optional()
+ .describe("Whether to verify the Kubernetes API server's TLS certificate against the configured CA certificate"),
+ tokenReviewerJwt: z
+ .string()
+ .trim()
+ .max(65536)
+ .optional()
+ .describe("Optional JWT token for accessing the Kubernetes TokenReview API"),
+ gatewayId: z
+ .string()
+ .uuid()
+ .nullish()
+ .describe("The ID of the gateway to use when performing Kubernetes API requests"),
+ gatewayPoolId: z
+ .string()
+ .uuid()
+ .nullish()
+ .describe("The ID of the gateway pool to use when performing Kubernetes API requests"),
+ allowedAudience: z
+ .string()
+ .trim()
+ .max(1000)
+ .default("")
+ .describe("The optional audience claim that service account JWT tokens must have to authenticate with Infisical")
+});
+
+export const kubernetesTemplateFieldsCreateSchema = kubernetesTemplateFieldsBaseSchema.superRefine(
+ superRefineKubernetesConnectionFields
+);
+
+export const templateFieldPatchKeysByMethod = {
+ ldap: Object.keys(ldapTemplateFieldsSchema.shape),
+ kubernetes: Object.keys(kubernetesTemplateFieldsBaseSchema.shape)
+} as const;
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.ts
index 10aa3b190f..e44e80dc00 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,27 +1,37 @@
import { ForbiddenError } from "@casl/ability";
-import { OrganizationActionScope } from "@app/db/schemas";
+import { OrganizationActionScope, TIdentityKubernetesAuthsUpdate } from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
+import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
+import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
+ OrgPermissionGatewayActions,
+ OrgPermissionGatewayPoolActions,
OrgPermissionMachineIdentityAuthTemplateActions,
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { chunkArray } from "@app/lib/fn";
import { TOrgPermission } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
+import { TIdentityKubernetesAuthDALFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-dal";
+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 { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TIdentityAuthTemplateDALFactory } from "./identity-auth-template-dal";
-import { IdentityAuthTemplateMethod } from "./identity-auth-template-enums";
+import { IdentityAuthTemplateMethod, TEMPLATE_SECRET_FIELDS_BY_METHOD } from "./identity-auth-template-enums";
+import { templateFieldPatchKeysByMethod } from "./identity-auth-template-schemas";
import {
TDeleteIdentityAuthTemplateDTO,
TFindTemplateUsagesDTO,
TGetIdentityAuthTemplateDTO,
TGetTemplatesByAuthMethodDTO,
+ TKubernetesTemplateFields,
TLdapTemplateFields,
TListIdentityAuthTemplatesDTO,
TUnlinkTemplateUsageDTO
@@ -29,7 +39,11 @@ import {
type TIdentityAuthTemplateServiceFactoryDep = {
identityAuthTemplateDAL: TIdentityAuthTemplateDALFactory;
- identityLdapAuthDAL: TIdentityLdapAuthDALFactory;
+ identityLdapAuthDAL: Pick<TIdentityLdapAuthDALFactory, "updateByTemplateId">;
+ identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "updateByTemplateId">;
+ gatewayDAL: Pick<TGatewayDALFactory, "find">;
+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
+ gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "encryptWithInputKey" | "decryptWithInputKey">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
@@ -38,9 +52,15 @@ type TIdentityAuthTemplateServiceFactoryDep = {
export type TIdentityAuthTemplateServiceFactory = ReturnType<typeof identityAuthTemplateServiceFactory>;
+const AUDIT_FANOUT_CHUNK_SIZE = 20;
+
export const identityAuthTemplateServiceFactory = ({
identityAuthTemplateDAL,
identityLdapAuthDAL,
+ identityKubernetesAuthDAL,
+ gatewayDAL,
+ gatewayV2DAL,
+ gatewayPoolDAL,
permissionService,
kmsService,
licenseService,
@@ -54,7 +74,138 @@ export const identityAuthTemplateServiceFactory = ({
message:
"Failed to use identity auth template due to plan restriction. Upgrade plan to access machine identity auth templates."
});
+ return plan;
+ };
+
+ // template credentials are write-only: every read path strips them so they never
+ // reach the client (the edit UI keeps a stored secret by omitting the field)
+ const $redactTemplateSecrets = (authMethod: string, fields: Record<string, unknown>) => {
+ const secretFields = TEMPLATE_SECRET_FIELDS_BY_METHOD[authMethod as IdentityAuthTemplateMethod] ?? [];
+ const redacted = { ...fields };
+ secretFields.forEach((key) => {
+ delete redacted[key];
+ });
+ return redacted;
+ };
+
+ // 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 $auditTemplatePropagation = async ({
+ identityIds,
+ authMethod,
+ templateId,
+ orgId
+ }: {
+ identityIds: string[];
+ authMethod: string;
+ templateId: string;
+ orgId: string;
+ }) => {
+ for (const batch of chunkArray(identityIds, AUDIT_FANOUT_CHUNK_SIZE)) {
+ // eslint-disable-next-line no-await-in-loop
+ await Promise.all(
+ batch.map((identityId) =>
+ auditLogService.createAuditLog({
+ actor: {
+ type: ActorType.PLATFORM,
+ metadata: {}
+ },
+ orgId,
+ event:
+ authMethod === IdentityAuthTemplateMethod.LDAP
+ ? { type: EventType.UPDATE_IDENTITY_LDAP_AUTH, metadata: { identityId, templateId } }
+ : { type: EventType.UPDATE_IDENTITY_KUBENETES_AUTH, metadata: { identityId, templateId } }
+ })
+ )
+ );
+ }
+ };
+
+ const $validateKubernetesTemplateFields = (fields: TKubernetesTemplateFields) => {
+ const issues = validateKubernetesConnectionFields(fields);
+ if (issues.length > 0) {
+ throw new BadRequestError({ message: issues[0].message });
+ }
};
+
+ // mirrors the checks the identity k8s auth attach flow runs, so a template cannot smuggle
+ // in a gateway its author could not attach directly
+ const $authorizeKubernetesTemplateGateway = ({
+ gatewayId,
+ gatewayPoolId,
+ plan,
+ permission
+ }: {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ plan: Awaited<ReturnType<TLicenseServiceFactory["getPlan"]>>;
+ permission: Awaited<ReturnType<TPermissionServiceFactory["getOrgPermission"]>>["permission"];
+ }) => {
+ if (gatewayId) {
+ if (!plan.gateway) {
+ throw new BadRequestError({
+ message:
+ "Your current plan does not support gateway usage with identity k8s auth. Please upgrade your plan or contact Infisical Sales for assistance."
+ });
+ }
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionGatewayActions.AttachGateways,
+ OrgPermissionSubjects.Gateway
+ );
+ }
+ if (gatewayPoolId) {
+ if (!plan.gatewayPool) {
+ throw new BadRequestError({
+ message: "Your current plan does not support gateway pools. Please upgrade to an Enterprise plan."
+ });
+ }
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionGatewayPoolActions.AttachGatewayPools,
+ OrgPermissionSubjects.GatewayPool
+ );
+ }
+ };
+
+ // resolves the template's user-facing gatewayId onto the v1/v2 column split used by
+ // identity_kubernetes_auths; only called when the caller is setting a gateway, so a
+ // stale reference inside the encrypted blob cannot block unrelated template edits
+ const $resolveKubernetesTemplateGateway = async ({
+ gatewayId,
+ gatewayPoolId,
+ orgId
+ }: {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ orgId: string;
+ }) => {
+ let resolvedGatewayId: string | null = null;
+ let resolvedGatewayV2Id: string | null = null;
+ if (gatewayId && !gatewayPoolId) {
+ const [[gateway], [gatewayV2]] = await Promise.all([
+ gatewayDAL.find({ id: gatewayId, orgId }),
+ gatewayV2DAL.find({ id: gatewayId, orgId })
+ ]);
+ if (gateway) {
+ resolvedGatewayId = gatewayId;
+ } else if (gatewayV2) {
+ resolvedGatewayV2Id = gatewayId;
+ } else {
+ throw new BadRequestError({
+ message: `Gateway with ID '${gatewayId}' was not found in this organization. Select an existing gateway for the template.`
+ });
+ }
+ }
+ if (gatewayPoolId) {
+ const pool = await gatewayPoolDAL.findById(gatewayPoolId);
+ if (!pool || pool.orgId !== orgId) {
+ throw new BadRequestError({
+ message: `Gateway pool with ID '${gatewayPoolId}' was not found in this organization. Select an existing gateway pool for the template.`
+ });
+ }
+ }
+ return { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId: gatewayPoolId ?? null };
+ };
+
const createTemplate = async ({
name,
authMethod,
@@ -68,7 +219,7 @@ export const identityAuthTemplateServiceFactory = ({
authMethod: string;
templateFields: Record<string, unknown>;
} & Omit<TOrgPermission, "orgId">) => {
- await $checkPlan(actorOrgId);
+ const plan = await $checkPlan(actorOrgId);
const { permission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
@@ -82,6 +233,30 @@ export const identityAuthTemplateServiceFactory = ({
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
+ let fieldsToPersist: Record<string, unknown> = templateFields;
+ if (authMethod === IdentityAuthTemplateMethod.KUBERNETES) {
+ const kubernetesFields = templateFields as TKubernetesTemplateFields;
+ const normalizedFields: TKubernetesTemplateFields = {
+ ...kubernetesFields,
+ verifyTlsCertificate: kubernetesFields.verifyTlsCertificate ?? Boolean(kubernetesFields.caCert?.length)
+ };
+ $validateKubernetesTemplateFields(normalizedFields);
+ if (normalizedFields.gatewayId || normalizedFields.gatewayPoolId) {
+ $authorizeKubernetesTemplateGateway({
+ gatewayId: normalizedFields.gatewayId,
+ gatewayPoolId: normalizedFields.gatewayPoolId,
+ plan,
+ permission
+ });
+ await $resolveKubernetesTemplateGateway({
+ gatewayId: normalizedFields.gatewayId,
+ gatewayPoolId: normalizedFields.gatewayPoolId,
+ orgId: actorOrgId
+ });
+ }
+ fieldsToPersist = normalizedFields;
+ }
+
const { encryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: actorOrgId
@@ -89,11 +264,11 @@ export const identityAuthTemplateServiceFactory = ({
const template = await identityAuthTemplateDAL.create({
name,
authMethod,
- templateFields: encryptor({ plainText: Buffer.from(JSON.stringify(templateFields)) }).cipherTextBlob,
+ templateFields: encryptor({ plainText: Buffer.from(JSON.stringify(fieldsToPersist)) }).cipherTextBlob,
orgId: actorOrgId
});
- return { ...template, templateFields };
+ return { ...template, templateFields: $redactTemplateSecrets(authMethod, fieldsToPersist) };
};
const updateTemplate = async ({
@@ -109,7 +284,7 @@ export const identityAuthTemplateServiceFactory = ({
name?: string;
templateFields?: Record<string, unknown>;
} & Omit<TOrgPermission, "orgId">) => {
- await $checkPlan(actorOrgId);
+ const plan = await $checkPlan(actorOrgId);
const template = await identityAuthTemplateDAL.findByIdAndOrgId(templateId, actorOrgId);
if (!template) {
throw new NotFoundError({ message: "Template not found" });
@@ -128,37 +303,93 @@ export const identityAuthTemplateServiceFactory = ({
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: template.orgId
});
- let finalTemplateFields: Record<string, unknown> = {};
+ const fieldPatch = templateFields && Object.keys(templateFields).length > 0 ? templateFields : undefined;
- const updatedTemplate = await identityAuthTemplateDAL.transaction(async (tx) => {
+ if (fieldPatch) {
+ const allowedPatchKeys: readonly string[] =
+ templateFieldPatchKeysByMethod[template.authMethod as IdentityAuthTemplateMethod] ?? [];
+ const invalidKeys = Object.keys(fieldPatch).filter((key) => !allowedPatchKeys.includes(key));
+ if (invalidKeys.length > 0) {
+ throw new BadRequestError({
+ message: `Template fields [${invalidKeys.join(", ")}] are not valid for a '${template.authMethod}' auth template`
+ });
+ }
+ }
+
+ const currentTemplateFields = JSON.parse(
+ decryptor({ cipherTextBlob: template.templateFields }).toString()
+ ) as Record<string, unknown>;
+ const mergedTemplateFields: Record<string, unknown> = fieldPatch
+ ? { ...currentTemplateFields, ...fieldPatch }
+ : currentTemplateFields;
+
+ let kubernetesPropagationData: TIdentityKubernetesAuthsUpdate | undefined;
+ if (fieldPatch && template.authMethod === IdentityAuthTemplateMethod.KUBERNETES) {
+ const merged = mergedTemplateFields as TKubernetesTemplateFields;
+ const patch = fieldPatch as Partial<TKubernetesTemplateFields>;
+ // follow the CA cert with the verification toggle unless the patch sets it explicitly,
+ // mirroring the identity k8s auth update behavior
+ if (!("verifyTlsCertificate" in patch) && "caCert" in patch) {
+ merged.verifyTlsCertificate = Boolean(patch.caCert?.length);
+ }
+ $validateKubernetesTemplateFields(merged);
+ kubernetesPropagationData = {
+ kubernetesHost: merged.kubernetesHost ?? null,
+ tokenReviewMode: merged.tokenReviewMode,
+ allowedAudience: merged.allowedAudience ?? "",
+ verifyTlsCertificate: merged.verifyTlsCertificate ?? Boolean(merged.caCert?.length),
+ encryptedKubernetesCaCertificate: merged.caCert
+ ? encryptor({ plainText: Buffer.from(merged.caCert) }).cipherTextBlob
+ : null,
+ encryptedKubernetesTokenReviewerJwt: merged.tokenReviewerJwt
+ ? encryptor({ plainText: Buffer.from(merged.tokenReviewerJwt) }).cipherTextBlob
+ : null
+ };
+ // gateway references are re-resolved (and re-authorized) only when the patch touches
+ // them; linked rows keep their columns otherwise, so a gateway that was deleted after
+ // authoring cannot block unrelated edits like rotating the reviewer JWT
+ if ("gatewayId" in patch || "gatewayPoolId" in patch) {
+ $authorizeKubernetesTemplateGateway({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ plan,
+ permission
+ });
+ const { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId } =
+ await $resolveKubernetesTemplateGateway({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ orgId: template.orgId
+ });
+ kubernetesPropagationData.gatewayId = resolvedGatewayId;
+ kubernetesPropagationData.gatewayV2Id = resolvedGatewayV2Id;
+ kubernetesPropagationData.gatewayPoolId = resolvedGatewayPoolId;
+ }
+ }
+
+ const { updatedTemplate, propagatedIdentityIds } = await identityAuthTemplateDAL.transaction(async (tx) => {
const authTemplate = await identityAuthTemplateDAL.updateById(
templateId,
{
name,
- ...(templateFields && {
- templateFields: encryptor({ plainText: Buffer.from(JSON.stringify(templateFields)) }).cipherTextBlob
+ ...(fieldPatch && {
+ // persist the merged result, not the raw patch, so a partial update cannot
+ // destroy the fields it does not carry
+ templateFields: encryptor({ plainText: Buffer.from(JSON.stringify(mergedTemplateFields)) }).cipherTextBlob
})
},
tx
);
- if (templateFields && template.authMethod === IdentityAuthTemplateMethod.LDAP) {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: template.orgId
- });
-
- const currentTemplateFields = JSON.parse(
- decryptor({ cipherTextBlob: template.templateFields }).toString()
- ) as TLdapTemplateFields;
+ let identityIds: string[] = [];
- const mergedTemplateFields: TLdapTemplateFields = { ...currentTemplateFields, ...templateFields };
- finalTemplateFields = mergedTemplateFields;
+ if (fieldPatch && template.authMethod === IdentityAuthTemplateMethod.LDAP) {
+ const mergedLdapFields = mergedTemplateFields as TLdapTemplateFields;
const ldapUpdateData: {
url?: string;
searchBase?: string;
@@ -167,54 +398,54 @@ export const identityAuthTemplateServiceFactory = ({
encryptedLdapCaCertificate?: Buffer;
} = {};
- if ("url" in templateFields) {
- ldapUpdateData.url = mergedTemplateFields.url;
+ if ("url" in fieldPatch) {
+ ldapUpdateData.url = mergedLdapFields.url;
}
- if ("searchBase" in templateFields) {
- ldapUpdateData.searchBase = mergedTemplateFields.searchBase;
+ if ("searchBase" in fieldPatch) {
+ ldapUpdateData.searchBase = mergedLdapFields.searchBase;
}
- if ("bindDN" in templateFields) {
+ if ("bindDN" in fieldPatch) {
ldapUpdateData.encryptedBindDN = encryptor({
- plainText: Buffer.from(mergedTemplateFields.bindDN)
+ plainText: Buffer.from(mergedLdapFields.bindDN)
}).cipherTextBlob;
}
- if ("bindPass" in templateFields) {
+ if ("bindPass" in fieldPatch) {
ldapUpdateData.encryptedBindPass = encryptor({
- plainText: Buffer.from(mergedTemplateFields.bindPass)
+ plainText: Buffer.from(mergedLdapFields.bindPass)
}).cipherTextBlob;
}
- if ("ldapCaCertificate" in templateFields) {
+ if ("ldapCaCertificate" in fieldPatch) {
ldapUpdateData.encryptedLdapCaCertificate = encryptor({
- plainText: Buffer.from(mergedTemplateFields.ldapCaCertificate || "")
+ plainText: Buffer.from(mergedLdapFields.ldapCaCertificate || "")
}).cipherTextBlob;
}
if (Object.keys(ldapUpdateData).length > 0) {
- const updatedLdapAuths = await identityLdapAuthDAL.update({ templateId }, ldapUpdateData, tx);
- await Promise.all(
- updatedLdapAuths.map(async (updatedLdapAuth) => {
- await auditLogService.createAuditLog({
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- orgId: actorOrgId,
- event: {
- type: EventType.UPDATE_IDENTITY_LDAP_AUTH,
- metadata: {
- identityId: updatedLdapAuth.identityId,
- templateId: template.id
- }
- }
- });
- })
- );
+ const updatedRows = await identityLdapAuthDAL.updateByTemplateId({ templateId }, ldapUpdateData, tx);
+ identityIds = updatedRows.map((row) => row.identityId);
}
}
- return authTemplate;
+
+ if (kubernetesPropagationData) {
+ const updatedRows = await identityKubernetesAuthDAL.updateByTemplateId(
+ { templateId },
+ kubernetesPropagationData,
+ tx
+ );
+ identityIds = updatedRows.map((row) => row.identityId);
+ }
+
+ return { updatedTemplate: authTemplate, propagatedIdentityIds: identityIds };
+ });
+
+ await $auditTemplatePropagation({
+ identityIds: propagatedIdentityIds,
+ authMethod: template.authMethod,
+ templateId: template.id,
+ orgId: template.orgId
});
- return { ...updatedTemplate, templateFields: finalTemplateFields };
+ return { ...updatedTemplate, templateFields: $redactTemplateSecrets(template.authMethod, mergedTemplateFields) };
};
const deleteTemplate = async ({
@@ -243,34 +474,39 @@ export const identityAuthTemplateServiceFactory = ({
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
- const deletedTemplate = await identityAuthTemplateDAL.transaction(async (tx) => {
- // Remove template reference from identityLdapAuth records
- const updatedLdapAuths = await identityLdapAuthDAL.update({ templateId }, { templateId: null }, tx);
- await Promise.all(
- updatedLdapAuths.map(async (updatedLdapAuth) => {
- await auditLogService.createAuditLog({
- actor: {
- type: ActorType.PLATFORM,
- metadata: {}
- },
- orgId: actorOrgId,
- event: {
- type: EventType.UPDATE_IDENTITY_LDAP_AUTH,
- metadata: {
- identityId: updatedLdapAuth.identityId,
- templateId: template.id
- }
- }
- });
- })
- );
+ const { deletedTemplate, unlinkedIdentityIds } = await identityAuthTemplateDAL.transaction(async (tx) => {
+ // Unlink identity auth records; the copied config values are kept so linked
+ // identities keep authenticating
+ let identityIds: string[] = [];
+ if (template.authMethod === IdentityAuthTemplateMethod.LDAP) {
+ const updatedRows = await identityLdapAuthDAL.updateByTemplateId({ templateId }, { templateId: null }, tx);
+ identityIds = updatedRows.map((row) => row.identityId);
+ } else if (template.authMethod === IdentityAuthTemplateMethod.KUBERNETES) {
+ const updatedRows = await identityKubernetesAuthDAL.updateByTemplateId(
+ { templateId },
+ { templateId: null },
+ tx
+ );
+ identityIds = updatedRows.map((row) => row.identityId);
+ } else {
+ // fail loudly rather than deleting a template whose linked identities we cannot unlink
+ throw new BadRequestError({
+ message: `Deleting templates with auth method '${template.authMethod}' is not supported`
+ });
+ }
- // Delete the template
const [deletedTpl] = await identityAuthTemplateDAL.delete({ id: templateId }, tx);
- return deletedTpl;
+ return { deletedTemplate: deletedTpl, unlinkedIdentityIds: identityIds };
});
- return deletedTemplate;
+ await $auditTemplatePropagation({
+ identityIds: unlinkedIdentityIds,
+ authMethod: template.authMethod,
+ templateId: template.id,
+ orgId: template.orgId
+ });
+
+ return { ...deletedTemplate, templateFields: {} };
};
const getTemplate = async ({
@@ -303,11 +539,12 @@ export const identityAuthTemplateServiceFactory = ({
type: KmsDataKey.Organization,
orgId: template.orgId
});
- const decryptedTemplateFields = decryptor({ cipherTextBlob: template.templateFields }).toString();
+ const decryptedTemplateFields = JSON.parse(
+ decryptor({ cipherTextBlob: template.templateFields }).toString()
+ ) as Record<string, unknown>;
return {
...template,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- templateFields: JSON.parse(decryptedTemplateFields)
+ templateFields: $redactTemplateSecrets(template.authMethod, decryptedTemplateFields)
};
};
@@ -342,11 +579,16 @@ export const identityAuthTemplateServiceFactory = ({
});
return {
totalCount,
- templates: docs.map((doc) => ({
- ...doc,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- templateFields: JSON.parse(decryptor({ cipherTextBlob: doc.templateFields }).toString())
- }))
+ templates: docs.map((doc) => {
+ const parsedTemplateFields = JSON.parse(decryptor({ cipherTextBlob: doc.templateFields }).toString()) as Record<
+ string,
+ unknown
+ >;
+ return {
+ ...doc,
+ templateFields: $redactTemplateSecrets(doc.authMethod, parsedTemplateFields)
+ };
+ })
};
};
@@ -377,11 +619,16 @@ export const identityAuthTemplateServiceFactory = ({
type: KmsDataKey.Organization,
orgId: actorOrgId
});
- return docs.map((doc) => ({
- ...doc,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- templateFields: JSON.parse(decryptor({ cipherTextBlob: doc.templateFields }).toString())
- }));
+ return docs.map((doc) => {
+ const parsedTemplateFields = JSON.parse(decryptor({ cipherTextBlob: doc.templateFields }).toString()) as Record<
+ string,
+ unknown
+ >;
+ return {
+ ...doc,
+ templateFields: $redactTemplateSecrets(doc.authMethod, parsedTemplateFields)
+ };
+ });
};
const findTemplateUsages = async ({
@@ -441,13 +688,31 @@ export const identityAuthTemplateServiceFactory = ({
throw new NotFoundError({ message: "Template not found" });
}
- switch (template.authMethod) {
- case IdentityAuthTemplateMethod.LDAP:
- await identityLdapAuthDAL.update({ $in: { identityId: identityIds }, templateId }, { templateId: null });
- break;
- default:
- break;
+ let unlinkedIdentityIds: string[] = [];
+ if (template.authMethod === IdentityAuthTemplateMethod.LDAP) {
+ const updatedRows = await identityLdapAuthDAL.updateByTemplateId(
+ { templateId, identityIds },
+ { templateId: null }
+ );
+ unlinkedIdentityIds = updatedRows.map((row) => row.identityId);
+ } else if (template.authMethod === IdentityAuthTemplateMethod.KUBERNETES) {
+ const updatedRows = await identityKubernetesAuthDAL.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`
+ });
}
+
+ await $auditTemplatePropagation({
+ identityIds: unlinkedIdentityIds,
+ authMethod: template.authMethod,
+ templateId: template.id,
+ orgId: template.orgId
+ });
};
return {
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.ts
index 8039e41c28..149bdecb65 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
@@ -1,4 +1,5 @@
import { TProjectPermission } from "@app/lib/types";
+import { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
import { IdentityAuthTemplateMethod } from "./identity-auth-template-enums";
@@ -11,9 +12,21 @@ export type TLdapTemplateFields = {
ldapCaCertificate?: string;
};
+export type TKubernetesTemplateFields = {
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode;
+ kubernetesHost?: string | null;
+ caCert?: string;
+ verifyTlsCertificate?: boolean;
+ tokenReviewerJwt?: string;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ allowedAudience?: string;
+};
+
// Union type for all template field types
export type TTemplateFieldsByMethod = {
[IdentityAuthTemplateMethod.LDAP]: TLdapTemplateFields;
+ [IdentityAuthTemplateMethod.KUBERNETES]: TKubernetesTemplateFields;
};
// Generic base types that use conditional types for type safety
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 1e61ab6c1d..d5da9a750b 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -613,6 +613,8 @@ export const KUBERNETES_AUTH = {
},
ATTACH: {
identityId: "The ID of the machine identity to attach the configuration onto.",
+ templateId:
+ "The ID of the Kubernetes auth template to source connection settings from. When provided, the host, CA certificate, token reviewer JWT, token review mode, gateway, and allowed audience are taken from the template and cannot be set individually.",
kubernetesHost: "The host string, host:port pair, or URL to the base of the Kubernetes API server.",
caCert:
"The PEM-encoded CA certificate used to validate the Kubernetes API server's TLS certificate. Required when verifyTlsCertificate is true. Supplying a non-empty caCert always implies verifyTlsCertificate=true; explicitly setting the toggle to false in the same request is rejected.",
@@ -621,7 +623,7 @@ export const KUBERNETES_AUTH = {
tokenReviewerJwt:
"Optional JWT token for accessing Kubernetes TokenReview API. If provided, this long-lived token will be used to validate service account tokens during authentication. If omitted, the client's own JWT will be used instead, which requires the client to have the system:auth-delegator ClusterRole binding.",
tokenReviewMode:
- "The mode to use for token review. Must be one of: 'api', 'gateway'. If gateway is selected, the gateway must be deployed in Kubernetes, and the gateway must have the system:auth-delegator ClusterRole binding.",
+ "The mode to use for token review. Must be one of: 'api', 'gateway'. Defaults to 'api' when omitted. If gateway is selected, the gateway must be deployed in Kubernetes, and the gateway must have the system:auth-delegator ClusterRole binding.",
allowedNamespaces:
"The comma-separated list of trusted namespaces that service accounts must belong to authenticate with Infisical.",
allowedNames: "The comma-separated list of trusted service account names that can authenticate with Infisical.",
@@ -635,6 +637,8 @@ export const KUBERNETES_AUTH = {
},
UPDATE: {
identityId: "The ID of the machine identity to update the auth method for.",
+ templateId:
+ "The ID of the Kubernetes auth template to link. While linked, connection settings are managed by the template and cannot be set individually. Pass null to unlink the template; the settings copied from it are kept.",
kubernetesHost: "The new host string, host:port pair, or URL to the base of the Kubernetes API server.",
caCert:
"The new PEM-encoded CA certificate used to validate the Kubernetes API server's TLS certificate. Required when verifyTlsCertificate is true. Supplying a non-empty caCert always implies verifyTlsCertificate=true; the update is rejected if the resulting effective state would store a CA together with verifyTlsCertificate=false.",
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 28bdfdae1e..041143c45d 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -2476,6 +2476,10 @@ export const registerRoutes = async (
const identityAuthTemplateService = identityAuthTemplateServiceFactory({
identityAuthTemplateDAL,
identityLdapAuthDAL,
+ identityKubernetesAuthDAL,
+ gatewayDAL,
+ gatewayV2DAL,
+ gatewayPoolDAL,
permissionService,
kmsService,
licenseService,
@@ -2508,6 +2512,7 @@ export const registerRoutes = async (
const identityKubernetesAuthService = identityKubernetesAuthServiceFactory({
identityDAL,
identityKubernetesAuthDAL,
+ identityAuthTemplateDAL,
identityAccessTokenDAL,
permissionService,
licenseService,
diff --git a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts b/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
index 5e339e242d..7face41064 100644
--- a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
+++ b/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
@@ -5,7 +5,6 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, KUBERNETES_AUTH } from "@app/lib/api-docs";
import { UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
@@ -13,6 +12,11 @@ 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 { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
+import {
+ kubernetesHostSchema,
+ rejectTemplateManagedKubernetesFields,
+ superRefineKubernetesConnectionFields
+} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-validators";
import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -32,7 +36,8 @@ const IdentityKubernetesAuthResponseSchema = IdentityKubernetesAuthsSchema.pick(
allowedAudience: true,
gatewayId: true,
gatewayPoolId: true,
- verifyTlsCertificate: true
+ verifyTlsCertificate: true,
+ templateId: true
}).extend({
caCert: z.string(),
tokenReviewerJwt: z.string().optional().nullable()
@@ -164,40 +169,21 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
}),
body: z
.object({
- kubernetesHost: z
- .string()
- .trim()
- .min(1)
- .nullable()
- .describe(KUBERNETES_AUTH.ATTACH.kubernetesHost)
- .refine(
- (val) => {
- if (val === null) return true;
-
- return characterValidator([
- CharacterType.Alphabets,
- CharacterType.Numbers,
- CharacterType.Colon,
- CharacterType.Period,
- CharacterType.ForwardSlash,
- CharacterType.Hyphen
- ])(val);
- },
- {
- message:
- "Kubernetes host must only contain alphabets, numbers, colons, periods, hyphen, and forward slashes."
- }
- ),
+ templateId: z.string().uuid().optional().describe(KUBERNETES_AUTH.ATTACH.templateId),
+ kubernetesHost: kubernetesHostSchema.nullish().describe(KUBERNETES_AUTH.ATTACH.kubernetesHost),
caCert: z.string().trim().optional().describe(KUBERNETES_AUTH.ATTACH.caCert),
verifyTlsCertificate: z.boolean().optional().describe(KUBERNETES_AUTH.ATTACH.verifyTlsCertificate),
tokenReviewerJwt: z.string().trim().optional().describe(KUBERNETES_AUTH.ATTACH.tokenReviewerJwt),
+ // no zod defaults on tokenReviewMode/allowedAudience: a default would make them
+ // indistinguishable from caller-supplied values, so template attaches could not
+ // reject them; the service defaults them (api / "") on the custom path
tokenReviewMode: z
.nativeEnum(IdentityKubernetesAuthTokenReviewMode)
- .default(IdentityKubernetesAuthTokenReviewMode.Api)
+ .optional()
.describe(KUBERNETES_AUTH.ATTACH.tokenReviewMode),
allowedNamespaces: z.string().describe(KUBERNETES_AUTH.ATTACH.allowedNamespaces), // TODO: validation
allowedNames: z.string().describe(KUBERNETES_AUTH.ATTACH.allowedNames),
- allowedAudience: z.string().describe(KUBERNETES_AUTH.ATTACH.allowedAudience),
+ allowedAudience: z.string().trim().max(1000).optional().describe(KUBERNETES_AUTH.ATTACH.allowedAudience),
gatewayId: z.string().uuid().optional().nullable().describe(KUBERNETES_AUTH.ATTACH.gatewayId),
gatewayPoolId: z.string().uuid().optional().nullable(),
accessTokenTrustedIps: z
@@ -230,30 +216,10 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
.describe(KUBERNETES_AUTH.ATTACH.accessTokenNumUsesLimit)
})
.superRefine((data, ctx) => {
- if (data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && !data.kubernetesHost) {
- ctx.addIssue({
- path: ["kubernetesHost"],
- code: z.ZodIssueCode.custom,
- message: "When token review mode is set to API, a Kubernetes host must be provided"
- });
- }
- if (
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&
- !data.gatewayId &&
- !data.gatewayPoolId
- ) {
- ctx.addIssue({
- path: ["gatewayId"],
- code: z.ZodIssueCode.custom,
- message: "When token review mode is set to Gateway, a gateway or gateway pool must be selected"
- });
- }
- if (data.gatewayId && data.gatewayPoolId) {
- ctx.addIssue({
- path: ["gatewayPoolId"],
- code: z.ZodIssueCode.custom,
- message: "Cannot specify both a gateway and a gateway pool"
- });
+ if (data.templateId) {
+ rejectTemplateManagedKubernetesFields(data, ctx);
+ } else {
+ superRefineKubernetesConnectionFields(data, ctx);
}
if (data.accessTokenTTL > data.accessTokenMaxTTL) {
@@ -263,30 +229,6 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
message: "Access Token TTL cannot be greater than Access Token Max TTL."
});
}
- if (
- data.verifyTlsCertificate &&
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- !data.caCert?.length
- ) {
- ctx.addIssue({
- path: ["caCert"],
- code: z.ZodIssueCode.custom,
- message:
- "A CA certificate is required when TLS certificate verification is enabled. Either paste the Kubernetes API server's CA certificate or disable verification."
- });
- }
- if (
- data.verifyTlsCertificate === false &&
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- data.caCert?.length
- ) {
- ctx.addIssue({
- path: ["verifyTlsCertificate"],
- code: z.ZodIssueCode.custom,
- message:
- "TLS certificate verification cannot be disabled when a CA certificate is provided. Either remove the CA certificate or enable verification."
- });
- }
}),
response: {
200: z.object({
@@ -312,6 +254,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
type: EventType.ADD_IDENTITY_KUBERNETES_AUTH,
metadata: {
identityId: identityKubernetesAuth.identityId,
+ templateId: identityKubernetesAuth.templateId,
kubernetesHost: identityKubernetesAuth.kubernetesHost ?? "",
allowedNamespaces: identityKubernetesAuth.allowedNamespaces,
allowedNames: identityKubernetesAuth.allowedNames,
@@ -364,31 +307,8 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
}),
body: z
.object({
- kubernetesHost: z
- .string()
- .trim()
- .min(1)
- .nullable()
- .optional()
- .describe(KUBERNETES_AUTH.UPDATE.kubernetesHost)
- .refine(
- (val) => {
- if (!val) return true;
-
- return characterValidator([
- CharacterType.Alphabets,
- CharacterType.Numbers,
- CharacterType.Colon,
- CharacterType.Period,
- CharacterType.ForwardSlash,
- CharacterType.Hyphen
- ])(val);
- },
- {
- message:
- "Kubernetes host must only contain alphabets, numbers, colons, periods, hyphen, and forward slashes."
- }
- ),
+ templateId: z.string().uuid().nullable().optional().describe(KUBERNETES_AUTH.UPDATE.templateId),
+ kubernetesHost: kubernetesHostSchema.nullish().describe(KUBERNETES_AUTH.UPDATE.kubernetesHost),
caCert: z.string().trim().optional().describe(KUBERNETES_AUTH.UPDATE.caCert),
verifyTlsCertificate: z.boolean().optional().describe(KUBERNETES_AUTH.UPDATE.verifyTlsCertificate),
tokenReviewerJwt: z.string().trim().nullable().optional().describe(KUBERNETES_AUTH.UPDATE.tokenReviewerJwt),
@@ -398,7 +318,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
.describe(KUBERNETES_AUTH.UPDATE.tokenReviewMode),
allowedNamespaces: z.string().optional().describe(KUBERNETES_AUTH.UPDATE.allowedNamespaces), // TODO: validation
allowedNames: z.string().optional().describe(KUBERNETES_AUTH.UPDATE.allowedNames),
- allowedAudience: z.string().optional().describe(KUBERNETES_AUTH.UPDATE.allowedAudience),
+ allowedAudience: z.string().trim().max(1000).optional().describe(KUBERNETES_AUTH.UPDATE.allowedAudience),
gatewayId: z.string().uuid().optional().nullable().describe(KUBERNETES_AUTH.UPDATE.gatewayId),
gatewayPoolId: z.string().uuid().optional().nullable(),
accessTokenTrustedIps: z
@@ -431,24 +351,28 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
.describe(KUBERNETES_AUTH.UPDATE.accessTokenMaxTTL)
})
.superRefine((data, ctx) => {
- if (
- data.tokenReviewMode &&
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&
- !data.gatewayId &&
- !data.gatewayPoolId
- ) {
- ctx.addIssue({
- path: ["gatewayId"],
- code: z.ZodIssueCode.custom,
- message: "When token review mode is set to Gateway, a gateway or gateway pool must be selected"
- });
- }
- if (data.gatewayId && data.gatewayPoolId) {
- ctx.addIssue({
- path: ["gatewayPoolId"],
- code: z.ZodIssueCode.custom,
- message: "Cannot specify both a gateway and a gateway pool"
- });
+ if (data.templateId) {
+ rejectTemplateManagedKubernetesFields(data, ctx);
+ } else {
+ if (
+ data.tokenReviewMode &&
+ data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&
+ !data.gatewayId &&
+ !data.gatewayPoolId
+ ) {
+ ctx.addIssue({
+ path: ["gatewayId"],
+ code: z.ZodIssueCode.custom,
+ message: "When token review mode is set to Gateway, a gateway or gateway pool must be selected"
+ });
+ }
+ if (data.gatewayId && data.gatewayPoolId) {
+ ctx.addIssue({
+ path: ["gatewayPoolId"],
+ code: z.ZodIssueCode.custom,
+ message: "Cannot specify both a gateway and a gateway pool"
+ });
+ }
}
if (data.accessTokenMaxTTL && data.accessTokenTTL ? data.accessTokenTTL > data.accessTokenMaxTTL : false) {
ctx.addIssue({
@@ -482,6 +406,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
type: EventType.UPDATE_IDENTITY_KUBENETES_AUTH,
metadata: {
identityId: identityKubernetesAuth.identityId,
+ templateId: identityKubernetesAuth.templateId,
kubernetesHost: identityKubernetesAuth.kubernetesHost ?? "",
allowedNamespaces: identityKubernetesAuth.allowedNamespaces,
allowedNames: identityKubernetesAuth.allowedNames,
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-dal.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-dal.ts
index ef1149a909..c91ae20f44 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-dal.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-dal.ts
@@ -1,7 +1,7 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
+import { TableName, TIdentityKubernetesAuthsUpdate } from "@app/db/schemas";
import { ormify } from "@app/lib/knex";
export type TIdentityKubernetesAuthDALFactory = ReturnType<typeof identityKubernetesAuthDALFactory>;
@@ -9,6 +9,19 @@ export type TIdentityKubernetesAuthDALFactory = ReturnType<typeof identityKubern
export const identityKubernetesAuthDALFactory = (db: TDbClient) => {
const kubernetesAuthOrm = ormify(db, TableName.IdentityKubernetesAuth);
+ // 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: TIdentityKubernetesAuthsUpdate,
+ tx?: Knex
+ ): Promise<{ identityId: string }[]> => {
+ const query = (tx || db)(TableName.IdentityKubernetesAuth).where({ templateId });
+ if (identityIds) void query.whereIn("identityId", identityIds);
+ const docs: { identityId: string }[] = await query.update(data).returning("identityId");
+ return docs;
+ };
+
const findByGatewayId = async (gatewayId: string, tx?: Knex) => {
const docs = await (tx || db.replicaNode())(TableName.IdentityKubernetesAuth)
.leftJoin(TableName.Identity, `${TableName.IdentityKubernetesAuth}.identityId`, `${TableName.Identity}.id`)
@@ -53,5 +66,12 @@ export const identityKubernetesAuthDALFactory = (db: TDbClient) => {
return parseInt(String(result?.count || "0"), 10);
};
- return { ...kubernetesAuthOrm, findByGatewayId, countByGatewayId, findByGatewayPoolId, countByGatewayPoolId };
+ return {
+ ...kubernetesAuthOrm,
+ updateByTemplateId,
+ findByGatewayId,
+ countByGatewayId,
+ findByGatewayPoolId,
+ countByGatewayPoolId
+ };
};
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 5a44f65a04..6217a1ece1 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -12,17 +12,22 @@ import {
OrganizationActionScope,
TIdentityKubernetesAuthsUpdate
} from "@app/db/schemas";
+import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";
import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+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 { TKubernetesTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
OrgPermissionGatewayActions,
OrgPermissionGatewayPoolActions,
OrgPermissionIdentityActions,
+ OrgPermissionMachineIdentityAuthTemplateActions,
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import {
@@ -90,6 +95,7 @@ type TIdentityKubernetesAuthServiceFactoryDep = {
"create" | "findOne" | "transaction" | "updateById" | "delete"
>;
identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
+ identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId">;
membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
@@ -118,6 +124,7 @@ const GATEWAY_AUTH_DEFAULT_HOST = "https://kubernetes.default.svc.cluster.local"
export const identityKubernetesAuthServiceFactory = ({
identityDAL,
identityKubernetesAuthDAL,
+ identityAuthTemplateDAL,
membershipIdentityDAL,
keyStore,
identityAccessTokenDAL,
@@ -770,28 +777,29 @@ export const identityKubernetesAuthServiceFactory = ({
}
};
- const attachKubernetesAuth = async ({
- identityId,
- gatewayId,
- gatewayPoolId,
- kubernetesHost,
- caCert,
- verifyTlsCertificate,
- tokenReviewerJwt,
- tokenReviewMode,
- allowedNamespaces,
- allowedNames,
- allowedAudience,
- accessTokenTTL,
- accessTokenMaxTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps,
- actorId,
- actorAuthMethod,
- actor,
- actorOrgId,
- isActorSuperAdmin
- }: TAttachKubernetesAuthDTO) => {
+ const attachKubernetesAuth = async (dto: TAttachKubernetesAuthDTO) => {
+ const {
+ identityId,
+ templateId,
+ allowedNamespaces,
+ allowedNames,
+ accessTokenTTL,
+ accessTokenMaxTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId,
+ isActorSuperAdmin
+ } = dto;
+ let { gatewayId, gatewayPoolId, kubernetesHost, caCert, verifyTlsCertificate, tokenReviewerJwt, allowedAudience } =
+ dto;
+ let { tokenReviewMode } = dto;
+ // the route leaves these two optional (no zod default) so template-managed values can
+ // be detected and rejected when a template is used; default them for the custom path
+ tokenReviewMode = tokenReviewMode ?? IdentityKubernetesAuthTokenReviewMode.Api;
+ allowedAudience = allowedAudience ?? "";
const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
scopeData: {
scope: AccessScope.Organization,
@@ -842,6 +850,50 @@ export const identityKubernetesAuthServiceFactory = ({
OrgPermissionSubjects.Identity
);
}
+
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId: identityMembershipOrg.scopeOrgId
+ });
+
+ let template: TIdentityAuthTemplates | undefined;
+ if (templateId) {
+ 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.KUBERNETES) {
+ throw new NotFoundError({ message: `Kubernetes auth template with ID '${templateId}' not found` });
+ }
+
+ const templateFields = JSON.parse(
+ decryptor({ cipherTextBlob: template.templateFields }).toString()
+ ) as TKubernetesTemplateFields;
+
+ kubernetesHost = templateFields.kubernetesHost ?? null;
+ caCert = templateFields.caCert || undefined;
+ tokenReviewerJwt = templateFields.tokenReviewerJwt || undefined;
+ tokenReviewMode = templateFields.tokenReviewMode;
+ gatewayId = templateFields.gatewayId ?? null;
+ gatewayPoolId = templateFields.gatewayPoolId ?? null;
+ verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
+ allowedAudience = templateFields.allowedAudience ?? "";
+ } else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && !kubernetesHost) {
+ throw new BadRequestError({
+ message: "When token review mode is set to API, a Kubernetes host must be provided"
+ });
+ }
+
const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
const reformattedAccessTokenTrustedIps = accessTokenTrustedIps.map((accessTokenTrustedIp) => {
if (
@@ -895,18 +947,22 @@ export const identityKubernetesAuthServiceFactory = ({
isGatewayV1 = false;
}
- const { permission: orgPermission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor,
- actorId,
- orgId: identityMembershipOrg.scopeOrgId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionGatewayActions.AttachGateways,
- OrgPermissionSubjects.Gateway
- );
+ // when the gateway comes from a template, attaching the gateway was authorized at
+ // template authoring time, so the actor only needs the attach-template permission
+ if (!template) {
+ const { permission: orgPermission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId: identityMembershipOrg.scopeOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionGatewayActions.AttachGateways,
+ OrgPermissionSubjects.Gateway
+ );
+ }
if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
const gatewayExecutor = $createGatewayValidationRequest(gatewayId);
@@ -933,18 +989,20 @@ export const identityKubernetesAuthServiceFactory = ({
});
}
- const { permission: orgPermission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor,
- actorId,
- orgId: identityMembershipOrg.scopeOrgId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionGatewayPoolActions.AttachGatewayPools,
- OrgPermissionSubjects.GatewayPool
- );
+ if (!template) {
+ const { permission: orgPermission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId: identityMembershipOrg.scopeOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionGatewayPoolActions.AttachGatewayPools,
+ OrgPermissionSubjects.GatewayPool
+ );
+ }
const pool = await gatewayPoolDAL.findById(gatewayPoolId);
if (!pool || pool.orgId !== identityMembershipOrg.scopeOrgId) {
@@ -989,11 +1047,6 @@ export const identityKubernetesAuthServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: identityMembershipOrg.scopeOrgId
- });
-
let resolvedGatewayId: string | null | undefined = null;
let resolvedGatewayV2Id: string | null | undefined = null;
if (!gatewayPoolId && gatewayId) {
@@ -1012,13 +1065,15 @@ export const identityKubernetesAuthServiceFactory = ({
tokenReviewMode,
allowedNamespaces,
allowedNames,
- allowedAudience,
+ // narrowing from the early default does not survive into this closure
+ allowedAudience: allowedAudience ?? "",
accessTokenMaxTTL,
accessTokenTTL,
accessTokenNumUsesLimit,
gatewayId: resolvedGatewayId,
gatewayV2Id: resolvedGatewayV2Id,
gatewayPoolId: gatewayPoolId ?? null,
+ templateId: template?.id ?? null,
verifyTlsCertificate: resolvedVerifyTlsCertificate,
accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps),
encryptedKubernetesTokenReviewerJwt: tokenReviewerJwt
@@ -1040,28 +1095,25 @@ export const identityKubernetesAuthServiceFactory = ({
};
};
- const updateKubernetesAuth = async ({
- identityId,
- kubernetesHost,
- caCert,
- verifyTlsCertificate,
- tokenReviewerJwt,
- tokenReviewMode,
- allowedNamespaces,
- allowedNames,
- allowedAudience,
- gatewayId,
- gatewayPoolId,
- accessTokenTTL,
- accessTokenMaxTTL,
- accessTokenNumUsesLimit,
- accessTokenTrustedIps,
- actorId,
- actorAuthMethod,
- actor,
- actorOrgId,
- isActorSuperAdmin
- }: TUpdateKubernetesAuthDTO) => {
+ const updateKubernetesAuth = async (dto: TUpdateKubernetesAuthDTO) => {
+ const {
+ identityId,
+ templateId,
+ allowedNamespaces,
+ allowedNames,
+ accessTokenTTL,
+ accessTokenMaxTTL,
+ accessTokenNumUsesLimit,
+ accessTokenTrustedIps,
+ actorId,
+ actorAuthMethod,
+ actor,
+ actorOrgId,
+ isActorSuperAdmin
+ } = dto;
+ let { kubernetesHost, caCert, verifyTlsCertificate, tokenReviewerJwt, allowedAudience, gatewayId, gatewayPoolId } =
+ dto;
+ let { tokenReviewMode } = dto;
const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
scopeData: {
scope: AccessScope.Organization,
@@ -1118,6 +1170,65 @@ export const identityKubernetesAuthServiceFactory = ({
OrgPermissionSubjects.Identity
);
}
+
+ 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 !== identityKubernetesAuth.templateId) {
+ 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.KUBERNETES) {
+ throw new NotFoundError({ message: `Kubernetes auth template with ID '${templateId}' not found` });
+ }
+
+ const templateFields = JSON.parse(
+ decryptor({ cipherTextBlob: template.templateFields }).toString()
+ ) as TKubernetesTemplateFields;
+
+ kubernetesHost = templateFields.kubernetesHost ?? null;
+ caCert = templateFields.caCert ?? "";
+ tokenReviewerJwt = templateFields.tokenReviewerJwt || null;
+ tokenReviewMode = templateFields.tokenReviewMode;
+ gatewayId = templateFields.gatewayId ?? null;
+ gatewayPoolId = templateFields.gatewayPoolId ?? null;
+ verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
+ allowedAudience = templateFields.allowedAudience ?? "";
+ } else if (templateId === undefined && identityKubernetesAuth.templateId) {
+ const hasTemplateManagedFieldChanges =
+ kubernetesHost !== undefined ||
+ caCert !== undefined ||
+ verifyTlsCertificate !== undefined ||
+ tokenReviewerJwt !== undefined ||
+ tokenReviewMode !== undefined ||
+ allowedAudience !== undefined ||
+ gatewayId !== undefined ||
+ gatewayPoolId !== undefined;
+ if (hasTemplateManagedFieldChanges) {
+ throw new BadRequestError({
+ message:
+ "This identity's Kubernetes auth connection settings are managed by an auth template. Update the template to change them, or unlink the template by setting templateId to null."
+ });
+ }
+ }
+
const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
const reformattedAccessTokenTrustedIps = accessTokenTrustedIps?.map((accessTokenTrustedIp) => {
if (
@@ -1158,18 +1269,20 @@ export const identityKubernetesAuthServiceFactory = ({
isGatewayV1 = false;
}
- const { permission: orgPermission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor,
- actorId,
- orgId: identityMembershipOrg.scopeOrgId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionGatewayActions.AttachGateways,
- OrgPermissionSubjects.Gateway
- );
+ if (!template) {
+ const { permission: orgPermission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId: identityMembershipOrg.scopeOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionGatewayActions.AttachGateways,
+ OrgPermissionSubjects.Gateway
+ );
+ }
}
// Handle gateway pool permission check
@@ -1179,18 +1292,20 @@ export const identityKubernetesAuthServiceFactory = ({
message: "Your current plan does not support gateway pools. Please upgrade to an Enterprise plan."
});
}
- const { permission: orgPermission } = await permissionService.getOrgPermission({
- scope: OrganizationActionScope.Any,
- actor,
- actorId,
- orgId: identityMembershipOrg.scopeOrgId,
- actorAuthMethod,
- actorOrgId
- });
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionGatewayPoolActions.AttachGatewayPools,
- OrgPermissionSubjects.GatewayPool
- );
+ if (!template) {
+ const { permission: orgPermission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId: identityMembershipOrg.scopeOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionGatewayPoolActions.AttachGatewayPools,
+ OrgPermissionSubjects.GatewayPool
+ );
+ }
const pool = await gatewayPoolDAL.findById(gatewayPoolId);
if (!pool || pool.orgId !== identityMembershipOrg.scopeOrgId) {
@@ -1233,11 +1348,6 @@ export const identityKubernetesAuthServiceFactory = ({
effectiveGatewayId = identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId;
}
- const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: identityMembershipOrg.scopeOrgId
- });
-
let effectiveCaCert: string | undefined;
if (caCert !== undefined) {
effectiveCaCert = caCert;
@@ -1351,6 +1461,9 @@ export const identityKubernetesAuthServiceFactory = ({
allowedNamespaces,
allowedNames,
allowedAudience,
+ // 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,
gatewayId: shouldUpdateGatewayId ? gatewayIdValue : undefined,
gatewayV2Id: shouldUpdateGatewayId ? gatewayV2IdValue : undefined,
gatewayPoolId: gatewayPoolIdValue,
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-types.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-types.ts
index ad11fef5e1..c36ff82837 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-types.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-types.ts
@@ -13,14 +13,15 @@ export enum IdentityKubernetesAuthTokenReviewMode {
export type TAttachKubernetesAuthDTO = {
identityId: string;
- kubernetesHost: string | null;
+ templateId?: string;
+ kubernetesHost?: string | null;
caCert?: string;
verifyTlsCertificate?: boolean;
tokenReviewerJwt?: string;
- tokenReviewMode: IdentityKubernetesAuthTokenReviewMode;
+ tokenReviewMode?: IdentityKubernetesAuthTokenReviewMode;
allowedNamespaces: string;
allowedNames: string;
- allowedAudience: string;
+ allowedAudience?: string;
gatewayId?: string | null;
gatewayPoolId?: string | null;
accessTokenTTL: number;
@@ -32,6 +33,7 @@ export type TAttachKubernetesAuthDTO = {
export type TUpdateKubernetesAuthDTO = {
identityId: string;
+ templateId?: string | null;
kubernetesHost?: string | null;
caCert?: string;
verifyTlsCertificate?: boolean;
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts
index fd00c77fc7..3883afc796 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts
@@ -1,12 +1,110 @@
import { AxiosError, AxiosResponse } from "axios";
import https from "https";
+import { z } from "zod";
+import { TEMPLATE_VALIDATION_MESSAGES } from "@app/ee/services/identity-auth-template/identity-auth-template-enums";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { handleAxiosError, KubernetesAuthErrorContext } from "./identity-kubernetes-auth-error-handlers";
+import { IdentityKubernetesAuthTokenReviewMode } from "./identity-kubernetes-auth-types";
+
+export const kubernetesHostSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(255)
+ .refine(
+ (val) => {
+ if (!val) return true;
+
+ return characterValidator([
+ CharacterType.Alphabets,
+ CharacterType.Numbers,
+ CharacterType.Colon,
+ CharacterType.Period,
+ CharacterType.ForwardSlash,
+ CharacterType.Hyphen
+ ])(val);
+ },
+ {
+ message: "Kubernetes host must only contain alphabets, numbers, colons, periods, hyphen, and forward slashes."
+ }
+ );
+
+export type TKubernetesConnectionFields = {
+ tokenReviewMode?: IdentityKubernetesAuthTokenReviewMode | null;
+ kubernetesHost?: string | null;
+ caCert?: string | null;
+ verifyTlsCertificate?: boolean;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+};
+
+// single source for the cross-field connection rules shared by the identity k8s auth
+// attach route, the auth template create/update paths, and the frontend mirrors
+export const validateKubernetesConnectionFields = (
+ fields: TKubernetesConnectionFields
+): { path: string; message: string }[] => {
+ const issues: { path: string; message: string }[] = [];
+ const tokenReviewMode = fields.tokenReviewMode ?? IdentityKubernetesAuthTokenReviewMode.Api;
+
+ if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && !fields.kubernetesHost) {
+ issues.push({ path: "kubernetesHost", message: TEMPLATE_VALIDATION_MESSAGES.KUBERNETES.HOST_REQUIRED });
+ }
+ if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway && !fields.gatewayId && !fields.gatewayPoolId) {
+ issues.push({ path: "gatewayId", message: TEMPLATE_VALIDATION_MESSAGES.KUBERNETES.GATEWAY_REQUIRED });
+ }
+ if (fields.gatewayId && fields.gatewayPoolId) {
+ issues.push({ path: "gatewayPoolId", message: TEMPLATE_VALIDATION_MESSAGES.KUBERNETES.GATEWAY_CONFLICT });
+ }
+ if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api) {
+ if (fields.verifyTlsCertificate && !fields.caCert?.length) {
+ issues.push({ path: "caCert", message: TEMPLATE_VALIDATION_MESSAGES.KUBERNETES.CA_CERT_REQUIRED });
+ }
+ if (fields.verifyTlsCertificate === false && fields.caCert?.length) {
+ issues.push({
+ path: "verifyTlsCertificate",
+ message: TEMPLATE_VALIDATION_MESSAGES.KUBERNETES.TLS_VERIFICATION_CONFLICT
+ });
+ }
+ }
+ return issues;
+};
+
+export const superRefineKubernetesConnectionFields = (fields: TKubernetesConnectionFields, ctx: z.RefinementCtx) => {
+ validateKubernetesConnectionFields(fields).forEach((issue) => {
+ ctx.addIssue({ path: [issue.path], code: z.ZodIssueCode.custom, message: issue.message });
+ });
+};
+
+// fields the linked auth template owns on an identity's kubernetes auth; both the attach
+// and update routes reject them so the two endpoints cannot drift apart again
+export const TEMPLATE_MANAGED_KUBERNETES_AUTH_FIELDS = [
+ "kubernetesHost",
+ "caCert",
+ "verifyTlsCertificate",
+ "tokenReviewerJwt",
+ "tokenReviewMode",
+ "allowedAudience",
+ "gatewayId",
+ "gatewayPoolId"
+] as const;
+
+export const rejectTemplateManagedKubernetesFields = (data: Record<string, unknown>, ctx: z.RefinementCtx) => {
+ TEMPLATE_MANAGED_KUBERNETES_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`
+ });
+ }
+ });
+};
export type GatewayRequestExecutor = <T>(
method: "get" | "post",
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-dal.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-dal.ts
index 0d998dbe93..6b81e835fa 100644
--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-dal.ts
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-dal.ts
@@ -1,5 +1,9 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
+// not re-exported by the schemas barrel
+import { TIdentityLdapAuthsUpdate } from "@app/db/schemas/identity-ldap-auths";
import { ormify } from "@app/lib/knex";
export type TIdentityLdapAuthDALFactory = ReturnType<typeof identityLdapAuthDALFactory>;
@@ -7,5 +11,18 @@ export type TIdentityLdapAuthDALFactory = ReturnType<typeof identityLdapAuthDALF
export const identityLdapAuthDALFactory = (db: TDbClient) => {
const ldapAuthOrm = ormify(db, TableName.IdentityLdapAuth);
- return ldapAuthOrm;
+ // 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: TIdentityLdapAuthsUpdate,
+ tx?: Knex
+ ): Promise<{ identityId: string }[]> => {
+ const query = (tx || db)(TableName.IdentityLdapAuth).where({ templateId });
+ if (identityIds) void query.whereIn("identityId", identityIds);
+ const docs: { identityId: string }[] = await query.update(data).returning("identityId");
+ return docs;
+ };
+
+ return { ...ldapAuthOrm, updateByTemplateId };
};
diff --git a/docs/documentation/platform/identities/auth-templates.mdx b/docs/documentation/platform/identities/auth-templates.mdx
index 5c389376fe..206d7dfbfa 100644
--- a/docs/documentation/platform/identities/auth-templates.mdx
+++ b/docs/documentation/platform/identities/auth-templates.mdx
@@ -34,7 +34,7 @@ Auth templates are managed in **Organization Settings > Access Control > Identit
![Create Template Button](/images/platform/identities/auth-templates/create-template-button.png)
- Select the authentication method you want to create a template for (currently supports LDAP Auth).
+ Select the authentication method you want to create a template for (currently supports LDAP Auth and Kubernetes Auth).
</Step>
<Step title="Configure template settings">
@@ -49,7 +49,7 @@ Auth templates are managed in **Organization Settings > Access Control > Identit
- **Template Name**: A descriptive name for your template
- **URL**: The LDAP server to connect to such as `ldap://ldap.your-org.com`, `ldaps://ldap.myorg.com:636` _(for connection over SSL/TLS)_, etc.
- **Bind DN**: The DN to bind to the LDAP server with.
- - **Bind Pass**: The password to bind to the LDAP server with.
+ - **Bind Pass**: The password to bind to the LDAP server with. For security, this value is never displayed again after saving; when editing a template, leave the field blank to keep the current password.
- **Search Base / DN**: Base DN under which to perform user search such as `ou=Users,dc=acme,dc=com`.
- **CA Certificate**: The CA certificate to use when verifying the LDAP server certificate. This field is optional but recommended.
@@ -57,6 +57,23 @@ Auth templates are managed in **Organization Settings > Access Control > Identit
You can read more about LDAP Auth configuration in the [LDAP Auth documentation](/documentation/platform/identities/ldap-auth/general).
</Note>
</Tab>
+ <Tab title="Kubernetes Auth Template">
+ **For Kubernetes Auth templates**, configure the following fields:
+
+ - **Template Name**: A descriptive name for your template
+ - **Gateway**: An optional [gateway](/documentation/platform/gateways/overview) or gateway pool used to reach the Kubernetes API server.
+ - **Review Mode**: How service account tokens are reviewed. Select **Gateway as Reviewer** to have a gateway deployed in the cluster review tokens with its own service account, or **Manual Token Reviewer JWT (API)** to call the Kubernetes TokenReview API directly.
+ - **Kubernetes Host / Base Kubernetes API URL**: The host string, host:port pair, or URL to the base of the Kubernetes API server. Required when the review mode is set to API.
+ - **Token Reviewer JWT**: An optional long-lived service account token used to call the TokenReview API. If omitted, the authenticating client's own token is used, which requires the client's service account to have the `system:auth-delegator` ClusterRole binding. For security, this value is never displayed again after saving; when editing a template, leave the field blank to keep the current token.
+ - **Allowed Audience**: An optional audience claim that service account tokens must have to authenticate with Infisical.
+ - **Verify TLS Certificate** and **CA Certificate**: Whether and how to validate the Kubernetes API server's TLS certificate.
+
+ Allowed namespaces, allowed service account names, 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.
+
+ <Note>
+ You can read more about Kubernetes Auth configuration in the [Kubernetes Auth documentation](/documentation/platform/identities/kubernetes-auth).
+ </Note>
+ </Tab>
</Tabs>
</Step>
</Steps>
@@ -91,6 +108,6 @@ You can view which identities are using a specific template by clicking **View U
</Accordion>
<Accordion title="Do templates support all authentication methods?">
- Currently, auth templates support LDAP Auth. Support for additional authentication methods will be added in future releases.
+ Currently, auth templates support LDAP Auth and Kubernetes Auth. Support for additional authentication methods will be added in future releases.
</Accordion>
</AccordionGroup>
\ No newline at end of file
diff --git a/frontend/src/helpers/identityAuthSchemas.ts b/frontend/src/helpers/identityAuthSchemas.ts
index bc2b811de6..f8c29d0cc5 100644
--- a/frontend/src/helpers/identityAuthSchemas.ts
+++ b/frontend/src/helpers/identityAuthSchemas.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
-import { IdentityTrustedIp } from "@app/hooks/api/identities/types";
+import {
+ IdentityKubernetesAuthTokenReviewMode,
+ IdentityTrustedIp
+} from "@app/hooks/api/identities/types";
import { SECONDS_PER_DAY } from "./datetime";
import { isValidIpOrCidr } from "./ip";
@@ -54,3 +57,74 @@ export const mapTrustedIpsFromServer = (trustedIps: IdentityTrustedIp[]) =>
trustedIps.map(({ ipAddress, prefix }) => ({
ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
}));
+
+// Cross-field Kubernetes connection rules mirroring the backend's shared validator
+// (identity-kubernetes-auth-validators.ts); used by the identity k8s auth form and the
+// auth template modal so the two surfaces cannot drift apart.
+export const superRefineKubernetesConnectionFields = (
+ data: {
+ tokenReviewMode?: IdentityKubernetesAuthTokenReviewMode;
+ kubernetesHost?: string | null;
+ caCert?: string;
+ verifyTlsCertificate?: boolean;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ },
+ ctx: z.RefinementCtx
+) => {
+ const tokenReviewMode = data.tokenReviewMode ?? IdentityKubernetesAuthTokenReviewMode.Api;
+
+ if (
+ tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
+ !data.kubernetesHost?.length
+ ) {
+ ctx.addIssue({
+ path: ["kubernetesHost"],
+ code: z.ZodIssueCode.custom,
+ message: "When token review mode is set to API, a Kubernetes host must be provided"
+ });
+ }
+ if (
+ tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&
+ !data.gatewayId &&
+ !data.gatewayPoolId
+ ) {
+ ctx.addIssue({
+ path: ["gatewayId"],
+ code: z.ZodIssueCode.custom,
+ message:
+ "When token review mode is set to Gateway, a gateway or gateway pool must be selected"
+ });
+ }
+ if (data.gatewayId && data.gatewayPoolId) {
+ ctx.addIssue({
+ path: ["gatewayPoolId"],
+ code: z.ZodIssueCode.custom,
+ message: "Cannot specify both a gateway and a gateway pool"
+ });
+ }
+ if (
+ data.verifyTlsCertificate &&
+ tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
+ !data.caCert?.length
+ ) {
+ ctx.addIssue({
+ path: ["caCert"],
+ code: z.ZodIssueCode.custom,
+ message:
+ "A CA certificate is required when TLS certificate verification is enabled. Either paste the Kubernetes API server's CA certificate or disable verification."
+ });
+ }
+ if (
+ data.verifyTlsCertificate === false &&
+ tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
+ data.caCert?.length
+ ) {
+ ctx.addIssue({
+ path: ["verifyTlsCertificate"],
+ code: z.ZodIssueCode.custom,
+ message:
+ "TLS certificate verification cannot be disabled when a CA certificate is provided. Either remove the CA certificate or enable verification."
+ });
+ }
+};
diff --git a/frontend/src/hooks/api/identities/mutations.tsx b/frontend/src/hooks/api/identities/mutations.tsx
index 0eee524334..4b1e32fccd 100644
--- a/frontend/src/hooks/api/identities/mutations.tsx
+++ b/frontend/src/hooks/api/identities/mutations.tsx
@@ -1417,6 +1417,7 @@ export const useAddIdentityKubernetesAuth = () => {
return useMutation<IdentityKubernetesAuth, object, AddIdentityKubernetesAuthDTO>({
mutationFn: async ({
identityId,
+ templateId,
kubernetesHost,
tokenReviewerJwt,
allowedNames,
@@ -1436,6 +1437,7 @@ export const useAddIdentityKubernetesAuth = () => {
} = await apiRequest.post<{ identityKubernetesAuth: IdentityKubernetesAuth }>(
`/api/v1/auth/kubernetes-auth/identities/${identityId}`,
{
+ templateId,
kubernetesHost,
tokenReviewerJwt,
allowedNames,
@@ -1561,6 +1563,7 @@ export const useUpdateIdentityKubernetesAuth = () => {
return useMutation<IdentityKubernetesAuth, object, UpdateIdentityKubernetesAuthDTO>({
mutationFn: async ({
identityId,
+ templateId,
kubernetesHost,
tokenReviewerJwt,
allowedNamespaces,
@@ -1580,6 +1583,8 @@ export const useUpdateIdentityKubernetesAuth = () => {
} = await apiRequest.patch<{ identityKubernetesAuth: IdentityKubernetesAuth }>(
`/api/v1/auth/kubernetes-auth/identities/${identityId}`,
{
+ // tri-state: undefined keeps the current template link, null unlinks, uuid links
+ templateId,
kubernetesHost,
tokenReviewerJwt,
allowedNames,
diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.ts
index 8375d14a9e..07326f5dcc 100644
--- a/frontend/src/hooks/api/identities/types.ts
+++ b/frontend/src/hooks/api/identities/types.ts
@@ -504,6 +504,7 @@ export enum IdentityKubernetesAuthTokenReviewMode {
export type IdentityKubernetesAuth = {
identityId: string;
+ templateId?: string | null;
kubernetesHost: string;
tokenReviewerJwt: string;
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode;
@@ -524,15 +525,16 @@ export type AddIdentityKubernetesAuthDTO = {
organizationId?: string;
projectId?: string;
identityId: string;
- kubernetesHost: string | null;
+ templateId?: string;
+ kubernetesHost?: string | null;
tokenReviewerJwt?: string;
- tokenReviewMode: IdentityKubernetesAuthTokenReviewMode;
+ tokenReviewMode?: IdentityKubernetesAuthTokenReviewMode;
allowedNamespaces: string;
allowedNames: string;
- allowedAudience: string;
+ allowedAudience?: string;
gatewayId?: string | null;
gatewayPoolId?: string | null;
- caCert: string;
+ caCert?: string;
verifyTlsCertificate?: boolean;
accessTokenTTL: number;
accessTokenMaxTTL: number;
@@ -546,6 +548,7 @@ export type UpdateIdentityKubernetesAuthDTO = {
organizationId?: string;
projectId?: string;
identityId: string;
+ templateId?: string | null;
kubernetesHost?: string | null;
tokenReviewerJwt?: string | null;
tokenReviewMode?: IdentityKubernetesAuthTokenReviewMode;
diff --git a/frontend/src/hooks/api/identityAuthTemplates/queries.tsx b/frontend/src/hooks/api/identityAuthTemplates/queries.tsx
index 90c4c6c3cb..fd01833003 100644
--- a/frontend/src/hooks/api/identityAuthTemplates/queries.tsx
+++ b/frontend/src/hooks/api/identityAuthTemplates/queries.tsx
@@ -6,6 +6,7 @@ import {
GetIdentityAuthTemplatesDTO,
GetTemplateUsagesDTO,
IdentityAuthTemplate,
+ IdentityAuthTemplateForMethod,
MachineAuthTemplateUsage,
MachineIdentityAuthMethod
} from "./types";
@@ -59,16 +60,24 @@ export const useGetIdentityAuthTemplate = (templateId: string, organizationId: s
});
};
-export const useGetAvailableTemplates = (authMethod: MachineIdentityAuthMethod) => {
+export const useGetAvailableTemplates = <T extends MachineIdentityAuthMethod>(
+ authMethod: T,
+ options?: { enabled?: boolean }
+) => {
return useQuery({
queryKey: identityAuthTemplatesKeys.getAvailableTemplates(authMethod),
queryFn: async () => {
- const { data } = await apiRequest.get<IdentityAuthTemplate[]>("/api/v1/identity-templates", {
- params: { authMethod }
- });
+ const { data } = await apiRequest.get<IdentityAuthTemplateForMethod<T>[]>(
+ "/api/v1/identity-templates",
+ {
+ params: { authMethod }
+ }
+ );
return data;
},
- enabled: Boolean(authMethod)
+ // the endpoint requires the attach-template permission and an enterprise plan; callers
+ // gate the query so users without either do not fire a guaranteed 4xx on every mount
+ enabled: Boolean(authMethod) && (options?.enabled ?? true)
});
};
diff --git a/frontend/src/hooks/api/identityAuthTemplates/types.ts b/frontend/src/hooks/api/identityAuthTemplates/types.ts
index d446afe525..9b830c6ca8 100644
--- a/frontend/src/hooks/api/identityAuthTemplates/types.ts
+++ b/frontend/src/hooks/api/identityAuthTemplates/types.ts
@@ -1,5 +1,8 @@
+import { IdentityKubernetesAuthTokenReviewMode } from "../identities/types";
+
export enum MachineIdentityAuthMethod {
- LDAP = "ldap"
+ LDAP = "ldap",
+ KUBERNETES = "kubernetes"
}
export interface LdapTemplateFields {
@@ -10,28 +13,50 @@ export interface LdapTemplateFields {
ldapCaCertificate?: string;
}
-export interface IdentityAuthTemplate {
+export interface KubernetesTemplateFields {
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode;
+ kubernetesHost?: string | null;
+ caCert?: string;
+ verifyTlsCertificate?: boolean;
+ tokenReviewerJwt?: string;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ allowedAudience?: string;
+}
+
+export type TemplateFieldsByMethod = {
+ [MachineIdentityAuthMethod.LDAP]: LdapTemplateFields;
+ [MachineIdentityAuthMethod.KUBERNETES]: KubernetesTemplateFields;
+};
+
+export interface IdentityAuthTemplateForMethod<
+ T extends MachineIdentityAuthMethod = MachineIdentityAuthMethod
+> {
id: string;
name: string;
- authMethod: MachineIdentityAuthMethod;
+ authMethod: T;
organizationId: string;
- templateFields: LdapTemplateFields;
+ templateFields: TemplateFieldsByMethod[T];
createdAt: string;
updatedAt: string;
}
+export type IdentityAuthTemplate =
+ | IdentityAuthTemplateForMethod<MachineIdentityAuthMethod.LDAP>
+ | IdentityAuthTemplateForMethod<MachineIdentityAuthMethod.KUBERNETES>;
+
export interface CreateIdentityAuthTemplateDTO {
organizationId: string;
name: string;
authMethod: MachineIdentityAuthMethod;
- templateFields: LdapTemplateFields;
+ templateFields: LdapTemplateFields | KubernetesTemplateFields;
}
export interface UpdateIdentityAuthTemplateDTO {
templateId: string;
organizationId: string;
name?: string;
- templateFields?: Partial<LdapTemplateFields>;
+ templateFields?: Partial<LdapTemplateFields> | Partial<KubernetesTemplateFields>;
}
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.tsx
index 57180fc37c..04fd57c118 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
@@ -6,15 +6,18 @@ import {
useForm
} from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
+import { HelpCircleIcon, InfoIcon } from "lucide-react";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
import {
Button,
Field,
FieldError,
FieldGroup,
FieldLabel,
+ GatewayPicker,
Input,
Select,
SelectContent,
@@ -27,33 +30,117 @@ import {
SheetFooter,
SheetHeader,
SheetTitle,
- TextArea
+ Switch,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
} from "@app/components/v3";
import { useOrganization } from "@app/context";
import {
+ OrgGatewayPermissionActions,
+ OrgPermissionSubjects
+} from "@app/context/OrgPermissionContext/types";
+import { superRefineKubernetesConnectionFields } from "@app/helpers/identityAuthSchemas";
+import { IdentityKubernetesAuthTokenReviewMode } from "@app/hooks/api/identities/types";
+import {
+ type IdentityAuthTemplate,
+ type KubernetesTemplateFields,
+ type LdapTemplateFields,
MachineIdentityAuthMethod,
useCreateIdentityAuthTemplate,
useUpdateIdentityAuthTemplate
} from "@app/hooks/api/identityAuthTemplates";
import { UsePopUpState } from "@app/hooks/usePopUp";
-const authMethods = [{ label: "LDAP Auth", value: MachineIdentityAuthMethod.LDAP }];
-
-const schema = z.object({
- name: z.string().min(1, "Template name is required"),
- method: z.nativeEnum(MachineIdentityAuthMethod),
- url: z.string().min(1, "LDAP URL is required"),
- bindDN: z.string().min(1, "Bind DN is required"),
- bindPass: z.string().min(1, "Bind Pass is required"),
- searchBase: z.string().min(1, "Search Base / DN is required"),
- ldapCaCertificate: z
- .string()
- .optional()
- .transform((val) => val || undefined)
-});
+const authMethods = [
+ { label: "LDAP Auth", value: MachineIdentityAuthMethod.LDAP },
+ { label: "Kubernetes Auth", value: MachineIdentityAuthMethod.KUBERNETES }
+];
+
+const schema = z
+ .object({
+ name: z.string().min(1, "Template name is required"),
+ method: z.nativeEnum(MachineIdentityAuthMethod),
+ // secrets (bindPass, tokenReviewerJwt) are write-only: reads never return them, so in
+ // edit mode an empty field means "keep the stored value"
+ isEdit: z.boolean().default(false),
+ url: z.string().optional(),
+ bindDN: z.string().optional(),
+ bindPass: z.string().optional(),
+ searchBase: z.string().optional(),
+ ldapCaCertificate: z
+ .string()
+ .optional()
+ .transform((val) => val || undefined),
+ tokenReviewMode: z
+ .nativeEnum(IdentityKubernetesAuthTokenReviewMode)
+ .default(IdentityKubernetesAuthTokenReviewMode.Api),
+ kubernetesHost: z.string().optional(),
+ tokenReviewerJwt: z.string().optional(),
+ gatewayId: z.string().optional().nullable(),
+ gatewayPoolId: z.string().optional().nullable(),
+ caCert: z.string().optional(),
+ verifyTlsCertificate: z.boolean().default(true),
+ allowedAudience: z.string().optional()
+ })
+ .superRefine((data, ctx) => {
+ if (data.method === MachineIdentityAuthMethod.LDAP) {
+ if (!data.url) {
+ ctx.addIssue({
+ path: ["url"],
+ code: z.ZodIssueCode.custom,
+ message: "LDAP URL is required"
+ });
+ }
+ if (!data.bindDN) {
+ ctx.addIssue({
+ path: ["bindDN"],
+ code: z.ZodIssueCode.custom,
+ message: "Bind DN is required"
+ });
+ }
+ if (!data.bindPass && !data.isEdit) {
+ ctx.addIssue({
+ path: ["bindPass"],
+ code: z.ZodIssueCode.custom,
+ message: "Bind Pass is required"
+ });
+ }
+ if (!data.searchBase) {
+ ctx.addIssue({
+ path: ["searchBase"],
+ code: z.ZodIssueCode.custom,
+ message: "Search Base / DN is required"
+ });
+ }
+ return;
+ }
+
+ superRefineKubernetesConnectionFields(data, ctx);
+ });
export type FormData = z.infer<typeof schema>;
+const emptyFormValues: FormData = {
+ name: "",
+ method: MachineIdentityAuthMethod.LDAP,
+ isEdit: false,
+ url: "",
+ bindDN: "",
+ bindPass: "",
+ searchBase: "",
+ ldapCaCertificate: "",
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
+ kubernetesHost: "",
+ tokenReviewerJwt: "",
+ gatewayId: null,
+ gatewayPoolId: null,
+ caCert: "",
+ verifyTlsCertificate: true,
+ allowedAudience: ""
+};
+
type Props = {
popUp: UsePopUpState<["createTemplate", "editTemplate"]>;
handlePopUpToggle: (
@@ -70,66 +157,109 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
const { mutateAsync: updateTemplate } = useUpdateIdentityAuthTemplate();
const isEdit = popUp.editTemplate.isOpen;
- const template = popUp.editTemplate?.data?.template;
+ const template = popUp.editTemplate?.data?.template as IdentityAuthTemplate | undefined;
const {
control,
handleSubmit,
reset,
watch,
+ setValue,
formState: { isSubmitting }
} = useForm<FormData>({
resolver: zodResolver(schema),
- defaultValues: {
- name: "",
- method: MachineIdentityAuthMethod.LDAP,
- url: "",
- bindDN: "",
- bindPass: "",
- searchBase: "",
- ldapCaCertificate: ""
- }
+ defaultValues: emptyFormValues
});
useEffect(() => {
if (isEdit && template) {
- reset({
- name: template.name || "",
- method: MachineIdentityAuthMethod.LDAP,
- url: template.templateFields?.url || "",
- bindDN: template.templateFields?.bindDN || "",
- bindPass: template.templateFields?.bindPass || "",
- searchBase: template.templateFields?.searchBase || "",
- ldapCaCertificate: template.templateFields?.ldapCaCertificate || ""
- });
+ if (template.authMethod === MachineIdentityAuthMethod.KUBERNETES) {
+ const fields = template.templateFields;
+ reset({
+ ...emptyFormValues,
+ name: template.name || "",
+ method: MachineIdentityAuthMethod.KUBERNETES,
+ isEdit: true,
+ tokenReviewMode: fields?.tokenReviewMode || IdentityKubernetesAuthTokenReviewMode.Api,
+ kubernetesHost: fields?.kubernetesHost || "",
+ // write-only secret: never returned by the API, so edit starts blank (blank = keep)
+ tokenReviewerJwt: "",
+ gatewayId: fields?.gatewayId || null,
+ gatewayPoolId: fields?.gatewayPoolId || null,
+ caCert: fields?.caCert || "",
+ verifyTlsCertificate: fields?.verifyTlsCertificate ?? Boolean(fields?.caCert),
+ allowedAudience: fields?.allowedAudience || ""
+ });
+ } else {
+ reset({
+ ...emptyFormValues,
+ name: template.name || "",
+ method: MachineIdentityAuthMethod.LDAP,
+ isEdit: true,
+ url: template.templateFields?.url || "",
+ bindDN: template.templateFields?.bindDN || "",
+ // write-only secret: never returned by the API, so edit starts blank (blank = keep)
+ bindPass: "",
+ searchBase: template.templateFields?.searchBase || "",
+ ldapCaCertificate: template.templateFields?.ldapCaCertificate || ""
+ });
+ }
} else {
- reset({
- name: "",
- method: MachineIdentityAuthMethod.LDAP,
- url: "",
- bindDN: "",
- bindPass: "",
- searchBase: "",
- ldapCaCertificate: ""
- });
+ reset(emptyFormValues);
}
}, [isEdit, template, reset]);
const selectedMethod = watch("method");
+ const tokenReviewMode = watch("tokenReviewMode");
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);
+
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> = {
+ ...templateFields
+ };
+ if (data.method === MachineIdentityAuthMethod.LDAP && !data.bindPass) {
+ delete (patchFields as Partial<LdapTemplateFields>).bindPass;
+ }
+ if (
+ data.method === MachineIdentityAuthMethod.KUBERNETES &&
+ isApiMode &&
+ !data.tokenReviewerJwt
+ ) {
+ delete (patchFields as Partial<KubernetesTemplateFields>).tokenReviewerJwt;
+ }
await updateTemplate({
templateId: template.id,
organizationId: orgId,
name: data.name,
- templateFields: {
- url: data.url,
- bindDN: data.bindDN,
- bindPass: data.bindPass,
- searchBase: data.searchBase,
- ldapCaCertificate: data.ldapCaCertificate
- }
+ templateFields: patchFields
});
createNotification({
text: "Successfully updated auth template",
@@ -140,13 +270,7 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
organizationId: orgId,
name: data.name,
authMethod: data.method,
- templateFields: {
- url: data.url,
- bindDN: data.bindDN,
- bindPass: data.bindPass,
- searchBase: data.searchBase,
- ldapCaCertificate: data.ldapCaCertificate
- }
+ templateFields
});
createNotification({
text: "Successfully created auth template",
@@ -163,7 +287,17 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
reset();
};
- const renderField = <TName extends "name" | "url" | "bindDN" | "bindPass" | "searchBase">(
+ const renderField = <
+ TName extends
+ | "name"
+ | "url"
+ | "bindDN"
+ | "bindPass"
+ | "searchBase"
+ | "kubernetesHost"
+ | "tokenReviewerJwt"
+ | "allowedAudience"
+ >(
id: string,
label: string,
field: ControllerRenderProps<FormData, TName>,
@@ -215,7 +349,7 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
<FieldLabel htmlFor="identity-auth-template-method">
Authentication Method
</FieldLabel>
- <Select value={field.value} onValueChange={field.onChange}>
+ <Select value={field.value} onValueChange={field.onChange} disabled={isEdit}>
<SelectTrigger
id="identity-auth-template-method"
className="w-full"
@@ -236,7 +370,7 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
)}
/>
- {selectedMethod === "ldap" && (
+ {selectedMethod === MachineIdentityAuthMethod.LDAP && (
<>
<Controller
control={control}
@@ -263,7 +397,7 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
name="bindPass"
render={({ field, fieldState: { error } }) =>
renderField("identity-auth-template-bind-pass", "Bind Pass", field, error, {
- placeholder: "********",
+ placeholder: isEdit ? "Leave blank to keep the current value" : "********",
type: "password"
})
}
@@ -311,6 +445,233 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
/>
</>
)}
+
+ {selectedMethod === MachineIdentityAuthMethod.KUBERNETES && (
+ <>
+ <OrgPermissionCan
+ I={OrgGatewayPermissionActions.AttachGateways}
+ a={OrgPermissionSubjects.Gateway}
+ >
+ {(isAllowed) => (
+ <Controller
+ control={control}
+ name="gatewayId"
+ render={({ fieldState: { error } }) => {
+ const gatewayIdVal = watch("gatewayId");
+ const gatewayPoolIdVal = watch("gatewayPoolId");
+
+ return (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel htmlFor="identity-auth-template-gateway">
+ Gateway (optional)
+ </FieldLabel>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <GatewayPicker
+ value={{
+ gatewayId: gatewayIdVal || null,
+ gatewayPoolId: gatewayPoolIdVal || null
+ }}
+ onChange={({ gatewayId: gwId, gatewayPoolId: poolId }) => {
+ setValue("gatewayId", gwId, { shouldDirty: true });
+ setValue("gatewayPoolId", poolId, { shouldDirty: true });
+ if (!gwId && !poolId) {
+ setValue(
+ "tokenReviewMode",
+ IdentityKubernetesAuthTokenReviewMode.Api,
+ { shouldDirty: true, shouldTouch: true }
+ );
+ }
+ }}
+ isDisabled={!isAllowed}
+ className="w-full"
+ />
+ </div>
+ </TooltipTrigger>
+ {!isAllowed && (
+ <TooltipContent className="max-w-md">
+ Restricted access. You don&apos;t have permission to attach
+ gateways to resources.
+ </TooltipContent>
+ )}
+ </Tooltip>
+ <FieldError>{error?.message}</FieldError>
+ </Field>
+ );
+ }}
+ />
+ )}
+ </OrgPermissionCan>
+
+ <Controller
+ control={control}
+ name="tokenReviewMode"
+ render={({ field, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel
+ htmlFor="identity-auth-template-token-review-mode"
+ className="inline-flex items-center gap-1.5"
+ >
+ Review Mode
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ The method of which tokens are reviewed. If you select Gateway as
+ Reviewer, the selected gateway will be used to review tokens with. If
+ this option is enabled, the gateway must be deployed in Kubernetes, and
+ the gateway must have the system:auth-delegator ClusterRole binding.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger
+ id="identity-auth-template-token-review-mode"
+ className="w-full"
+ isError={Boolean(error)}
+ >
+ <SelectValue placeholder="Select review mode" />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ <SelectItem value="gateway">Gateway as Reviewer</SelectItem>
+ <SelectItem value="api">Manual Token Reviewer JWT (API)</SelectItem>
+ </SelectContent>
+ </Select>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+
+ {tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && (
+ <>
+ <Controller
+ control={control}
+ name="kubernetesHost"
+ render={({ field, fieldState: { error } }) =>
+ renderField(
+ "identity-auth-template-kubernetes-host",
+ "Kubernetes Host / Base Kubernetes API URL",
+ field,
+ error,
+ {
+ placeholder: "https://my-example-k8s-api-host.com",
+ autoComplete: "off"
+ }
+ )
+ }
+ />
+
+ <Controller
+ control={control}
+ name="tokenReviewerJwt"
+ render={({ field, fieldState: { error } }) =>
+ renderField(
+ "identity-auth-template-token-reviewer-jwt",
+ "Token Reviewer JWT (optional)",
+ field,
+ error,
+ {
+ placeholder: isEdit
+ ? "Leave blank to keep the current value"
+ : "eyJhbGciOiJSUzI1NiIs...",
+ type: "password",
+ autoComplete: "new-password"
+ }
+ )
+ }
+ />
+ </>
+ )}
+
+ <Controller
+ control={control}
+ name="allowedAudience"
+ render={({ field, fieldState: { error } }) =>
+ renderField(
+ "identity-auth-template-allowed-audience",
+ "Allowed Audience (optional)",
+ field,
+ error,
+ { placeholder: "https://kubernetes.default.svc" }
+ )
+ }
+ />
+
+ {tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && (
+ <>
+ <Controller
+ control={control}
+ name="verifyTlsCertificate"
+ render={({ field: { value, onChange }, fieldState: { error } }) => {
+ const hasCaCert = Boolean(watch("caCert")?.length);
+ return (
+ <Field data-invalid={Boolean(error)}>
+ <div className="flex items-center gap-2">
+ <Switch
+ id="identity-auth-template-verify-tls"
+ checked={hasCaCert ? true : value}
+ onCheckedChange={onChange}
+ disabled={hasCaCert}
+ />
+ <FieldLabel
+ htmlFor="identity-auth-template-verify-tls"
+ className="mb-0 inline-flex items-center gap-1.5"
+ >
+ Verify TLS Certificate
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircleIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ {hasCaCert
+ ? "Verification is always on while a CA certificate is provided. To disable verification, clear the CA certificate field below."
+ : "When enabled, Infisical validates the Kubernetes API server's TLS certificate against the CA certificate provided below."}
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ </div>
+ <FieldError errors={[error]} />
+ </Field>
+ );
+ }}
+ />
+
+ <Controller
+ control={control}
+ name="caCert"
+ render={({ field, fieldState: { error } }) => {
+ const verifyTlsCertificate = watch("verifyTlsCertificate");
+ return (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel htmlFor="identity-auth-template-k8s-ca-certificate">
+ CA Certificate
+ </FieldLabel>
+ <TextArea
+ {...field}
+ id="identity-auth-template-k8s-ca-certificate"
+ placeholder="-----BEGIN CERTIFICATE----- ..."
+ aria-invalid={Boolean(error)}
+ onChange={(e) => {
+ field.onChange(e);
+ if (e.target.value.length > 0 && !verifyTlsCertificate) {
+ setValue("verifyTlsCertificate", true, {
+ shouldDirty: true,
+ shouldValidate: true
+ });
+ }
+ }}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ );
+ }}
+ />
+ </>
+ )}
+ </>
+ )}
</FieldGroup>
<SheetFooter className="border-t">
<Button
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplatesTable.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthTemplatesTable.tsx
index 04bc14f9d1..6523ee333d 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 {
+ MachineIdentityAuthMethod,
TEMPLATE_UI_LABELS,
useGetIdentityAuthTemplates
} from "@app/hooks/api/identityAuthTemplates";
@@ -200,7 +201,7 @@ export const IdentityAuthTemplatesTable = ({ handlePopUpOpen, onEmptyStateChange
)}
/>
</TableHead>
- <TableHead>URL</TableHead>
+ <TableHead>Host / URL</TableHead>
<TableHead className="w-5" />
</TableRow>
</TableHeader>
@@ -229,7 +230,11 @@ export const IdentityAuthTemplatesTable = ({ handlePopUpOpen, onEmptyStateChange
<TableCell>
<span className="uppercase">{template.authMethod}</span>
</TableCell>
- <TableCell isTruncatable>{template.templateFields.url}</TableCell>
+ <TableCell isTruncatable>
+ {template.authMethod === MachineIdentityAuthMethod.KUBERNETES
+ ? template.templateFields.kubernetesHost || "Gateway"
+ : template.templateFields.url}
+ </TableCell>
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx
index 465c8584f0..7687a77432 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx
@@ -13,6 +13,7 @@ import {
FieldError,
FieldGroup,
FieldLabel,
+ FilterableSelect,
GatewayPicker,
Input,
Select,
@@ -30,9 +31,10 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
-import { useOrganization, useSubscription } from "@app/context";
+import { useOrganization, useOrgPermission, useSubscription } from "@app/context";
import {
OrgGatewayPermissionActions,
+ OrgPermissionMachineIdentityAuthTemplateActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
import {
@@ -40,6 +42,7 @@ import {
DEFAULT_TRUSTED_IPS,
mapTrustedIpsFromServer,
superRefineAccessTokenTtl,
+ superRefineKubernetesConnectionFields,
trustedIpsSchema
} from "@app/helpers/identityAuthSchemas";
import { useScopeVariant } from "@app/hooks";
@@ -54,6 +57,8 @@ import {
useListAvailableAppConnections
} from "@app/hooks/api/appConnections/queries";
import { IdentityKubernetesAuthTokenReviewMode } from "@app/hooks/api/identities/types";
+import { MachineIdentityAuthMethod } from "@app/hooks/api/identityAuthTemplates";
+import { useGetAvailableTemplates } from "@app/hooks/api/identityAuthTemplates/queries";
import { VaultKubernetesAuthRole } from "@app/hooks/api/migration/types";
import { useCanUseOrgAppConnectionImport } from "@app/hooks/useCanUseAppConnectionImport";
import { usePopUp, UsePopUpState } from "@app/hooks/usePopUp";
@@ -67,6 +72,8 @@ import { VaultKubernetesAuthImportModal } from "./VaultKubernetesAuthImportModal
const buildSchema = (maxAccessTokenTTL: number) =>
z
.object({
+ scope: z.enum(["template", "custom"]),
+ templateId: z.string().optional(),
tokenReviewMode: z
.nativeEnum(IdentityKubernetesAuthTokenReviewMode)
.default(IdentityKubernetesAuthTokenReviewMode.Api),
@@ -85,59 +92,29 @@ const buildSchema = (maxAccessTokenTTL: number) =>
accessTokenTrustedIps: trustedIpsSchema
})
.superRefine((data, ctx) => {
- if (
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- !data.kubernetesHost?.length
- ) {
- ctx.addIssue({
- path: ["kubernetesHost"],
- code: z.ZodIssueCode.custom,
- message: "When token review mode is set to API, a Kubernetes host must be provided"
- });
- }
-
- if (
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&
- !data.gatewayId &&
- !data.gatewayPoolId
- ) {
- ctx.addIssue({
- path: ["gatewayId"],
- code: z.ZodIssueCode.custom,
- message:
- "When token review mode is set to Gateway, a gateway or gateway pool must be selected"
- });
+ if (data.scope === "template") {
+ if (!data.templateId) {
+ ctx.addIssue({
+ path: ["templateId"],
+ code: z.ZodIssueCode.custom,
+ message: "Template is required when using a template configuration"
+ });
+ }
+ return;
}
- if (
- data.verifyTlsCertificate &&
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- !data.caCert?.length
- ) {
- ctx.addIssue({
- path: ["caCert"],
- code: z.ZodIssueCode.custom,
- message: "A CA certificate is required when TLS certificate verification is enabled."
- });
- }
-
- if (
- data.verifyTlsCertificate === false &&
- data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- data.caCert?.length
- ) {
- ctx.addIssue({
- path: ["verifyTlsCertificate"],
- code: z.ZodIssueCode.custom,
- message:
- "TLS certificate verification cannot be disabled while a CA certificate is provided. Either remove the CA certificate or enable verification."
- });
- }
+ superRefineKubernetesConnectionFields(data, ctx);
})
.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"]>,
@@ -171,6 +148,17 @@ export const IdentityKubernetesAuthForm = ({
const { mutateAsync: addMutateAsync } = useAddIdentityKubernetesAuth();
const { mutateAsync: updateMutateAsync } = useUpdateIdentityKubernetesAuth();
const [tabValue, setTabValue] = useState<IdentityFormTab>(IdentityFormTab.Configuration);
+ const { permission } = useOrgPermission();
+
+ const canAttachTemplates = permission.can(
+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,
+ OrgPermissionSubjects.MachineIdentityAuthTemplate
+ );
+
+ const { data: templates, isPending: isTemplatesPending } = useGetAvailableTemplates(
+ MachineIdentityAuthMethod.KUBERNETES,
+ { enabled: canAttachTemplates && Boolean(subscription?.machineIdentityAuthTemplates) }
+ );
const { data } = useGetIdentityKubernetesAuth(identityId ?? "", {
enabled: isUpdate
@@ -202,11 +190,13 @@ export const IdentityKubernetesAuthForm = ({
reset,
watch,
setValue,
-
- formState: { isSubmitting }
+ clearErrors,
+ formState: { errors, isSubmitting }
} = useForm<FormData>({
resolver,
defaultValues: {
+ scope: "custom",
+ templateId: "",
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
kubernetesHost: "",
tokenReviewerJwt: "",
@@ -226,6 +216,8 @@ export const IdentityKubernetesAuthForm = ({
useEffect(() => {
if (data) {
reset({
+ scope: data.templateId ? "template" : "custom",
+ templateId: data.templateId || "",
tokenReviewMode: data.tokenReviewMode,
kubernetesHost: data.kubernetesHost,
tokenReviewerJwt: data.tokenReviewerJwt,
@@ -245,6 +237,8 @@ export const IdentityKubernetesAuthForm = ({
});
} else {
reset({
+ scope: "custom",
+ templateId: "",
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
kubernetesHost: "",
tokenReviewerJwt: "",
@@ -261,12 +255,46 @@ export const IdentityKubernetesAuthForm = ({
}
}, [data]);
+ const scope = watch("scope");
+ const selectedTemplateId = 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" ? selectedTemplateId : "custom")
+ ) ??
+ // while the template list is loading (or the linked template is missing from it), keep
+ // the picker controlled and visibly linked so the user cannot mistake it for unset
+ (scope === "template" && selectedTemplateId
+ ? { group: "Templates" as const, label: "Linked template", value: selectedTemplateId }
+ : undefined);
+
useEffect(() => {
onSubmittingChange?.(isSubmitting);
}, [isSubmitting, onSubmittingChange]);
const handleImportFromVault = (role: VaultKubernetesAuthRole) => {
try {
+ // importing a Vault role defines a custom configuration; drop any selected template
+ // so the imported connection values are actually submitted
+ setValue("scope", "custom");
+ setValue("templateId", "");
+
setValue("kubernetesHost", role.config.kubernetes_host, {
shouldDirty: true,
shouldTouch: true,
@@ -351,6 +379,8 @@ export const IdentityKubernetesAuthForm = ({
};
const onFormSubmit = async ({
+ scope: submissionScope,
+ templateId: submissionTemplateId,
kubernetesHost,
tokenReviewerJwt,
allowedNames,
@@ -368,56 +398,56 @@ export const IdentityKubernetesAuthForm = ({
}: FormData) => {
if (!identityId) return;
+ const basePayload = {
+ ...(projectId ? { projectId } : { organizationId: orgId }),
+ identityId,
+ allowedNames: allowedNames || "",
+ allowedNamespaces: allowedNamespaces || "",
+ accessTokenTTL: Number(accessTokenTTL),
+ accessTokenMaxTTL: Number(accessTokenMaxTTL),
+ accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit || "0"),
+ accessTokenTrustedIps
+ };
+
+ const customConfigPayload = {
+ ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api
+ ? {
+ kubernetesHost: kubernetesHost || ""
+ }
+ : {
+ kubernetesHost: null
+ }),
+ allowedAudience: allowedAudience || "",
+ gatewayId: gatewayPoolId ? null : gatewayId || null,
+ gatewayPoolId: gatewayPoolId || null,
+ verifyTlsCertificate,
+ tokenReviewMode
+ };
+
if (data) {
- await updateMutateAsync({
- ...(projectId ? { projectId } : { organizationId: orgId }),
- ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api
- ? {
- kubernetesHost: kubernetesHost || ""
- }
+ await updateMutateAsync(
+ submissionScope === "template"
+ ? { ...basePayload, templateId: submissionTemplateId }
: {
- kubernetesHost: null
- }),
- tokenReviewerJwt: tokenReviewerJwt || null,
- allowedNames,
- allowedNamespaces,
- allowedAudience,
- caCert,
- verifyTlsCertificate,
- identityId,
- gatewayId: gatewayPoolId ? null : gatewayId || null,
- gatewayPoolId: gatewayPoolId || null,
- tokenReviewMode,
- accessTokenTTL: Number(accessTokenTTL),
- accessTokenMaxTTL: Number(accessTokenMaxTTL),
- accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit || "0"),
- accessTokenTrustedIps
- });
- } else {
- await addMutateAsync({
- ...(projectId ? { projectId } : { organizationId: orgId }),
- identityId,
- ...(tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api
- ? {
- kubernetesHost: kubernetesHost || ""
+ ...basePayload,
+ ...customConfigPayload,
+ // unlink an existing template so the custom values are accepted
+ ...(data.templateId ? { templateId: null } : {}),
+ tokenReviewerJwt: tokenReviewerJwt || null,
+ caCert
}
+ );
+ } else {
+ await addMutateAsync(
+ submissionScope === "template"
+ ? { ...basePayload, templateId: submissionTemplateId }
: {
- kubernetesHost: null
- }),
- tokenReviewerJwt: tokenReviewerJwt || undefined,
- allowedNames: allowedNames || "",
- allowedNamespaces: allowedNamespaces || "",
- allowedAudience: allowedAudience || "",
- gatewayId: gatewayPoolId ? null : gatewayId || null,
- gatewayPoolId: gatewayPoolId || null,
- caCert: caCert || "",
- verifyTlsCertificate,
- tokenReviewMode,
- accessTokenTTL: Number(accessTokenTTL),
- accessTokenMaxTTL: Number(accessTokenMaxTTL),
- accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit || "0"),
- accessTokenTrustedIps
- });
+ ...basePayload,
+ ...customConfigPayload,
+ tokenReviewerJwt: tokenReviewerJwt || undefined,
+ caCert: caCert || ""
+ }
+ );
}
handlePopUpToggle("identityAuthMethod", false);
@@ -431,6 +461,7 @@ export const IdentityKubernetesAuthForm = ({
};
const tokenReviewMode = watch("tokenReviewMode");
+ const templateDisabledClass = scope === "template" ? "opacity-55" : "";
return (
<form
@@ -438,6 +469,8 @@ export const IdentityKubernetesAuthForm = ({
onSubmit={handleSubmit(onFormSubmit, (fields) => {
setTabValue(
[
+ "scope",
+ "templateId",
"kubernetesHost",
"tokenReviewerJwt",
"tokenReviewMode",
@@ -492,6 +525,89 @@ export const IdentityKubernetesAuthForm = ({
</Tooltip>
</div>
)}
+ {canAttachTemplates && (
+ <Controller
+ control={control}
+ name="scope"
+ render={({ field: { onChange }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="kubernetes-configuration">Configuration</FieldLabel>
+ <FilterableSelect<ConfigurationOption>
+ inputId="kubernetes-configuration"
+ value={selectedConfiguration}
+ options={configurationOptions}
+ groupBy="group"
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ placeholder="Select or search configurations..."
+ isLoading={isTemplatesPending}
+ 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(
+ "tokenReviewMode",
+ data?.tokenReviewMode || IdentityKubernetesAuthTokenReviewMode.Api
+ );
+ setValue("kubernetesHost", data?.kubernetesHost || "");
+ setValue("tokenReviewerJwt", data?.tokenReviewerJwt || "");
+ setValue(
+ "gatewayId",
+ data?.gatewayPoolId ? null : data?.gatewayId || null
+ );
+ setValue("gatewayPoolId", data?.gatewayPoolId || null);
+ setValue("caCert", data?.caCert || "");
+ setValue("verifyTlsCertificate", data?.verifyTlsCertificate ?? true);
+ setValue("allowedAudience", data?.allowedAudience || "");
+ 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",
+ "kubernetesHost",
+ "caCert",
+ "verifyTlsCertificate",
+ "tokenReviewerJwt",
+ "gatewayId",
+ "gatewayPoolId"
+ ]);
+ const fields = template.templateFields;
+ setValue(
+ "tokenReviewMode",
+ fields.tokenReviewMode || IdentityKubernetesAuthTokenReviewMode.Api
+ );
+ setValue("kubernetesHost", fields.kubernetesHost || "");
+ setValue("tokenReviewerJwt", fields.tokenReviewerJwt || "");
+ setValue(
+ "gatewayId",
+ fields.gatewayPoolId ? null : fields.gatewayId || null
+ );
+ setValue("gatewayPoolId", fields.gatewayPoolId || null);
+ setValue("caCert", fields.caCert || "");
+ setValue(
+ "verifyTlsCertificate",
+ fields.verifyTlsCertificate ?? Boolean(fields.caCert)
+ );
+ setValue("allowedAudience", fields.allowedAudience || "");
+ }}
+ />
+ <FieldError>{error?.message || errors.templateId?.message}</FieldError>
+ </Field>
+ )}
+ />
+ )}
<OrgPermissionCan
I={OrgGatewayPermissionActions.AttachGateways}
a={OrgPermissionSubjects.Gateway}
@@ -506,7 +622,7 @@ export const IdentityKubernetesAuthForm = ({
const gatewayIdVal = watch("gatewayId");
return (
- <Field>
+ <Field className={templateDisabledClass}>
<FieldLabel htmlFor="gatewayId">Gateway (optional)</FieldLabel>
<Tooltip>
<TooltipTrigger asChild>
@@ -527,7 +643,7 @@ export const IdentityKubernetesAuthForm = ({
);
}
}}
- isDisabled={!isAllowed}
+ isDisabled={!isAllowed || scope === "template"}
className="w-full"
/>
</div>
@@ -551,7 +667,7 @@ export const IdentityKubernetesAuthForm = ({
control={control}
name="tokenReviewMode"
render={({ field, fieldState: { error } }) => (
- <Field>
+ <Field className={templateDisabledClass}>
<FieldLabel
htmlFor="tokenReviewMode"
className="inline-flex items-center gap-1.5"
@@ -569,7 +685,11 @@ export const IdentityKubernetesAuthForm = ({
</TooltipContent>
</Tooltip>
</FieldLabel>
- <Select value={field.value} onValueChange={field.onChange}>
+ <Select
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled={scope === "template"}
+ >
<SelectTrigger id="tokenReviewMode" isError={Boolean(error)}>
<SelectValue placeholder="Select review mode" />
</SelectTrigger>
@@ -588,7 +708,7 @@ export const IdentityKubernetesAuthForm = ({
defaultValue="2592000"
name="kubernetesHost"
render={({ field, fieldState: { error } }) => (
- <Field>
+ <Field className={templateDisabledClass}>
<FieldLabel
htmlFor="kubernetesHost"
className="inline-flex items-center gap-1.5"
@@ -612,6 +732,7 @@ export const IdentityKubernetesAuthForm = ({
type="text"
value={field.value || ""}
autoComplete="off"
+ disabled={scope === "template"}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
@@ -625,7 +746,7 @@ export const IdentityKubernetesAuthForm = ({
control={control}
name="tokenReviewerJwt"
render={({ field, fieldState: { error } }) => (
- <Field>
+ <Field className={templateDisabledClass}>
<FieldLabel
htmlFor="tokenReviewerJwt"
className="inline-flex items-center gap-1.5"
@@ -649,7 +770,10 @@ export const IdentityKubernetesAuthForm = ({
id="tokenReviewerJwt"
type="password"
autoComplete="new-password"
- placeholder="eyJhbGciOiJSUzI1NiIs..."
+ placeholder={
+ scope === "template" ? "Defined in template" : "eyJhbGciOiJSUzI1NiIs..."
+ }
+ disabled={scope === "template"}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
@@ -757,7 +881,7 @@ export const IdentityKubernetesAuthForm = ({
defaultValue=""
name="allowedAudience"
render={({ field, fieldState: { error } }) => (
- <Field>
+ <Field className={templateDisabledClass}>
<FieldLabel
htmlFor="allowedAudience"
className="inline-flex items-center gap-1.5"
@@ -778,6 +902,7 @@ export const IdentityKubernetesAuthForm = ({
id="allowedAudience"
type="text"
placeholder="https://kubernetes.default.svc"
+ disabled={scope === "template"}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
@@ -792,14 +917,14 @@ export const IdentityKubernetesAuthForm = ({
render={({ field: { value, onChange }, fieldState: { error } }) => {
const hasCaCert = Boolean(watch("caCert")?.length);
return (
- <Field>
+ <Field className={templateDisabledClass}>
<div className="flex items-center gap-2">
<Switch
id="k8s-verify-tls-certificate"
variant={scopeVariant}
checked={hasCaCert ? true : value}
onCheckedChange={onChange}
- disabled={hasCaCert}
+ disabled={hasCaCert || scope === "template"}
/>
<FieldLabel
htmlFor="k8s-verify-tls-certificate"
@@ -849,7 +974,7 @@ export const IdentityKubernetesAuthForm = ({
render={({ field, fieldState: { error } }) => {
const verifyTlsCertificate = watch("verifyTlsCertificate");
return (
- <Field>
+ <Field className={templateDisabledClass}>
<FieldLabel htmlFor="caCert" className="inline-flex items-center gap-1.5">
CA Certificate
<Tooltip>
@@ -868,6 +993,7 @@ export const IdentityKubernetesAuthForm = ({
{...field}
id="caCert"
placeholder="-----BEGIN CERTIFICATE----- ..."
+ disabled={scope === "template"}
isError={Boolean(error)}
onChange={(e) => {
field.onChange(e);
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx
index a208110082..d493e1da29 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx
@@ -236,9 +236,6 @@ export const IdentityLdapAuthForm = ({
const { mutateAsync: addMutateAsync } = useAddIdentityLdapAuth();
const { mutateAsync: updateMutateAsync } = useUpdateIdentityLdapAuth();
const [tabValue, setTabValue] = useState<IdentityFormTab>(IdentityFormTab.Configuration);
- const { data: templates, isPending: isTemplatesPending } = useGetAvailableTemplates(
- MachineIdentityAuthMethod.LDAP
- );
const { permission } = useOrgPermission();
const canAttachTemplates = permission.can(
@@ -246,6 +243,11 @@ export const IdentityLdapAuthForm = ({
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
+ const { data: templates, isPending: isTemplatesPending } = useGetAvailableTemplates(
+ MachineIdentityAuthMethod.LDAP,
+ { enabled: canAttachTemplates && Boolean(subscription?.machineIdentityAuthTemplates) }
+ );
+
const { data } = useGetIdentityLdapAuth(identityId ?? "", {
enabled: isUpdate
});
@@ -288,7 +290,7 @@ export const IdentityLdapAuthForm = ({
() => [
{
group: "Configuration",
- label: "Custom configuration",
+ label: "Custom Configuration",
value: "custom"
},
...(templates ?? []).map((template) => ({
@@ -564,11 +566,16 @@ export const IdentityLdapAuthForm = ({
onChange("template");
setValue("templateId", template.id);
clearErrors("templateId");
- setValue("url", template.templateFields.url);
- setValue("bindDN", template.templateFields.bindDN);
- setValue("bindPass", template.templateFields.bindPass);
- setValue("searchBase", template.templateFields.searchBase);
- setValue("ldapCaCertificate", template.templateFields.ldapCaCertificate);
+ setValue("url", template.templateFields.url ?? "");
+ setValue("bindDN", template.templateFields.bindDN ?? "");
+ // bindPass is write-only: the picker feed never returns it, and the
+ // attach flow resolves it server-side from the template
+ setValue("bindPass", template.templateFields.bindPass ?? "");
+ setValue("searchBase", template.templateFields.searchBase ?? "");
+ setValue(
+ "ldapCaCertificate",
+ template.templateFields.ldapCaCertificate ?? ""
+ );
}}
/>
<FieldError>{error?.message || errors.templateId?.message}</FieldError>