Skip to content

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

fix: gate k8s template host check on a live gateway reference

Scott Wilson067ac0fabaa8
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
new file mode 100644
index 0000000000..a0178aaa00
--- /dev/null
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
@@ -0,0 +1,181 @@
+import { createMongoAbility } from "@casl/ability";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
+
+import { IdentityAuthTemplateMethod } from "./identity-auth-template-enums";
+import { identityAuthTemplateServiceFactory } from "./identity-auth-template-service";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ isDevelopmentMode: false, ALLOW_INTERNAL_IP_CONNECTIONS: false })
+}));
+
+const ORG_ID = "org-id";
+const TEMPLATE_ID = "template-id";
+const GATEWAY_ID = "gateway-id";
+const PRIVATE_HOST = "https://10.0.0.1";
+const PUBLIC_HOST = "https://8.8.8.8";
+
+const baseTemplateFields = {
+ kubernetesHost: PUBLIC_HOST,
+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
+ tokenReviewerJwt: "reviewer-jwt",
+ allowedAudience: "",
+ gatewayId: GATEWAY_ID
+};
+
+const createService = ({
+ templateFields = baseTemplateFields,
+ liveGatewayIds = [GATEWAY_ID]
+}: {
+ templateFields?: Record<string, unknown>;
+ liveGatewayIds?: string[];
+} = {}) => {
+ const identityKubernetesAuthDAL = {
+ updateByTemplateId: vi.fn().mockResolvedValue([{ identityId: "identity-id" }])
+ };
+
+ const identityAuthTemplateDAL = {
+ findByIdAndOrgId: vi.fn().mockResolvedValue({
+ id: TEMPLATE_ID,
+ orgId: ORG_ID,
+ name: "k8s-template",
+ authMethod: IdentityAuthTemplateMethod.KUBERNETES,
+ // the fake cipher pair below round-trips plaintext, so the "encrypted" blob is the JSON
+ templateFields: Buffer.from(JSON.stringify(templateFields))
+ }),
+ findTemplateUsages: vi.fn().mockResolvedValue([{ identityId: "identity-id", identityName: "identity" }]),
+ updateById: vi.fn().mockImplementation((id: string, data: Record<string, unknown>) => ({
+ id,
+ orgId: ORG_ID,
+ name: "k8s-template",
+ authMethod: IdentityAuthTemplateMethod.KUBERNETES,
+ ...data
+ })),
+ transaction: vi.fn().mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) => cb({}))
+ };
+
+ // a live gateway resolves as v1; anything else is treated as deleted by both DALs
+ const gatewayDAL = {
+ find: vi.fn().mockImplementation(({ id }: { id: string }) => (liveGatewayIds.includes(id) ? [{ id }] : []))
+ };
+ const gatewayV2DAL = { find: vi.fn().mockResolvedValue([]) };
+ const gatewayPoolDAL = { findById: vi.fn().mockResolvedValue(null) };
+
+ const service = identityAuthTemplateServiceFactory({
+ identityAuthTemplateDAL,
+ identityLdapAuthDAL: { updateByTemplateId: vi.fn() },
+ identityKubernetesAuthDAL,
+ gatewayDAL,
+ gatewayV2DAL,
+ gatewayPoolDAL,
+ permissionService: {
+ getOrgPermission: vi
+ .fn()
+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) })
+ },
+ kmsService: {
+ createCipherPairWithDataKey: vi.fn().mockResolvedValue({
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: plainText }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ })
+ },
+ licenseService: {
+ getPlan: vi.fn().mockResolvedValue({ machineIdentityAuthTemplates: true, gateway: true, gatewayPool: true })
+ },
+ auditLogService: { createAuditLog: vi.fn() }
+ } as unknown as Parameters<typeof identityAuthTemplateServiceFactory>[0]);
+
+ return { service, identityKubernetesAuthDAL, identityAuthTemplateDAL };
+};
+
+const updateHost = (service: ReturnType<typeof createService>["service"], kubernetesHost: string) =>
+ service.updateTemplate({
+ templateId: TEMPLATE_ID,
+ templateFields: { kubernetesHost },
+ actorId: "actor-id",
+ actor: "user",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+ } as unknown as Parameters<typeof service.updateTemplate>[0]);
+
+describe("identityAuthTemplateServiceFactory kubernetes host validation", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("blocks a private host when the template's gateway no longer exists", async () => {
+ // the linked identities lost their gateway columns to ON DELETE SET NULL when the gateway
+ // was deleted, so the stale id in the encrypted blob must not exempt the host check
+ const { service, identityKubernetesAuthDAL } = createService({ liveGatewayIds: [] });
+
+ await expect(updateHost(service, PRIVATE_HOST)).rejects.toThrow("Local IPs not allowed as URL");
+ expect(identityKubernetesAuthDAL.updateByTemplateId).not.toHaveBeenCalled();
+ });
+
+ it("allows a private host while the template's gateway is still live", async () => {
+ const { service, identityKubernetesAuthDAL } = createService();
+
+ await updateHost(service, PRIVATE_HOST);
+
+ expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
+ { templateId: TEMPLATE_ID },
+ expect.objectContaining({ kubernetesHost: PRIVATE_HOST }),
+ expect.anything()
+ );
+ });
+
+ it("blocks a private host when the template has no gateway at all", async () => {
+ const { service } = createService({
+ templateFields: { ...baseTemplateFields, gatewayId: undefined }
+ });
+
+ await expect(updateHost(service, PRIVATE_HOST)).rejects.toThrow("Local IPs not allowed as URL");
+ });
+
+ it("still permits unrelated edits when the gateway was deleted after authoring", async () => {
+ // rotating the reviewer JWT carries no host, so a dangling gateway must not block it
+ const { service, identityKubernetesAuthDAL } = createService({ liveGatewayIds: [] });
+
+ await service.updateTemplate({
+ templateId: TEMPLATE_ID,
+ templateFields: { tokenReviewerJwt: "rotated-jwt" },
+ actorId: "actor-id",
+ actor: "user",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+ } as unknown as Parameters<typeof service.updateTemplate>[0]);
+
+ expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalled();
+ });
+
+ it("still permits unrelated edits when a private host sits behind a deleted gateway", async () => {
+ // the host is legitimately private because it was only ever reached through the gateway;
+ // re-checking it on an edit that cannot change where we dial would strand the template
+ const { service, identityKubernetesAuthDAL } = createService({
+ templateFields: { ...baseTemplateFields, kubernetesHost: PRIVATE_HOST },
+ liveGatewayIds: []
+ });
+
+ await service.updateTemplate({
+ templateId: TEMPLATE_ID,
+ templateFields: { tokenReviewerJwt: "rotated-jwt" },
+ actorId: "actor-id",
+ actor: "user",
+ actorAuthMethod: undefined,
+ actorOrgId: ORG_ID
+ } as unknown as Parameters<typeof service.updateTemplate>[0]);
+
+ expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalled();
+ });
+
+ it("propagates a public host regardless of gateway state", async () => {
+ const { service, identityKubernetesAuthDAL } = createService({ liveGatewayIds: [] });
+
+ await updateHost(service, PUBLIC_HOST);
+
+ expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
+ { templateId: TEMPLATE_ID },
+ expect.objectContaining({ kubernetesHost: PUBLIC_HOST }),
+ expect.anything()
+ );
+ });
+});
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
index 2b771ba80a..c9647dfbb4 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
@@ -227,6 +227,33 @@ export const identityAuthTemplateServiceFactory = ({
return { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId: gatewayPoolId ?? null };
};
+ // the gateway exemption on the host check is only sound while the reference still points at
+ // a live gateway: identity_kubernetes_auths loses its gateway columns to ON DELETE SET NULL,
+ // but the template keeps the id inside its encrypted blob, so a deleted gateway leaves the
+ // two out of sync and the linked rows fall back to dialing the host directly
+ const $kubernetesTemplateGatewayIsLive = async ({
+ gatewayId,
+ gatewayPoolId,
+ orgId
+ }: {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+ orgId: string;
+ }) => {
+ if (gatewayPoolId) {
+ const pool = await gatewayPoolDAL.findById(gatewayPoolId);
+ return Boolean(pool && pool.orgId === orgId);
+ }
+ if (gatewayId) {
+ const [[gateway], [gatewayV2]] = await Promise.all([
+ gatewayDAL.find({ id: gatewayId, orgId }),
+ gatewayV2DAL.find({ id: gatewayId, orgId })
+ ]);
+ return Boolean(gateway || gatewayV2);
+ }
+ return false;
+ };
+
const createTemplate = async ({
name,
authMethod,
@@ -379,16 +406,50 @@ export const identityAuthTemplateServiceFactory = ({
merged.verifyTlsCertificate = Boolean(patch.caCert?.length);
}
$validateKubernetesTemplateFields(merged);
- // the merged host propagates to every linked identity and is dialed by the backend
- // at login, so it gets the same local/private-address block as the identity attach
- // flow (gateway-dialed hosts are exempt)
+ // 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
+ const patchTouchesGateway = "gatewayId" in patch || "gatewayPoolId" in patch;
+ let resolvedGateway: Awaited<ReturnType<typeof $resolveKubernetesTemplateGateway>> | undefined;
+ if (patchTouchesGateway) {
+ $authorizeKubernetesTemplateGateway({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ plan,
+ permission
+ });
+ resolvedGateway = await $resolveKubernetesTemplateGateway({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ orgId: template.orgId
+ });
+ }
+ // the merged host propagates to every linked identity and is dialed by the backend at
+ // login, so it gets the same local/private-address block as the identity attach flow.
+ // only patches that change where we dial are checked: re-checking on every edit would
+ // strand a template whose gateway was deleted, since its host is legitimately private.
+ // gateway-dialed hosts stay exempt, but only while the reference still resolves, as the
+ // linked rows have already lost the gateway a stale id in the blob still claims
+ const patchAffectsDialing = patchTouchesGateway || "kubernetesHost" in patch || "tokenReviewMode" in patch;
if (
+ patchAffectsDialing &&
merged.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- merged.kubernetesHost &&
- !merged.gatewayId &&
- !merged.gatewayPoolId
+ merged.kubernetesHost
) {
- await blockLocalAndPrivateIpAddresses(merged.kubernetesHost);
+ const dialsThroughGateway = resolvedGateway
+ ? Boolean(
+ resolvedGateway.resolvedGatewayId ||
+ resolvedGateway.resolvedGatewayV2Id ||
+ resolvedGateway.resolvedGatewayPoolId
+ )
+ : await $kubernetesTemplateGatewayIsLive({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ orgId: template.orgId
+ });
+ if (!dialsThroughGateway) {
+ await blockLocalAndPrivateIpAddresses(merged.kubernetesHost);
+ }
}
kubernetesPropagationData = {
kubernetesHost: merged.kubernetesHost ?? null,
@@ -403,25 +464,10 @@ export const identityAuthTemplateServiceFactory = ({
: null,
isTokenReviewerJwtTemplateSourced: Boolean(merged.tokenReviewerJwt)
};
- // 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;
+ if (resolvedGateway) {
+ kubernetesPropagationData.gatewayId = resolvedGateway.resolvedGatewayId;
+ kubernetesPropagationData.gatewayV2Id = resolvedGateway.resolvedGatewayV2Id;
+ kubernetesPropagationData.gatewayPoolId = resolvedGateway.resolvedGatewayPoolId;
}
}