Skip to content

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

improvement: address feedback

Scott Wilson0177cf28793d
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 95a4fea088..88325b3476 100644
--- a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
+++ b/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
@@ -37,7 +37,11 @@ const IdentityKubernetesAuthResponseSchema = IdentityKubernetesAuthsSchema.pick(
gatewayId: true,
gatewayPoolId: true,
verifyTlsCertificate: true,
- templateId: true
+ templateId: true,
+ // template-sourced JWTs read back as "" (write-only), so this flag is the only way a
+ // client can tell "no stored JWT" from "hidden JWT that must be kept, replaced, or
+ // explicitly cleared with tokenReviewerJwt: null"
+ isTokenReviewerJwtTemplateSourced: true
}).extend({
caCert: z.string(),
tokenReviewerJwt: z.string().optional().nullable()
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
new file mode 100644
index 0000000000..98a348714b
--- /dev/null
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
@@ -0,0 +1,222 @@
+import { createMongoAbility } from "@casl/ability";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { IdentityAuthMethod } from "@app/db/schemas";
+
+import { identityKubernetesAuthServiceFactory } from "./identity-kubernetes-auth-service";
+import { IdentityKubernetesAuthTokenReviewMode } from "./identity-kubernetes-auth-types";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ isDevelopmentMode: false, ALLOW_INTERNAL_IP_CONNECTIONS: false })
+}));
+
+// the real logger is initialized at server boot; the connectivity log lines on the
+// happy path would otherwise dereference undefined
+vi.mock("@app/lib/logger", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@app/lib/logger")>();
+ return { ...actual, logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } };
+});
+
+vi.mock("../super-admin/super-admin-fns", () => ({
+ validateIdentityUpdateForSuperAdminPrivileges: vi.fn()
+}));
+
+// keep the pure cross-field checks real and stub only the outbound connectivity probes,
+// so the suite exercises the actual validation without touching the network
+vi.mock("./identity-kubernetes-auth-validators", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./identity-kubernetes-auth-validators")>();
+ return {
+ ...actual,
+ validateKubernetesHostConnectivity: vi.fn().mockResolvedValue(undefined),
+ validateTokenReviewerPermissions: vi.fn().mockResolvedValue(undefined)
+ };
+});
+
+const ORG_ID = "org-id";
+const IDENTITY_ID = "identity-id";
+const TEMPLATE_ID = "template-id";
+const PRIVATE_HOST = "https://10.0.0.1";
+// a literal IP keeps the suite hermetic: blockLocalAndPrivateIpAddresses skips the DNS lookup
+const PUBLIC_HOST = "https://8.8.8.8";
+
+const NO_GATEWAY = { gatewayId: null, gatewayV2Id: null, gatewayPoolId: null };
+
+const createService = ({
+ templateBlobFields = {
+ kubernetesHost: PUBLIC_HOST,
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
+ tokenReviewerJwt: "reviewer-jwt",
+ allowedAudience: ""
+ },
+ templateGatewayColumns = NO_GATEWAY,
+ identityAuthMethods = [] as string[]
+} = {}) => {
+ const templateRow = {
+ id: TEMPLATE_ID,
+ orgId: ORG_ID,
+ name: "auth-template",
+ authMethod: "kubernetes",
+ // the fake cipher pair below round-trips plaintext, so the "encrypted" blob is the JSON
+ templateFields: Buffer.from(JSON.stringify(templateBlobFields)),
+ ...templateGatewayColumns
+ };
+
+ const storedAuthRow = {
+ id: "k8s-auth-id",
+ identityId: IDENTITY_ID,
+ templateId: null,
+ accessTokenTTL: 0,
+ accessTokenMaxTTL: 0,
+ accessTokenNumUsesLimit: 0,
+ accessTokenTrustedIps: [],
+ kubernetesHost: PUBLIC_HOST,
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
+ allowedAudience: "",
+ isTokenReviewerJwtTemplateSourced: false,
+ verifyTlsCertificate: false,
+ encryptedKubernetesCaCertificate: null,
+ encryptedKubernetesTokenReviewerJwt: null,
+ ...NO_GATEWAY
+ };
+
+ const identityKubernetesAuthDAL = {
+ create: vi.fn().mockImplementation((data: Record<string, unknown>) => ({ id: "k8s-auth-id", ...data })),
+ findOne: vi.fn().mockResolvedValue(storedAuthRow),
+ updateById: vi.fn().mockImplementation((id: string, data: Record<string, unknown>) => ({
+ ...storedAuthRow,
+ ...data
+ })),
+ delete: vi.fn(),
+ transaction: vi.fn().mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) => cb({}))
+ };
+
+ const service = identityKubernetesAuthServiceFactory({
+ identityDAL: { findById: vi.fn() },
+ identityKubernetesAuthDAL,
+ identityAccessTokenDAL: { delete: vi.fn() },
+ identityAuthTemplateDAL: { findByIdAndOrgId: vi.fn().mockResolvedValue(templateRow) },
+ membershipIdentityDAL: {
+ findOne: vi.fn(),
+ update: vi.fn(),
+ getIdentityById: vi.fn().mockResolvedValue({
+ scopeOrgId: ORG_ID,
+ identity: { id: IDENTITY_ID, orgId: ORG_ID, projectId: null, authMethods: identityAuthMethods }
+ })
+ },
+ keyStore: { setItemWithExpiryNX: vi.fn() },
+ permissionService: {
+ getOrgPermission: vi
+ .fn()
+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) }),
+ getProjectPermission: vi.fn()
+ },
+ licenseService: {
+ getPlan: vi.fn().mockResolvedValue({
+ machineIdentityAuthTemplates: true,
+ gateway: true,
+ gatewayPool: true,
+ ipAllowlisting: true
+ })
+ },
+ kmsService: {
+ createCipherPairWithDataKey: vi.fn().mockResolvedValue({
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ })
+ },
+ gatewayService: {},
+ gatewayV2Service: {},
+ gatewayDAL: { find: vi.fn().mockResolvedValue([]) },
+ gatewayV2DAL: { find: vi.fn().mockResolvedValue([]) },
+ gatewayPoolService: { pickHealthyGateway: vi.fn(), runWithPoolFailover: vi.fn() },
+ gatewayPoolDAL: { findById: vi.fn().mockResolvedValue(null) },
+ orgDAL: { findById: vi.fn(), findOne: vi.fn(), findEffectiveOrgMembership: vi.fn() },
+ identityAccessTokenService: {
+ issueIdentityAccessToken: vi.fn(),
+ revokeTokensForIdentityAuthMethod: vi.fn(),
+ invalidateTrustedIpsCache: vi.fn()
+ }
+ } as unknown as Parameters<typeof identityKubernetesAuthServiceFactory>[0]);
+
+ return { service, identityKubernetesAuthDAL };
+};
+
+const baseActor = {
+ actor: "user",
+ actorId: "actor-id",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+};
+
+const attachWithTemplate = (service: ReturnType<typeof createService>["service"]) =>
+ service.attachKubernetesAuth({
+ ...baseActor,
+ identityId: IDENTITY_ID,
+ templateId: TEMPLATE_ID,
+ allowedNames: "",
+ allowedNamespaces: "",
+ accessTokenTTL: 7200,
+ accessTokenMaxTTL: 7200,
+ accessTokenNumUsesLimit: 0,
+ accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }]
+ } as unknown as Parameters<typeof service.attachKubernetesAuth>[0]);
+
+const updateWithTemplate = (service: ReturnType<typeof createService>["service"]) =>
+ service.updateKubernetesAuth({
+ ...baseActor,
+ identityId: IDENTITY_ID,
+ templateId: TEMPLATE_ID
+ } as unknown as Parameters<typeof service.updateKubernetesAuth>[0]);
+
+describe("identityKubernetesAuthServiceFactory template attach validation", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("rejects attaching a gateway-mode template whose gateway was deleted", async () => {
+ // ON DELETE SET NULL clears the template's gateway columns out-of-band, leaving a config
+ // that would attach cleanly and then fail every login
+ const { service, identityKubernetesAuthDAL } = createService({
+ templateBlobFields: { tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Gateway, allowedAudience: "" },
+ templateGatewayColumns: NO_GATEWAY
+ });
+
+ await expect(attachWithTemplate(service)).rejects.toThrow("Cannot use auth template 'auth-template'");
+ expect(identityKubernetesAuthDAL.create).not.toHaveBeenCalled();
+ });
+
+ it("rejects attaching a template whose private host lost its gateway", async () => {
+ const { service, identityKubernetesAuthDAL } = createService({
+ templateBlobFields: {
+ kubernetesHost: PRIVATE_HOST,
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
+ tokenReviewerJwt: "reviewer-jwt",
+ allowedAudience: ""
+ },
+ templateGatewayColumns: NO_GATEWAY
+ });
+
+ await expect(attachWithTemplate(service)).rejects.toThrow("Local IPs not allowed as URL");
+ expect(identityKubernetesAuthDAL.create).not.toHaveBeenCalled();
+ });
+
+ it("attaches a healthy direct-dial template", async () => {
+ const { service, identityKubernetesAuthDAL } = createService();
+
+ await attachWithTemplate(service);
+
+ expect(identityKubernetesAuthDAL.create).toHaveBeenCalledWith(
+ expect.objectContaining({ templateId: TEMPLATE_ID, kubernetesHost: PUBLIC_HOST }),
+ expect.anything()
+ );
+ });
+
+ it("rejects linking a degraded gateway-mode template on update", async () => {
+ const { service, identityKubernetesAuthDAL } = createService({
+ templateBlobFields: { tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Gateway, allowedAudience: "" },
+ templateGatewayColumns: NO_GATEWAY,
+ identityAuthMethods: [IdentityAuthMethod.KUBERNETES_AUTH]
+ });
+
+ await expect(updateWithTemplate(service)).rejects.toThrow("Cannot use auth template 'auth-template'");
+ expect(identityKubernetesAuthDAL.updateById).not.toHaveBeenCalled();
+ });
+});
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 6c287a0e0a..506784de9b 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
@@ -60,6 +60,7 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -85,6 +86,8 @@ import {
} from "./identity-kubernetes-auth-types";
import {
GatewayRequestExecutor,
+ TKubernetesConnectionFields,
+ validateKubernetesConnectionFields,
validateKubernetesHostConnectivity,
validateTokenReviewerPermissions
} from "./identity-kubernetes-auth-validators";
@@ -310,6 +313,24 @@ export const identityKubernetesAuthServiceFactory = ({
return storedVerify ?? false;
};
+ const $validateTemplateSourcedConnection = async (templateName: string, fields: TKubernetesConnectionFields) => {
+ const issues = validateKubernetesConnectionFields(fields);
+ if (issues.length > 0) {
+ throw new BadRequestError({
+ message: `Cannot use auth template '${templateName}': ${issues[0].message}. The template's gateway or gateway pool may have been deleted; update the template's connection settings and try again.`
+ });
+ }
+ if (
+ (fields.tokenReviewMode ?? IdentityKubernetesAuthTokenReviewMode.Api) ===
+ IdentityKubernetesAuthTokenReviewMode.Api &&
+ fields.kubernetesHost &&
+ !fields.gatewayId &&
+ !fields.gatewayPoolId
+ ) {
+ await blockLocalAndPrivateIpAddresses(fields.kubernetesHost);
+ }
+ };
+
const login = async ({ identityId, jwt: serviceAccountJwt, organizationSlug }: TLoginKubernetesAuthDTO) => {
const authMetricStartTime = performance.now();
const appCfg = getConfig();
@@ -902,12 +923,19 @@ export const identityKubernetesAuthServiceFactory = ({
caCert = templateFields.caCert || undefined;
tokenReviewerJwt = templateFields.tokenReviewerJwt || undefined;
tokenReviewMode = templateFields.tokenReviewMode;
- // the template's gateway lives in columns, not the encrypted fields, so it can carry a
- // foreign key and clear itself in step with the columns copied onto this row
gatewayId = template.gatewayV2Id ?? template.gatewayId ?? null;
gatewayPoolId = template.gatewayPoolId ?? null;
verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
allowedAudience = templateFields.allowedAudience ?? "";
+
+ await $validateTemplateSourcedConnection(template.name, {
+ tokenReviewMode,
+ kubernetesHost,
+ caCert,
+ verifyTlsCertificate,
+ gatewayId,
+ gatewayPoolId
+ });
} else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && !kubernetesHost) {
throw new BadRequestError({
message: "When token review mode is set to API, a Kubernetes host must be provided"
@@ -1247,6 +1275,15 @@ export const identityKubernetesAuthServiceFactory = ({
gatewayPoolId = template.gatewayPoolId ?? null;
verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
allowedAudience = templateFields.allowedAudience ?? "";
+
+ await $validateTemplateSourcedConnection(template.name, {
+ tokenReviewMode,
+ kubernetesHost,
+ caCert,
+ verifyTlsCertificate,
+ gatewayId,
+ gatewayPoolId
+ });
} else if (templateId === undefined && identityKubernetesAuth.templateId) {
const hasTemplateManagedFieldChanges =
kubernetesHost !== undefined ||
diff --git a/frontend/src/components/v3/generic/Select/Select.tsx b/frontend/src/components/v3/generic/Select/Select.tsx
index bc873e8491..576f02c798 100644
--- a/frontend/src/components/v3/generic/Select/Select.tsx
+++ b/frontend/src/components/v3/generic/Select/Select.tsx
@@ -60,7 +60,7 @@ function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.V
}
const selectTriggerVariants = cva(
- "flex w-fit !cursor-pointer items-center justify-between gap-1.5 rounded-md border border-border bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap text-foreground select-none disabled:cursor-not-allowed disabled:opacity-50 data-placeholder:text-muted data-[size=default]:h-9 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 *:data-[slot=select-value]:truncate [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&>span]:truncate",
+ "flex w-fit !cursor-pointer items-center justify-between gap-1.5 rounded-md border border-border bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap text-foreground select-none disabled:!cursor-not-allowed disabled:opacity-50 data-placeholder:text-muted data-[size=default]:h-9 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 *:data-[slot=select-value]:truncate [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&>span]:truncate",
{
variants: {
variant: {
diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.ts
index 07326f5dcc..516b6df8a5 100644
--- a/frontend/src/hooks/api/identities/types.ts
+++ b/frontend/src/hooks/api/identities/types.ts
@@ -507,6 +507,8 @@ export type IdentityKubernetesAuth = {
templateId?: string | null;
kubernetesHost: string;
tokenReviewerJwt: string;
+ // template-sourced JWTs read back as ""; this flag marks that a hidden JWT is stored
+ isTokenReviewerJwtTemplateSourced?: boolean;
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode;
allowedNamespaces: string;
allowedNames: string;
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 08aa1e063d..97fd5a8e37 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
@@ -42,6 +42,7 @@ import {
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
import { superRefineKubernetesConnectionFields } from "@app/helpers/identityAuthSchemas";
+import { IdentityAuthMethod } from "@app/hooks/api";
import { IdentityKubernetesAuthTokenReviewMode } from "@app/hooks/api/identities/types";
import {
type IdentityAuthTemplate,
@@ -53,9 +54,24 @@ import {
} from "@app/hooks/api/identityAuthTemplates";
import { UsePopUpState } from "@app/hooks/usePopUp";
-const authMethods = [
- { label: "LDAP Auth", value: MachineIdentityAuthMethod.LDAP },
- { label: "Kubernetes Auth", value: MachineIdentityAuthMethod.KUBERNETES }
+import { identityAuthMethodOptions } from "./IdentityAuthMethodModalContent";
+
+// reuse the identity auth method icons so the template pickers and tables cannot
+// drift apart from the direct identity auth presentation
+const getMethodIcon = (method: IdentityAuthMethod) =>
+ identityAuthMethodOptions.find(({ value }) => value === method)?.icon;
+
+export const templateAuthMethods = [
+ {
+ label: "LDAP Auth",
+ value: MachineIdentityAuthMethod.LDAP,
+ icon: getMethodIcon(IdentityAuthMethod.LDAP_AUTH)
+ },
+ {
+ label: "Kubernetes Auth",
+ value: MachineIdentityAuthMethod.KUBERNETES,
+ icon: getMethodIcon(IdentityAuthMethod.KUBERNETES_AUTH)
+ }
];
const schema = z
@@ -367,9 +383,12 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
<SelectValue placeholder="Select auth method..." />
</SelectTrigger>
<SelectContent position="popper">
- {authMethods.map(({ label, value }) => (
+ {templateAuthMethods.map(({ label, value, icon }) => (
<SelectItem key={value} value={value}>
- {label}
+ <span className="flex items-center gap-2">
+ {icon}
+ {label}
+ </span>
</SelectItem>
))}
</SelectContent>
@@ -603,6 +622,7 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
id="identity-auth-template-clear-token-reviewer-jwt"
checked={value}
onCheckedChange={onChange}
+ variant={isSubOrganization ? "sub-org" : "org"}
/>
<FieldLabel
htmlFor="identity-auth-template-clear-token-reviewer-jwt"
@@ -651,6 +671,7 @@ export const IdentityAuthTemplateModal = ({ popUp, handlePopUpToggle }: Props) =
checked={hasCaCert ? true : value}
onCheckedChange={onChange}
disabled={hasCaCert}
+ variant={isSubOrganization ? "sub-org" : "org"}
/>
<FieldLabel
htmlFor="identity-auth-template-verify-tls"
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 daec373481..d11b140db6 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
@@ -51,6 +51,8 @@ import {
} from "@app/hooks/api/identityAuthTemplates";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { templateAuthMethods } from "./IdentityAuthTemplateModal";
+
enum TemplatesOrderBy {
Name = "name",
AuthMethod = "authMethod"
@@ -224,77 +226,89 @@ export const IdentityAuthTemplatesTable = ({ handlePopUpOpen, onEmptyStateChange
</TableRow>
))}
{!isPending &&
- templates?.map((template) => (
- <TableRow key={`template-${template.id}`}>
- <TableCell isTruncatable>{template.name}</TableCell>
- <TableCell>
- <span className="uppercase">{template.authMethod}</span>
- </TableCell>
- <TableCell isTruncatable>
- {template.authMethod === MachineIdentityAuthMethod.KUBERNETES
- ? template.templateFields.kubernetesHost || "Gateway"
- : template.templateFields.url}
- </TableCell>
- <TableCell variant="action">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton variant="ghost" size="xs" onClick={(e) => e.stopPropagation()}>
- <MoreHorizontalIcon />
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("viewUsages", { template });
- }}
- >
- <EyeIcon />
- {TEMPLATE_UI_LABELS.VIEW_USAGES}
- </DropdownMenuItem>
- <OrgPermissionCan
- I={OrgPermissionMachineIdentityAuthTemplateActions.EditTemplates}
- a={OrgPermissionSubjects.MachineIdentityAuthTemplate}
- >
- {(isAllowed) => (
- <DropdownMenuItem
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("editTemplate", { template });
- }}
- isDisabled={!isAllowed}
- >
- <EditIcon />
- {TEMPLATE_UI_LABELS.EDIT_TEMPLATE}
- </DropdownMenuItem>
- )}
- </OrgPermissionCan>
- <OrgPermissionCan
- I={OrgPermissionMachineIdentityAuthTemplateActions.DeleteTemplates}
- a={OrgPermissionSubjects.MachineIdentityAuthTemplate}
- >
- {(isAllowed) => (
- <DropdownMenuItem
- variant="danger"
- onClick={(e) => {
- e.stopPropagation();
- handlePopUpOpen("deleteTemplate", {
- templateId: template.id,
- name: template.name
- });
- }}
- isDisabled={!isAllowed}
- >
- <TrashIcon />
- {TEMPLATE_UI_LABELS.DELETE_TEMPLATE}
- </DropdownMenuItem>
- )}
- </OrgPermissionCan>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- ))}
+ templates?.map((template) => {
+ const methodOption = templateAuthMethods.find(
+ ({ value }) => value === template.authMethod
+ );
+ return (
+ <TableRow key={`template-${template.id}`}>
+ <TableCell isTruncatable>{template.name}</TableCell>
+ <TableCell>
+ <span className="flex items-center gap-2">
+ {methodOption?.icon}
+ {methodOption?.label ?? template.authMethod}
+ </span>
+ </TableCell>
+ <TableCell isTruncatable>
+ {template.authMethod === MachineIdentityAuthMethod.KUBERNETES
+ ? template.templateFields.kubernetesHost || "Gateway"
+ : template.templateFields.url}
+ </TableCell>
+ <TableCell variant="action">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <MoreHorizontalIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("viewUsages", { template });
+ }}
+ >
+ <EyeIcon />
+ {TEMPLATE_UI_LABELS.VIEW_USAGES}
+ </DropdownMenuItem>
+ <OrgPermissionCan
+ I={OrgPermissionMachineIdentityAuthTemplateActions.EditTemplates}
+ a={OrgPermissionSubjects.MachineIdentityAuthTemplate}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("editTemplate", { template });
+ }}
+ isDisabled={!isAllowed}
+ >
+ <EditIcon />
+ {TEMPLATE_UI_LABELS.EDIT_TEMPLATE}
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
+ <OrgPermissionCan
+ I={OrgPermissionMachineIdentityAuthTemplateActions.DeleteTemplates}
+ a={OrgPermissionSubjects.MachineIdentityAuthTemplate}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ variant="danger"
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePopUpOpen("deleteTemplate", {
+ templateId: template.id,
+ name: template.name
+ });
+ }}
+ isDisabled={!isAllowed}
+ >
+ <TrashIcon />
+ {TEMPLATE_UI_LABELS.DELETE_TEMPLATE}
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ );
+ })}
</TableBody>
</Table>
{totalCount > 0 && (
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 c15ebc8c7e..b729253481 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
@@ -9,7 +9,10 @@ import { createNotification } from "@app/components/notifications";
import { OrgPermissionCan } from "@app/components/permissions";
import {
Button,
+ Checkbox,
Field,
+ FieldContent,
+ FieldDescription,
FieldError,
FieldGroup,
FieldLabel,
@@ -79,6 +82,7 @@ const buildSchema = (maxAccessTokenTTL: number) =>
.default(IdentityKubernetesAuthTokenReviewMode.Api),
kubernetesHost: z.string().optional().nullable(),
tokenReviewerJwt: z.string().optional(),
+ removeTemplateSourcedJwt: z.boolean().optional(),
gatewayId: z.string().optional().nullable(),
gatewayPoolId: z.string().optional().nullable(),
allowedNames: z.string(),
@@ -155,7 +159,7 @@ export const IdentityKubernetesAuthForm = ({
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
- const { data: templates, isPending: isTemplatesPending } = useGetAvailableTemplates(
+ const { data: templates, isLoading: isTemplatesLoading } = useGetAvailableTemplates(
MachineIdentityAuthMethod.KUBERNETES,
{ enabled: canAttachTemplates && Boolean(subscription?.machineIdentityAuthTemplates) }
);
@@ -200,6 +204,7 @@ export const IdentityKubernetesAuthForm = ({
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
kubernetesHost: "",
tokenReviewerJwt: "",
+ removeTemplateSourcedJwt: false,
allowedNames: "",
allowedNamespaces: "",
gatewayId: "",
@@ -221,6 +226,7 @@ export const IdentityKubernetesAuthForm = ({
tokenReviewMode: data.tokenReviewMode,
kubernetesHost: data.kubernetesHost,
tokenReviewerJwt: data.tokenReviewerJwt,
+ removeTemplateSourcedJwt: false,
allowedNames: data.allowedNames,
allowedNamespaces: data.allowedNamespaces,
allowedAudience: data.allowedAudience,
@@ -242,6 +248,7 @@ export const IdentityKubernetesAuthForm = ({
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
kubernetesHost: "",
tokenReviewerJwt: "",
+ removeTemplateSourcedJwt: false,
allowedNames: "",
allowedNamespaces: "",
allowedAudience: "",
@@ -383,6 +390,7 @@ export const IdentityKubernetesAuthForm = ({
templateId: submissionTemplateId,
kubernetesHost,
tokenReviewerJwt,
+ removeTemplateSourcedJwt,
allowedNames,
allowedNamespaces,
allowedAudience,
@@ -425,6 +433,14 @@ export const IdentityKubernetesAuthForm = ({
};
if (data) {
+ // a blank field can only mean "clear" when the stored JWT was readable and
+ // prefilled; template-sourced JWTs read back as "" so blank must keep them, and
+ // removing one takes the explicit checkbox
+ let tokenReviewerJwtUpdate: string | null | undefined =
+ tokenReviewerJwt || (data.tokenReviewerJwt ? null : undefined);
+ if (removeTemplateSourcedJwt) {
+ tokenReviewerJwtUpdate = null;
+ }
await updateMutateAsync(
submissionScope === "template"
? { ...basePayload, templateId: submissionTemplateId }
@@ -433,9 +449,7 @@ export const IdentityKubernetesAuthForm = ({
...customConfigPayload,
// unlink an existing template so the custom values are accepted
...(data.templateId ? { templateId: null } : {}),
- // a blank field can only mean "clear" when the stored JWT was readable and
- // prefilled; template-sourced JWTs read back as "" so blank must keep them
- tokenReviewerJwt: tokenReviewerJwt || (data.tokenReviewerJwt ? null : undefined),
+ tokenReviewerJwt: tokenReviewerJwtUpdate,
caCert
}
);
@@ -463,8 +477,17 @@ export const IdentityKubernetesAuthForm = ({
};
const tokenReviewMode = watch("tokenReviewMode");
+ const isRemovingTemplateJwt = watch("removeTemplateSourcedJwt");
+ const hasTemplateSourcedJwt = Boolean(data?.isTokenReviewerJwtTemplateSourced);
const templateDisabledClass = scope === "template" ? "opacity-55" : "";
+ let tokenReviewerJwtPlaceholder = "eyJhbGciOiJSUzI1NiIs...";
+ if (scope === "template") {
+ tokenReviewerJwtPlaceholder = "Defined in template";
+ } else if (hasTemplateSourcedJwt) {
+ tokenReviewerJwtPlaceholder = "Leave blank to keep the stored JWT";
+ }
+
return (
<form
id={IDENTITY_AUTH_FORM_ID}
@@ -542,7 +565,7 @@ export const IdentityKubernetesAuthForm = ({
getOptionLabel={(option) => option.label}
getOptionValue={(option) => option.value}
placeholder="Select or search configurations..."
- isLoading={isTemplatesPending}
+ isLoading={isTemplatesLoading}
isError={Boolean(error || errors.templateId)}
onChange={(option) => {
const selectedOption = option as ConfigurationOption | null;
@@ -772,10 +795,8 @@ export const IdentityKubernetesAuthForm = ({
id="tokenReviewerJwt"
type="password"
autoComplete="new-password"
- placeholder={
- scope === "template" ? "Defined in template" : "eyJhbGciOiJSUzI1NiIs..."
- }
- disabled={scope === "template"}
+ placeholder={tokenReviewerJwtPlaceholder}
+ disabled={scope === "template" || isRemovingTemplateJwt}
isError={Boolean(error)}
/>
<FieldError>{error?.message}</FieldError>
@@ -783,6 +804,39 @@ export const IdentityKubernetesAuthForm = ({
)}
/>
)}
+ {scope === "custom" && hasTemplateSourcedJwt && (
+ <Controller
+ control={control}
+ name="removeTemplateSourcedJwt"
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal">
+ <Checkbox
+ id="removeTemplateSourcedJwt"
+ variant={scopeVariant}
+ isChecked={Boolean(value)}
+ onCheckedChange={(next) => {
+ const checked = next === true;
+ onChange(checked);
+ if (checked) setValue("tokenReviewerJwt", "");
+ }}
+ />
+ <FieldContent>
+ <FieldLabel htmlFor="removeTemplateSourcedJwt" className="cursor-pointer">
+ Remove template-sourced token reviewer JWT
+ </FieldLabel>
+ <FieldDescription>
+ This identity stores a write-only token reviewer JWT copied from its auth
+ template. Its connection settings cannot be changed while the JWT is kept.
+ Check to remove it on save
+ {tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api
+ ? ", or enter a new JWT above to replace it."
+ : "."}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
<Controller
control={control}
defaultValue=""
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 d493e1da29..3190c46dc8 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
@@ -243,7 +243,7 @@ export const IdentityLdapAuthForm = ({
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
- const { data: templates, isPending: isTemplatesPending } = useGetAvailableTemplates(
+ const { data: templates, isLoading: isTemplatesLoading } = useGetAvailableTemplates(
MachineIdentityAuthMethod.LDAP,
{ enabled: canAttachTemplates && Boolean(subscription?.machineIdentityAuthTemplates) }
);
@@ -542,7 +542,7 @@ export const IdentityLdapAuthForm = ({
getOptionLabel={(option) => option.label}
getOptionValue={(option) => option.value}
placeholder="Select or search configurations..."
- isLoading={isTemplatesPending}
+ isLoading={isTemplatesLoading}
isError={Boolean(error || errors.templateId)}
onChange={(option) => {
const selectedOption = option as ConfigurationOption | null;
diff --git a/frontend/src/views/IdentityAuthMethods/content/IdentityKubernetesAuthContent.tsx b/frontend/src/views/IdentityAuthMethods/content/IdentityKubernetesAuthContent.tsx
index 2f08e44fe7..75d1e5d488 100644
--- a/frontend/src/views/IdentityAuthMethods/content/IdentityKubernetesAuthContent.tsx
+++ b/frontend/src/views/IdentityAuthMethods/content/IdentityKubernetesAuthContent.tsx
@@ -1,6 +1,6 @@
-import { useMemo } from "react";
+import { ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
-import { BanIcon, EyeIcon } from "lucide-react";
+import { BanIcon, EyeIcon, EyeOffIcon } from "lucide-react";
import {
Badge,
@@ -14,19 +14,43 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
+import { useOrgPermission, useSubscription } from "@app/context";
+import {
+ OrgPermissionMachineIdentityAuthTemplateActions,
+ OrgPermissionSubjects
+} from "@app/context/OrgPermissionContext/types";
import { gatewaysQueryKeys, useGetIdentityKubernetesAuth } from "@app/hooks/api";
+import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/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 { IdentityAuthAccessTokenFields, IdentityAuthFieldDisplay } from "../helpers";
import { ViewAuthMethodProps } from "../types";
export const IdentityKubernetesAuthContent = ({ identityId }: ViewAuthMethodProps) => {
+ const { subscription } = useSubscription();
+ const { permission } = useOrgPermission();
+
+ const canAttachTemplates = permission.can(
+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,
+ OrgPermissionSubjects.MachineIdentityAuthTemplate
+ );
+
const { data: gateways } = useQuery(gatewaysQueryKeys.list());
+ const { data: pools } = useQuery({
+ ...gatewayPoolsQueryKeys.list(),
+ enabled: Boolean(subscription?.gatewayPool)
+ });
const { data, isPending } = useGetIdentityKubernetesAuth(identityId);
- const selectedGateway = useMemo(() => {
- return gateways?.find((gateway) => gateway.id === data?.gatewayId) || null;
- }, [gateways, data?.gatewayId]);
+ const { data: templates } = useGetAvailableTemplates(MachineIdentityAuthMethod.KUBERNETES, {
+ enabled:
+ canAttachTemplates &&
+ Boolean(subscription?.machineIdentityAuthTemplates) &&
+ Boolean(data?.templateId)
+ });
if (isPending) {
return <PageLoader />;
@@ -45,8 +69,64 @@ export const IdentityKubernetesAuthContent = ({ identityId }: ViewAuthMethodProp
);
}
+ const linkedTemplateName = templates?.find((template) => template.id === data.templateId)?.name;
+ const configurationLabel = data.templateId
+ ? (linkedTemplateName ?? "Linked template")
+ : "Custom Configuration";
+
+ const reviewModeLabel =
+ data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway
+ ? "Gateway as Reviewer"
+ : "Manual Token Reviewer JWT (API)";
+
+ let gatewayDisplay: string | null = null;
+ if (data.gatewayPoolId) {
+ gatewayDisplay =
+ pools?.find((pool) => pool.id === data.gatewayPoolId)?.name ?? data.gatewayPoolId;
+ } else if (data.gatewayId) {
+ gatewayDisplay =
+ gateways?.find((gateway) => gateway.id === data.gatewayId)?.name ?? data.gatewayId;
+ }
+
+ // template-sourced JWTs read back as "" (write-only), so truthiness of the value alone
+ // would claim "Not set" for an identity that stores and uses one at login
+ let tokenReviewerJwtDisplay: ReactNode = null;
+ if (data.isTokenReviewerJwtTemplateSourced) {
+ tokenReviewerJwtDisplay = (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="neutral">
+ <EyeOffIcon />
+ Configured
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-md">
+ This JWT was copied from an auth template and is write-only, so it cannot be viewed. Edit
+ the auth method to replace or remove it.
+ </TooltipContent>
+ </Tooltip>
+ );
+ } else if (data.tokenReviewerJwt) {
+ tokenReviewerJwtDisplay = (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="neutral">
+ <EyeIcon />
+ Reveal
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="right" className="max-w-xl p-2">
+ <p className="rounded-sm bg-container p-2 break-words">{data.tokenReviewerJwt}</p>
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
return (
<DetailGroup className="grid grid-cols-2 gap-x-6 gap-y-5">
+ <IdentityAuthFieldDisplay className="col-span-2" label="Configuration">
+ {configurationLabel}
+ </IdentityAuthFieldDisplay>
<IdentityAuthAccessTokenFields
accessTokenTTL={data.accessTokenTTL}
accessTokenMaxTTL={data.accessTokenMaxTTL}
@@ -59,25 +139,12 @@ export const IdentityKubernetesAuthContent = ({ identityId }: ViewAuthMethodProp
>
{data.kubernetesHost}
</IdentityAuthFieldDisplay>
- <IdentityAuthFieldDisplay label="Gateway">{selectedGateway?.name}</IdentityAuthFieldDisplay>
+ <IdentityAuthFieldDisplay label="Token Review Mode">
+ {reviewModeLabel}
+ </IdentityAuthFieldDisplay>
+ <IdentityAuthFieldDisplay label="Gateway">{gatewayDisplay}</IdentityAuthFieldDisplay>
<IdentityAuthFieldDisplay className="col-span-2" label="Token Reviewer JWT">
- {data.tokenReviewerJwt ? (
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="neutral">
- <EyeIcon />
- Reveal
- </Badge>
- </TooltipTrigger>
- <TooltipContent side="right" className="max-w-xl p-2">
- <p className="rounded-sm bg-container p-2 break-words">
- {data.tokenReviewerJwt || "Not provided"}
- </p>
- </TooltipContent>
- </Tooltip>
- ) : (
- <p className="text-base leading-4 text-muted italic">Not set</p>
- )}
+ {tokenReviewerJwtDisplay}
</IdentityAuthFieldDisplay>
<IdentityAuthFieldDisplay className="col-span-2" label="Allowed Service Account Names">
{data.allowedNames
diff --git a/frontend/src/views/IdentityAuthMethods/content/IdentityLdapAuthContent.tsx b/frontend/src/views/IdentityAuthMethods/content/IdentityLdapAuthContent.tsx
index ba1a697a3f..bfa7a1c959 100644
--- a/frontend/src/views/IdentityAuthMethods/content/IdentityLdapAuthContent.tsx
+++ b/frontend/src/views/IdentityAuthMethods/content/IdentityLdapAuthContent.tsx
@@ -12,7 +12,14 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
+import { useOrgPermission, useSubscription } from "@app/context";
+import {
+ OrgPermissionMachineIdentityAuthTemplateActions,
+ OrgPermissionSubjects
+} from "@app/context/OrgPermissionContext/types";
import { IdentityAuthMethod, useGetIdentityLdapAuth } from "@app/hooks/api";
+import { MachineIdentityAuthMethod } from "@app/hooks/api/identityAuthTemplates";
+import { useGetAvailableTemplates } from "@app/hooks/api/identityAuthTemplates/queries";
import {
IdentityAuthAccessTokenFields,
@@ -26,8 +33,23 @@ export const IdentityLdapAuthContent = ({
isLockedOut,
onMutated
}: ViewAuthMethodProps) => {
+ const { subscription } = useSubscription();
+ const { permission } = useOrgPermission();
+
+ const canAttachTemplates = permission.can(
+ OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,
+ OrgPermissionSubjects.MachineIdentityAuthTemplate
+ );
+
const { data, isPending } = useGetIdentityLdapAuth(identityId);
+ const { data: templates } = useGetAvailableTemplates(MachineIdentityAuthMethod.LDAP, {
+ enabled:
+ canAttachTemplates &&
+ Boolean(subscription?.machineIdentityAuthTemplates) &&
+ Boolean(data?.templateId)
+ });
+
if (isPending) {
return <PageLoader />;
}
@@ -45,8 +67,16 @@ export const IdentityLdapAuthContent = ({
);
}
+ const linkedTemplateName = templates?.find((template) => template.id === data.templateId)?.name;
+ const configurationLabel = data.templateId
+ ? (linkedTemplateName ?? "Linked template")
+ : "Custom Configuration";
+
return (
<DetailGroup className="grid grid-cols-2 gap-x-6 gap-y-5">
+ <IdentityAuthFieldDisplay className="col-span-2" label="Configuration">
+ {configurationLabel}
+ </IdentityAuthFieldDisplay>
<IdentityAuthAccessTokenFields
accessTokenTTL={data.accessTokenTTL}
accessTokenMaxTTL={data.accessTokenMaxTTL}