Skip to content

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

Merge branch 'main' into ENG-5443

Scott Wilson56948d4aca9c
diff --cc .infisicalignore
index 7b9d97d12a,851a1012ca..69bfe11111
--- a/.infisicalignore
+++ b/.infisicalignore
@@@ -66,5 -66,6 +66,7 @@@ backend/src/ee/services/honey-token/hon
docs/integrations/app-connections/ovh.mdx:private-key:84
docs/integrations/app-connections/datadog.mdx:generic-api-key:161
docs/integrations/app-connections/qovery.mdx:generic-api-key:96
+ backend/src/services/pki-sync/gcp-certificate-manager/gcp-certificate-manager-pki-sync-reconcile.test.ts:private-key:38
backend/src/services/certificate-v3/certificate-renewal-fns.test.ts:private-key:167
backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts:generic-api-key:216
++backend/src/ee/services/audit-log-stream/splunk/splunk-provider-schemas.test.ts:generic-api-key:7
diff --cc backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
index 98a348714b,0000000000..6fd9bd7cd5
mode 100644,000000..100644
--- 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
@@@ -1,222 -1,0 +1,227 @@@
+import { createMongoAbility } from "@casl/ability";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { IdentityAuthMethod } from "@app/db/schemas";
++import { TKubernetesTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";
+
+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[]
++}: {
++ templateBlobFields?: TKubernetesTemplateFields;
++ templateGatewayColumns?: typeof NO_GATEWAY;
++ identityAuthMethods?: 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 --cc backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 506784de9b,b07a76ff50..b3428247a6
--- 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,7 -55,7 +60,8 @@@ import
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+ import { getSharedHttpsAgent, safeRequest } from "@app/lib/validator/safe-request";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@@ -305,32 -298,6 +308,24 @@@ export const identityKubernetesAuthServ
};
};
- const $resolveEffectiveVerifyTlsCertificate = (
- caCert: string | null | undefined,
- storedVerify: boolean | null | undefined
- ): boolean => {
- if (!caCert?.length) return false;
- 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();
diff --cc backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts
index 3883afc796,c9dc60a660..9f659cd036
--- 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,111 -1,17 +1,115 @@@
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 { safeRequest } from "@app/lib/validator/safe-request";
+import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { handleAxiosError, KubernetesAuthErrorContext } from "./identity-kubernetes-auth-error-handlers";
+ import { getKubernetesServerName, withKubernetesHostScheme } from "./identity-kubernetes-auth-fns";
+import { IdentityKubernetesAuthTokenReviewMode } from "./identity-kubernetes-auth-types";
+ const VALIDATION_TIMEOUT_MS = 10_000;
+ // The /version and TokenReview responses are a few KB. Bounded so an operator-supplied host
+ // cannot make us buffer an arbitrary body.
+ const VALIDATION_MAX_RESPONSE_BYTES = 64 * 1024;
+
+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",
url: string,