Skip to content

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

improvement: move gateway details to template cols and address feedback

Scott Wilson66f9edaafc54
diff --git a/backend/src/db/migrations/20260827000000_add-gateway-to-identity-auth-templates.ts b/backend/src/db/migrations/20260827000000_add-gateway-to-identity-auth-templates.ts
new file mode 100644
index 0000000000..b63bbb68f3
--- /dev/null
+++ b/backend/src/db/migrations/20260827000000_add-gateway-to-identity-auth-templates.ts
@@ -0,0 +1,55 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasGatewayId = await knex.schema.hasColumn(TableName.IdentityAuthTemplate, "gatewayId");
+ const hasGatewayV2Id = await knex.schema.hasColumn(TableName.IdentityAuthTemplate, "gatewayV2Id");
+ const hasGatewayPoolId = await knex.schema.hasColumn(TableName.IdentityAuthTemplate, "gatewayPoolId");
+
+ if (!hasGatewayId || !hasGatewayV2Id || !hasGatewayPoolId) {
+ await knex.schema.alterTable(TableName.IdentityAuthTemplate, (t) => {
+ // the gateway a template dials through is a reference, not template data, so it lives in
+ // columns rather than the encrypted templateFields blob: ON DELETE SET NULL then keeps it
+ // in step with the identical columns on the linked identity rows, which a blob cannot do
+ if (!hasGatewayId) {
+ t.uuid("gatewayId").nullable();
+ t.foreign("gatewayId").references("id").inTable(TableName.Gateway).onDelete("SET NULL");
+ t.index("gatewayId");
+ }
+ if (!hasGatewayV2Id) {
+ t.uuid("gatewayV2Id").nullable();
+ t.foreign("gatewayV2Id").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");
+ t.index("gatewayV2Id");
+ }
+ if (!hasGatewayPoolId) {
+ t.uuid("gatewayPoolId").nullable();
+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("SET NULL");
+ t.index("gatewayPoolId");
+ }
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasGatewayId = await knex.schema.hasColumn(TableName.IdentityAuthTemplate, "gatewayId");
+ const hasGatewayV2Id = await knex.schema.hasColumn(TableName.IdentityAuthTemplate, "gatewayV2Id");
+ const hasGatewayPoolId = await knex.schema.hasColumn(TableName.IdentityAuthTemplate, "gatewayPoolId");
+
+ if (hasGatewayId || hasGatewayV2Id || hasGatewayPoolId) {
+ await knex.schema.alterTable(TableName.IdentityAuthTemplate, (t) => {
+ if (hasGatewayId) {
+ t.dropForeign(["gatewayId"]);
+ t.dropColumn("gatewayId");
+ }
+ if (hasGatewayV2Id) {
+ t.dropForeign(["gatewayV2Id"]);
+ t.dropColumn("gatewayV2Id");
+ }
+ if (hasGatewayPoolId) {
+ t.dropForeign(["gatewayPoolId"]);
+ t.dropColumn("gatewayPoolId");
+ }
+ });
+ }
+}
diff --git a/backend/src/db/schemas/identity-auth-templates.ts b/backend/src/db/schemas/identity-auth-templates.ts
index efe8ccb8c6..8390d37f1d 100644
--- a/backend/src/db/schemas/identity-auth-templates.ts
+++ b/backend/src/db/schemas/identity-auth-templates.ts
@@ -16,7 +16,10 @@ export const IdentityAuthTemplatesSchema = z.object({
name: z.string(),
authMethod: z.string(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ gatewayId: z.string().uuid().nullable().optional(),
+ gatewayV2Id: z.string().uuid().nullable().optional(),
+ gatewayPoolId: z.string().uuid().nullable().optional()
});
export type TIdentityAuthTemplates = z.infer<typeof IdentityAuthTemplatesSchema>;
diff --git a/backend/src/ee/routes/v1/identity-template-router.ts b/backend/src/ee/routes/v1/identity-template-router.ts
index ca5d3a2bfe..e3e719addb 100644
--- a/backend/src/ee/routes/v1/identity-template-router.ts
+++ b/backend/src/ee/routes/v1/identity-template-router.ts
@@ -28,12 +28,20 @@ const templateNameSchema = z
// Credential fields are stripped server-side by $sanitizeTemplate; declaring the
// exact shape here documents each method's fields and makes the response serializer a
// second barrier that drops anything undeclared
+// the gateway reference is stored in columns so it can carry a foreign key, but it stays
+// inside templateFields in the API, so the v1/v2 column split is not part of the contract
+const templateRowSchema = IdentityAuthTemplatesSchema.omit({
+ gatewayId: true,
+ gatewayV2Id: true,
+ gatewayPoolId: true
+});
+
const sanitizedTemplateSchema = z.discriminatedUnion("authMethod", [
- IdentityAuthTemplatesSchema.extend({
+ templateRowSchema.extend({
authMethod: z.literal(IdentityAuthTemplateMethod.LDAP),
templateFields: ldapTemplateFieldsResponseSchema
}),
- IdentityAuthTemplatesSchema.extend({
+ templateRowSchema.extend({
authMethod: z.literal(IdentityAuthTemplateMethod.KUBERNETES),
templateFields: kubernetesTemplateFieldsResponseSchema
})
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
index a0178aaa00..28f383f4f6 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
@@ -13,58 +13,69 @@ vi.mock("@app/lib/config/env", () => ({
const ORG_ID = "org-id";
const TEMPLATE_ID = "template-id";
const GATEWAY_ID = "gateway-id";
+const GATEWAY_V2_ID = "gateway-v2-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 baseTemplateFields = {
+const baseBlobFields = {
kubernetesHost: PUBLIC_HOST,
tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,
tokenReviewerJwt: "reviewer-jwt",
- allowedAudience: "",
- gatewayId: GATEWAY_ID
+ allowedAudience: ""
};
+const NO_GATEWAY = { gatewayId: null, gatewayV2Id: null, gatewayPoolId: null };
+
const createService = ({
- templateFields = baseTemplateFields,
- liveGatewayIds = [GATEWAY_ID]
+ authMethod = IdentityAuthTemplateMethod.KUBERNETES,
+ blobFields = baseBlobFields,
+ gatewayColumns = { gatewayId: GATEWAY_ID, gatewayV2Id: null, gatewayPoolId: null },
+ liveGatewayIds = [GATEWAY_ID],
+ liveGatewayV2Ids = [GATEWAY_V2_ID]
}: {
- templateFields?: Record<string, unknown>;
+ authMethod?: IdentityAuthTemplateMethod;
+ blobFields?: Record<string, unknown>;
+ gatewayColumns?: { gatewayId: string | null; gatewayV2Id: string | null; gatewayPoolId: string | null };
liveGatewayIds?: string[];
+ liveGatewayV2Ids?: string[];
} = {}) => {
const identityKubernetesAuthDAL = {
updateByTemplateId: vi.fn().mockResolvedValue([{ identityId: "identity-id" }])
};
+ const templateRow = {
+ id: TEMPLATE_ID,
+ orgId: ORG_ID,
+ name: "auth-template",
+ authMethod,
+ // the fake cipher pair below round-trips plaintext, so the "encrypted" blob is the JSON
+ templateFields: Buffer.from(JSON.stringify(blobFields)),
+ ...gatewayColumns
+ };
+
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))
- }),
+ findByIdAndOrgId: vi.fn().mockResolvedValue(templateRow),
findTemplateUsages: vi.fn().mockResolvedValue([{ identityId: "identity-id", identityName: "identity" }]),
updateById: vi.fn().mockImplementation((id: string, data: Record<string, unknown>) => ({
+ ...templateRow,
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 gatewayV2DAL = {
+ find: vi.fn().mockImplementation(({ id }: { id: string }) => (liveGatewayV2Ids.includes(id) ? [{ id }] : []))
+ };
const gatewayPoolDAL = { findById: vi.fn().mockResolvedValue(null) };
const service = identityAuthTemplateServiceFactory({
identityAuthTemplateDAL,
- identityLdapAuthDAL: { updateByTemplateId: vi.fn() },
+ identityLdapAuthDAL: { updateByTemplateId: vi.fn().mockResolvedValue([]) },
identityKubernetesAuthDAL,
gatewayDAL,
gatewayV2DAL,
@@ -89,10 +100,10 @@ const createService = ({
return { service, identityKubernetesAuthDAL, identityAuthTemplateDAL };
};
-const updateHost = (service: ReturnType<typeof createService>["service"], kubernetesHost: string) =>
+const patchTemplate = (service: ReturnType<typeof createService>["service"], templateFields: Record<string, unknown>) =>
service.updateTemplate({
templateId: TEMPLATE_ID,
- templateFields: { kubernetesHost },
+ templateFields,
actorId: "actor-id",
actor: "user",
actorAuthMethod: undefined,
@@ -102,19 +113,21 @@ const updateHost = (service: ReturnType<typeof createService>["service"], kubern
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: [] });
+ it("blocks a private host when the template has no gateway", async () => {
+ // a deleted gateway leaves these columns NULL via ON DELETE SET NULL, so the reference
+ // cannot outlive the gateway the way a stale id in the encrypted blob could
+ const { service, identityKubernetesAuthDAL } = createService({ gatewayColumns: NO_GATEWAY });
- await expect(updateHost(service, PRIVATE_HOST)).rejects.toThrow("Local IPs not allowed as URL");
+ await expect(patchTemplate(service, { kubernetesHost: 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 () => {
+ it("allows a private host while the template's gateway column is set", async () => {
const { service, identityKubernetesAuthDAL } = createService();
- await updateHost(service, PRIVATE_HOST);
+ await patchTemplate(service, { kubernetesHost: PRIVATE_HOST });
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
{ templateId: TEMPLATE_ID },
@@ -123,58 +136,99 @@ describe("identityAuthTemplateServiceFactory kubernetes host validation", () =>
);
});
- it("blocks a private host when the template has no gateway at all", async () => {
- const { service } = createService({
- templateFields: { ...baseTemplateFields, gatewayId: undefined }
- });
+ it("blocks a private host when the patch clears the gateway", async () => {
+ const { service } = createService();
- await expect(updateHost(service, PRIVATE_HOST)).rejects.toThrow("Local IPs not allowed as URL");
+ await expect(patchTemplate(service, { kubernetesHost: PRIVATE_HOST, gatewayId: null })).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: [] });
+ it("rejects a gateway the org does not have", async () => {
+ const { service } = createService();
- 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();
+ await expect(patchTemplate(service, { gatewayId: "11111111-1111-1111-1111-111111111111" })).rejects.toThrow(
+ "was not found in this organization"
+ );
});
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
+ // rotating the reviewer JWT cannot repoint the dial target, so it must not be blocked by a
+ // host that is only private because it was always reached through the now-deleted gateway
const { service, identityKubernetesAuthDAL } = createService({
- templateFields: { ...baseTemplateFields, kubernetesHost: PRIVATE_HOST },
- liveGatewayIds: []
+ blobFields: { ...baseBlobFields, kubernetesHost: PRIVATE_HOST },
+ gatewayColumns: NO_GATEWAY
});
- 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]);
+ await patchTemplate(service, { tokenReviewerJwt: "rotated-jwt" });
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalled();
});
+});
+
+describe("identityAuthTemplateServiceFactory gateway column storage", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("stores the gateway in columns and keeps it out of the encrypted blob", async () => {
+ const { service, identityAuthTemplateDAL } = createService({ gatewayColumns: NO_GATEWAY });
+
+ await patchTemplate(service, { gatewayId: GATEWAY_V2_ID });
+
+ const [, update] = identityAuthTemplateDAL.updateById.mock.calls[0] as [string, Record<string, unknown>];
+ // a v2 gateway resolves onto its own column, mirroring identity_kubernetes_auths
+ expect(update.gatewayV2Id).toBe(GATEWAY_V2_ID);
+ expect(update.gatewayId).toBeNull();
+ expect(JSON.parse((update.templateFields as Buffer).toString())).not.toHaveProperty("gatewayId");
+ });
+
+ it("reports the logical gatewayId from whichever column holds it", async () => {
+ const { service } = createService({
+ gatewayColumns: { gatewayId: null, gatewayV2Id: GATEWAY_V2_ID, gatewayPoolId: null }
+ });
+
+ const updated = await patchTemplate(service, { allowedAudience: "aud" });
+
+ expect(updated.templateFields).toMatchObject({ gatewayId: GATEWAY_V2_ID, gatewayPoolId: null });
+ });
+
+ it("propagates the template's gateway columns onto linked identities", async () => {
+ const { service, identityKubernetesAuthDAL } = createService({ gatewayColumns: NO_GATEWAY });
+
+ await patchTemplate(service, { gatewayId: GATEWAY_ID });
+
+ expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
+ { templateId: TEMPLATE_ID },
+ expect.objectContaining({ gatewayId: GATEWAY_ID, gatewayV2Id: null, gatewayPoolId: null }),
+ expect.anything()
+ );
+ });
+
+ it("keeps gateway fields out of a method that does not declare them", async () => {
+ // LDAP has no gateway concept, so its fields view must not sprout the columns and rely on
+ // the route's response schema to strip them again
+ const { service } = createService({
+ authMethod: IdentityAuthTemplateMethod.LDAP,
+ blobFields: { url: "ldap://example.com", bindDN: "cn=admin", bindPass: "pw", searchBase: "dc=example" },
+ gatewayColumns: NO_GATEWAY
+ });
+
+ const updated = await patchTemplate(service, { searchBase: "dc=other" });
+
+ expect(updated.templateFields).not.toHaveProperty("gatewayId");
+ expect(updated.templateFields).not.toHaveProperty("gatewayPoolId");
+ });
- it("propagates a public host regardless of gateway state", async () => {
- const { service, identityKubernetesAuthDAL } = createService({ liveGatewayIds: [] });
+ it("leaves the gateway columns alone when the patch does not mention them", async () => {
+ const { service, identityKubernetesAuthDAL, identityAuthTemplateDAL } = createService();
- await updateHost(service, PUBLIC_HOST);
+ await patchTemplate(service, { allowedAudience: "aud" });
+ const [, update] = identityAuthTemplateDAL.updateById.mock.calls[0] as [string, Record<string, unknown>];
+ expect(update).not.toHaveProperty("gatewayV2Id");
+ // linked rows still get the row's existing gateway, so they cannot drift from the template
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
{ templateId: TEMPLATE_ID },
- expect.objectContaining({ kubernetesHost: PUBLIC_HOST }),
+ expect.objectContaining({ gatewayId: GATEWAY_ID }),
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 c9647dfbb4..ec9cd39764 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,31 +227,35 @@ 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;
+ // the gateway reference lives in columns rather than the encrypted blob so it can carry a
+ // foreign key. ON DELETE SET NULL then clears it in step with the identical columns on the
+ // linked identity rows, which is what stops a deleted gateway from leaving a stale id behind
+ // that still looks live to the host check below
+ const GATEWAY_TEMPLATE_FIELD_KEYS = ["gatewayId", "gatewayPoolId"];
+
+ const $toBlobFields = (fields: Record<string, unknown>) => {
+ const blobFields = { ...fields };
+ GATEWAY_TEMPLATE_FIELD_KEYS.forEach((key) => delete blobFields[key]);
+ return blobFields;
+ };
+
+ // derived from the method's own field schema rather than a hardcoded list, so a method that
+ // later gains gateway support starts round-tripping the columns with no change here
+ const $methodHasGatewayFields = (authMethod: string) =>
+ (templateFieldPatchKeysByMethod[authMethod as IdentityAuthTemplateMethod] ?? []).includes("gatewayId");
+
+ // the API keeps one logical gatewayId covering both gateway generations, so the v1/v2
+ // column split stays an implementation detail
+ const $withGatewayFields = (
+ template: Pick<TIdentityAuthTemplates, "authMethod" | "gatewayId" | "gatewayV2Id" | "gatewayPoolId">,
+ fields: Record<string, unknown>
+ ) => {
+ if (!$methodHasGatewayFields(template.authMethod)) return fields;
+ return {
+ ...fields,
+ gatewayId: template.gatewayV2Id ?? template.gatewayId ?? null,
+ gatewayPoolId: template.gatewayPoolId ?? null
+ };
};
const createTemplate = async ({
@@ -282,6 +286,11 @@ export const identityAuthTemplateServiceFactory = ({
);
let fieldsToPersist: Record<string, unknown> = templateFields;
+ let gatewayColumns: Pick<TIdentityAuthTemplates, "gatewayId" | "gatewayV2Id" | "gatewayPoolId"> = {
+ gatewayId: null,
+ gatewayV2Id: null,
+ gatewayPoolId: null
+ };
if (authMethod === IdentityAuthTemplateMethod.KUBERNETES) {
const kubernetesFields = templateFields as TKubernetesTemplateFields;
const normalizedFields: TKubernetesTemplateFields = {
@@ -307,11 +316,17 @@ export const identityAuthTemplateServiceFactory = ({
plan,
permission
});
- await $resolveKubernetesTemplateGateway({
- gatewayId: normalizedFields.gatewayId,
- gatewayPoolId: normalizedFields.gatewayPoolId,
- orgId: actorOrgId
- });
+ const { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId } =
+ await $resolveKubernetesTemplateGateway({
+ gatewayId: normalizedFields.gatewayId,
+ gatewayPoolId: normalizedFields.gatewayPoolId,
+ orgId: actorOrgId
+ });
+ gatewayColumns = {
+ gatewayId: resolvedGatewayId,
+ gatewayV2Id: resolvedGatewayV2Id,
+ gatewayPoolId: resolvedGatewayPoolId
+ };
}
fieldsToPersist = normalizedFields;
}
@@ -320,14 +335,16 @@ export const identityAuthTemplateServiceFactory = ({
type: KmsDataKey.Organization,
orgId: actorOrgId
});
+ const blobFields = $toBlobFields(fieldsToPersist);
const template = await identityAuthTemplateDAL.create({
name,
authMethod,
- templateFields: encryptor({ plainText: Buffer.from(JSON.stringify(fieldsToPersist)) }).cipherTextBlob,
- orgId: actorOrgId
+ templateFields: encryptor({ plainText: Buffer.from(JSON.stringify(blobFields)) }).cipherTextBlob,
+ orgId: actorOrgId,
+ ...gatewayColumns
});
- return $sanitizeTemplate(template, fieldsToPersist);
+ return $sanitizeTemplate(template, $withGatewayFields(template, blobFields));
};
const updateTemplate = async ({
@@ -389,14 +406,16 @@ export const identityAuthTemplateServiceFactory = ({
}[])
: [];
- const currentTemplateFields = JSON.parse(
- decryptor({ cipherTextBlob: template.templateFields }).toString()
- ) as Record<string, unknown>;
+ const currentTemplateFields = $withGatewayFields(
+ template,
+ JSON.parse(decryptor({ cipherTextBlob: template.templateFields }).toString()) as Record<string, unknown>
+ );
const mergedTemplateFields: Record<string, unknown> = fieldPatch
? { ...currentTemplateFields, ...fieldPatch }
: currentTemplateFields;
let kubernetesPropagationData: TIdentityKubernetesAuthsUpdate | undefined;
+ let gatewayColumnUpdate: Pick<TIdentityAuthTemplates, "gatewayId" | "gatewayV2Id" | "gatewayPoolId"> | undefined;
if (fieldPatch && template.authMethod === IdentityAuthTemplateMethod.KUBERNETES) {
const merged = mergedTemplateFields as TKubernetesTemplateFields;
const patch = fieldPatch as Partial<TKubernetesTemplateFields>;
@@ -406,11 +425,10 @@ export const identityAuthTemplateServiceFactory = ({
merged.verifyTlsCertificate = Boolean(patch.caCert?.length);
}
$validateKubernetesTemplateFields(merged);
- // 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
+ // a gateway reference is only re-resolved (and re-authorized) when the patch supplies
+ // one; otherwise the columns already on the row stand, and the FK guarantees they name
+ // a gateway that still exists
const patchTouchesGateway = "gatewayId" in patch || "gatewayPoolId" in patch;
- let resolvedGateway: Awaited<ReturnType<typeof $resolveKubernetesTemplateGateway>> | undefined;
if (patchTouchesGateway) {
$authorizeKubernetesTemplateGateway({
gatewayId: merged.gatewayId,
@@ -418,38 +436,32 @@ export const identityAuthTemplateServiceFactory = ({
plan,
permission
});
- resolvedGateway = await $resolveKubernetesTemplateGateway({
- gatewayId: merged.gatewayId,
- gatewayPoolId: merged.gatewayPoolId,
- orgId: template.orgId
- });
+ const { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId } =
+ await $resolveKubernetesTemplateGateway({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ orgId: template.orgId
+ });
+ gatewayColumnUpdate = {
+ gatewayId: resolvedGatewayId,
+ gatewayV2Id: resolvedGatewayV2Id,
+ gatewayPoolId: resolvedGatewayPoolId
+ };
}
// 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
+ // only patches that can change where we dial are checked, so losing a gateway to a
+ // deletion does not strand the template: its host is legitimately private, and an edit
+ // that cannot repoint the dial target has no new address to vet
const patchAffectsDialing = patchTouchesGateway || "kubernetesHost" in patch || "tokenReviewMode" in patch;
if (
patchAffectsDialing &&
merged.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
- merged.kubernetesHost
+ merged.kubernetesHost &&
+ !merged.gatewayId &&
+ !merged.gatewayPoolId
) {
- 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);
- }
+ await blockLocalAndPrivateIpAddresses(merged.kubernetesHost);
}
kubernetesPropagationData = {
kubernetesHost: merged.kubernetesHost ?? null,
@@ -464,11 +476,14 @@ export const identityAuthTemplateServiceFactory = ({
: null,
isTokenReviewerJwtTemplateSourced: Boolean(merged.tokenReviewerJwt)
};
- if (resolvedGateway) {
- kubernetesPropagationData.gatewayId = resolvedGateway.resolvedGatewayId;
- kubernetesPropagationData.gatewayV2Id = resolvedGateway.resolvedGatewayV2Id;
- kubernetesPropagationData.gatewayPoolId = resolvedGateway.resolvedGatewayPoolId;
- }
+ const effectiveGatewayColumns = gatewayColumnUpdate ?? {
+ gatewayId: template.gatewayId ?? null,
+ gatewayV2Id: template.gatewayV2Id ?? null,
+ gatewayPoolId: template.gatewayPoolId ?? null
+ };
+ kubernetesPropagationData.gatewayId = effectiveGatewayColumns.gatewayId;
+ kubernetesPropagationData.gatewayV2Id = effectiveGatewayColumns.gatewayV2Id;
+ kubernetesPropagationData.gatewayPoolId = effectiveGatewayColumns.gatewayPoolId;
}
const { updatedTemplate, propagatedIdentityIds } = await identityAuthTemplateDAL.transaction(async (tx) => {
@@ -479,8 +494,10 @@ export const identityAuthTemplateServiceFactory = ({
...(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
- })
+ templateFields: encryptor({ plainText: Buffer.from(JSON.stringify($toBlobFields(mergedTemplateFields))) })
+ .cipherTextBlob
+ }),
+ ...gatewayColumnUpdate
},
tx
);
@@ -656,7 +673,7 @@ export const identityAuthTemplateServiceFactory = ({
const decryptedTemplateFields = JSON.parse(
decryptor({ cipherTextBlob: template.templateFields }).toString()
) as Record<string, unknown>;
- return $sanitizeTemplate(template, decryptedTemplateFields);
+ return $sanitizeTemplate(template, $withGatewayFields(template, decryptedTemplateFields));
};
const listTemplates = async ({
@@ -695,7 +712,7 @@ export const identityAuthTemplateServiceFactory = ({
string,
unknown
>;
- return $sanitizeTemplate(doc, parsedTemplateFields);
+ return $sanitizeTemplate(doc, $withGatewayFields(doc, parsedTemplateFields));
})
};
};
@@ -732,7 +749,7 @@ export const identityAuthTemplateServiceFactory = ({
string,
unknown
>;
- return $sanitizeTemplate(doc, parsedTemplateFields);
+ return $sanitizeTemplate(doc, $withGatewayFields(doc, parsedTemplateFields));
});
};
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 dc64997540..913149a044 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
@@ -12,7 +12,10 @@ import {
// what every read path returns: the row with its credentials replaced by presence flags.
// Derived from the response schemas so the service and the route contract cannot drift
-export type TSanitizedIdentityAuthTemplate = Omit<TIdentityAuthTemplates, "templateFields" | "authMethod"> &
+export type TSanitizedIdentityAuthTemplate = Omit<
+ TIdentityAuthTemplates,
+ "templateFields" | "authMethod" | "gatewayId" | "gatewayV2Id" | "gatewayPoolId"
+> &
(
| {
authMethod: IdentityAuthTemplateMethod.LDAP;
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 f8dbedbdd0..43ac1ed43a 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
@@ -902,8 +902,10 @@ export const identityKubernetesAuthServiceFactory = ({
caCert = templateFields.caCert || undefined;
tokenReviewerJwt = templateFields.tokenReviewerJwt || undefined;
tokenReviewMode = templateFields.tokenReviewMode;
- gatewayId = templateFields.gatewayId ?? null;
- gatewayPoolId = templateFields.gatewayPoolId ?? null;
+ // 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 ?? "";
} else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && !kubernetesHost) {
@@ -1235,8 +1237,10 @@ export const identityKubernetesAuthServiceFactory = ({
caCert = templateFields.caCert ?? "";
tokenReviewerJwt = templateFields.tokenReviewerJwt || null;
tokenReviewMode = templateFields.tokenReviewMode;
- gatewayId = templateFields.gatewayId ?? null;
- gatewayPoolId = templateFields.gatewayPoolId ?? null;
+ // 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 ?? "";
} else if (templateId === undefined && identityKubernetesAuth.templateId) {
@@ -1257,6 +1261,25 @@ export const identityKubernetesAuthServiceFactory = ({
}
}
+ // a template-sourced reviewer JWT stays write-only to the caller, so it must only ever be
+ // sent to the host the template chose. unlinking deliberately leaves the credential in
+ // place to keep login working, which would otherwise let an actor with EditAuth alone
+ // repoint the host and have the unauthenticated login endpoint deliver the JWT to a server
+ // they control. keyed on the provenance flag rather than on the unlink itself, so a repoint
+ // in a later request is caught too
+ if (
+ !template &&
+ identityKubernetesAuth.isTokenReviewerJwtTemplateSourced &&
+ tokenReviewerJwt === undefined &&
+ kubernetesHost !== undefined &&
+ kubernetesHost !== identityKubernetesAuth.kubernetesHost
+ ) {
+ throw new BadRequestError({
+ message:
+ "This identity still uses the token reviewer JWT copied from its auth template, so its Kubernetes host cannot be changed. Supply your own tokenReviewerJwt with this change, or set tokenReviewerJwt to null to remove the stored one."
+ });
+ }
+
const reformattedAccessTokenTrustedIps = accessTokenTrustedIps?.map((accessTokenTrustedIp) => {
if (
!plan.ipAllowlisting &&