Skip to content

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

feat(gateway): add Kubernetes auth for gateway enrollment

bernie-g5009b215c002
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 30ee39af18..0a6acabf58 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -500,6 +500,9 @@ import {
TResourceAwsAuths,
TResourceAwsAuthsInsert,
TResourceAwsAuthsUpdate,
+ TResourceKubernetesAuths,
+ TResourceKubernetesAuthsInsert,
+ TResourceKubernetesAuthsUpdate,
TResourceMetadata,
TResourceMetadataInsert,
TResourceMetadataUpdate,
@@ -1701,6 +1704,11 @@ declare module "knex/types/tables" {
TResourceAwsAuthsInsert,
TResourceAwsAuthsUpdate
>;
+ [TableName.ResourceKubernetesAuth]: KnexOriginal.CompositeTableType<
+ TResourceKubernetesAuths,
+ TResourceKubernetesAuthsInsert,
+ TResourceKubernetesAuthsUpdate
+ >;
[TableName.GatewayPool]: KnexOriginal.CompositeTableType<TGatewayPools, TGatewayPoolsInsert, TGatewayPoolsUpdate>;
[TableName.GatewayPoolMembership]: KnexOriginal.CompositeTableType<
TGatewayPoolMemberships,
diff --git a/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts b/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts
new file mode 100644
index 0000000000..3aa4b275d6
--- /dev/null
+++ b/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts
@@ -0,0 +1,29 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.ResourceKubernetesAuth))) {
+ await knex.schema.createTable(TableName.ResourceKubernetesAuth, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("authMethodId").notNullable().unique();
+ t.foreign("authMethodId").references("id").inTable(TableName.ResourceAuthMethod).onDelete("CASCADE");
+ t.string("kubernetesHost", 255).notNullable();
+ t.binary("encryptedKubernetesCaCertificate").nullable();
+ t.binary("encryptedKubernetesTokenReviewerJwt").nullable();
+ t.string("allowedNamespaces", 1024).notNullable().defaultTo("");
+ t.string("allowedNames", 1024).notNullable().defaultTo("");
+ t.string("allowedAudience", 255).notNullable().defaultTo("");
+ t.boolean("verifyTlsCertificate").notNullable().defaultTo(true);
+ t.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.ResourceKubernetesAuth);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await dropOnUpdateTrigger(knex, TableName.ResourceKubernetesAuth);
+ await knex.schema.dropTableIfExists(TableName.ResourceKubernetesAuth);
+}
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 28d3bcb7c6..b8bb0cf131 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -200,6 +200,7 @@ export * from "./rate-limit";
export * from "./relays";
export * from "./resource-auth-methods";
export * from "./resource-aws-auths";
+export * from "./resource-kubernetes-auths";
export * from "./resource-metadata";
export * from "./resource-token-auths";
export * from "./roles";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 9e31ccc2cf..6f64803179 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -240,6 +240,7 @@ export enum TableName {
GatewayV2 = "gateways_v2",
ResourceAuthMethod = "resource_auth_methods",
ResourceAwsAuth = "resource_aws_auths",
+ ResourceKubernetesAuth = "resource_kubernetes_auths",
ResourceTokenAuth = "resource_token_auths",
GatewayPool = "gateway_pools",
GatewayPoolMembership = "gateway_pool_memberships",
diff --git a/backend/src/db/schemas/resource-kubernetes-auths.ts b/backend/src/db/schemas/resource-kubernetes-auths.ts
new file mode 100644
index 0000000000..b55aafc890
--- /dev/null
+++ b/backend/src/db/schemas/resource-kubernetes-auths.ts
@@ -0,0 +1,30 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { zodBuffer } from "@app/lib/zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const ResourceKubernetesAuthsSchema = z.object({
+ id: z.string().uuid(),
+ authMethodId: z.string().uuid(),
+ kubernetesHost: z.string(),
+ encryptedKubernetesCaCertificate: zodBuffer.nullable().optional(),
+ encryptedKubernetesTokenReviewerJwt: zodBuffer.nullable().optional(),
+ allowedNamespaces: z.string().default(""),
+ allowedNames: z.string().default(""),
+ allowedAudience: z.string().default(""),
+ verifyTlsCertificate: z.boolean().default(true),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TResourceKubernetesAuths = z.infer<typeof ResourceKubernetesAuthsSchema>;
+export type TResourceKubernetesAuthsInsert = Omit<z.input<typeof ResourceKubernetesAuthsSchema>, TImmutableDBKeys>;
+export type TResourceKubernetesAuthsUpdate = Partial<
+ Omit<z.input<typeof ResourceKubernetesAuthsSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/ee/routes/v1/kmip-server-router.ts b/backend/src/ee/routes/v1/kmip-server-router.ts
index 53d344d2a0..f0ae286e55 100644
--- a/backend/src/ee/routes/v1/kmip-server-router.ts
+++ b/backend/src/ee/routes/v1/kmip-server-router.ts
@@ -4,6 +4,7 @@ import { KmipServersSchema } from "@app/db/schemas";
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { validateAccountIds, validatePrincipalArns } from "@app/ee/services/resource-auth-method/aws-auth-validators";
import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";
+import { AuthMethodViewSchema } from "@app/ee/services/resource-auth-method/resource-auth-method-schemas";
import { ApiDocsTags } from "@app/lib/api-docs";
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
@@ -39,28 +40,6 @@ const hostnamesOrIpsField = validateAltNamesField.refine(
"Hostnames or IPs must be at most 4096 characters"
);
-const AwsAuthMethodConfigSchema = z.object({
- id: z.string().uuid(),
- stsEndpoint: z.string(),
- allowedPrincipalArns: z.string(),
- allowedAccountIds: z.string(),
- createdAt: z.date(),
- updatedAt: z.date()
-});
-
-const TokenAuthMethodConfigSchema = z.object({});
-
-const IdentityAuthMethodConfigSchema = z.object({
- identityId: z.string(),
- identityName: z.string().nullable()
-});
-
-const AuthMethodViewSchema = z.discriminatedUnion("method", [
- z.object({ method: z.literal(ResourceAuthMethodType.Aws), config: AwsAuthMethodConfigSchema }),
- z.object({ method: z.literal(ResourceAuthMethodType.Token), config: TokenAuthMethodConfigSchema }),
- z.object({ method: z.literal(ResourceAuthMethodType.Identity), config: IdentityAuthMethodConfigSchema })
-]);
-
const KmipServerWithAuthMethodSchema = SanitizedKmipServerSchema.extend({
authMethod: AuthMethodViewSchema
});
diff --git a/backend/src/ee/routes/v2/relay-router.ts b/backend/src/ee/routes/v2/relay-router.ts
index 964660d46d..066e355ba9 100644
--- a/backend/src/ee/routes/v2/relay-router.ts
+++ b/backend/src/ee/routes/v2/relay-router.ts
@@ -4,6 +4,7 @@ import { RelaysSchema } from "@app/db/schemas";
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { validateAccountIds, validatePrincipalArns } from "@app/ee/services/resource-auth-method/aws-auth-validators";
import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";
+import { AuthMethodViewSchema } from "@app/ee/services/resource-auth-method/resource-auth-method-schemas";
import { UnauthorizedError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
@@ -24,28 +25,6 @@ const SanitizedRelaySchema = RelaysSchema.pick({
canRevoke: z.boolean()
});
-const AwsAuthMethodConfigSchema = z.object({
- id: z.string().uuid(),
- stsEndpoint: z.string(),
- allowedPrincipalArns: z.string(),
- allowedAccountIds: z.string(),
- createdAt: z.date(),
- updatedAt: z.date()
-});
-
-const TokenAuthMethodConfigSchema = z.object({});
-
-const IdentityAuthMethodConfigSchema = z.object({
- identityId: z.string(),
- identityName: z.string().nullable()
-});
-
-const AuthMethodViewSchema = z.discriminatedUnion("method", [
- z.object({ method: z.literal(ResourceAuthMethodType.Aws), config: AwsAuthMethodConfigSchema }),
- z.object({ method: z.literal(ResourceAuthMethodType.Token), config: TokenAuthMethodConfigSchema }),
- z.object({ method: z.literal(ResourceAuthMethodType.Identity), config: IdentityAuthMethodConfigSchema })
-]);
-
const RelayWithAuthMethodSchema = SanitizedRelaySchema.extend({
authMethod: AuthMethodViewSchema
});
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
index 80d0440ab6..e69642d281 100644
--- a/backend/src/ee/routes/v3/gateway-router.ts
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -3,7 +3,12 @@ import z from "zod";
import { GatewaysV2Schema } from "@app/db/schemas";
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { validateAccountIds, validatePrincipalArns } from "@app/ee/services/resource-auth-method/aws-auth-validators";
+import {
+ validateAllowedNames,
+ validateAllowedNamespaces
+} from "@app/ee/services/resource-auth-method/kubernetes-auth-validators";
import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";
+import { AuthMethodViewSchema } from "@app/ee/services/resource-auth-method/resource-auth-method-schemas";
import { ApiDocsTags, GATEWAYS } from "@app/lib/api-docs";
import { UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -28,28 +33,6 @@ const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
canRevoke: z.boolean()
});
-const AwsAuthMethodConfigSchema = z.object({
- id: z.string().uuid(),
- stsEndpoint: z.string(),
- allowedPrincipalArns: z.string(),
- allowedAccountIds: z.string(),
- createdAt: z.date(),
- updatedAt: z.date()
-});
-
-const TokenAuthMethodConfigSchema = z.object({});
-
-const IdentityAuthMethodConfigSchema = z.object({
- identityId: z.string(),
- identityName: z.string().nullable()
-});
-
-const AuthMethodViewSchema = z.discriminatedUnion("method", [
- z.object({ method: z.literal(ResourceAuthMethodType.Aws), config: AwsAuthMethodConfigSchema }),
- z.object({ method: z.literal(ResourceAuthMethodType.Token), config: TokenAuthMethodConfigSchema }),
- z.object({ method: z.literal(ResourceAuthMethodType.Identity), config: IdentityAuthMethodConfigSchema })
-]);
-
const GatewayWithAuthMethodSchema = SanitizedGatewayV2Schema.extend({
authMethod: AuthMethodViewSchema
});
@@ -74,12 +57,101 @@ const AwsAuthMethodInputSchema = z
path: ["allowedPrincipalArns"]
});
+const KubernetesAuthMethodInputSchema = z
+ .object({
+ method: z.literal(ResourceAuthMethodType.Kubernetes),
+ kubernetesHost: z
+ .string()
+ .trim()
+ .min(1)
+ .max(255)
+ .describe(GATEWAYS.AUTH_METHOD.kubernetesHost)
+ .refine((host) => !host.startsWith("http://"), "Kubernetes host must use https")
+ .refine(
+ (host) =>
+ z
+ .string()
+ .url()
+ .safeParse(host.startsWith("https://") ? host : `https://${host}`).success,
+ "Kubernetes host must be a valid URL"
+ ),
+ caCertificate: z.string().trim().max(10240).optional().describe(GATEWAYS.AUTH_METHOD.caCertificate),
+ tokenReviewerJwt: z.string().trim().max(8192).optional().describe(GATEWAYS.AUTH_METHOD.tokenReviewerJwt),
+ allowedNamespaces: validateAllowedNamespaces.describe(GATEWAYS.AUTH_METHOD.allowedNamespaces),
+ allowedNames: validateAllowedNames.describe(GATEWAYS.AUTH_METHOD.allowedNames),
+ allowedAudience: z.string().trim().max(255).default("").describe(GATEWAYS.AUTH_METHOD.allowedAudience),
+ verifyTlsCertificate: z.boolean().default(true).describe(GATEWAYS.AUTH_METHOD.verifyTlsCertificate)
+ })
+ .refine((data) => data.allowedNamespaces.trim().length > 0 || data.allowedNames.trim().length > 0, {
+ message: "At least one of allowedNamespaces or allowedNames must be set",
+ path: ["allowedNamespaces"]
+ });
+
const TokenAuthMethodInputSchema = z.object({
method: z.literal(ResourceAuthMethodType.Token)
});
// Settable methods only — `identity` is read-only and never accepted as input.
-const SettableAuthMethodInputSchema = z.union([AwsAuthMethodInputSchema, TokenAuthMethodInputSchema]);
+const SettableAuthMethodInputSchema = z.union([
+ AwsAuthMethodInputSchema,
+ KubernetesAuthMethodInputSchema,
+ TokenAuthMethodInputSchema
+]);
+
+type TSettableAuthMethodInput = z.infer<typeof SettableAuthMethodInputSchema>;
+
+// createGateway takes { method, config }; setMethod takes the config flattened onto the method.
+const toCreateAuthMethodArg = (input: TSettableAuthMethodInput) => {
+ if (input.method === ResourceAuthMethodType.Aws) {
+ return {
+ method: ResourceAuthMethodType.Aws,
+ config: {
+ stsEndpoint: input.stsEndpoint,
+ allowedPrincipalArns: input.allowedPrincipalArns,
+ allowedAccountIds: input.allowedAccountIds
+ }
+ } as const;
+ }
+ if (input.method === ResourceAuthMethodType.Kubernetes) {
+ return {
+ method: ResourceAuthMethodType.Kubernetes,
+ config: {
+ kubernetesHost: input.kubernetesHost,
+ caCertificate: input.caCertificate,
+ tokenReviewerJwt: input.tokenReviewerJwt,
+ allowedNamespaces: input.allowedNamespaces,
+ allowedNames: input.allowedNames,
+ allowedAudience: input.allowedAudience,
+ verifyTlsCertificate: input.verifyTlsCertificate
+ }
+ } as const;
+ }
+ return { method: ResourceAuthMethodType.Token } as const;
+};
+
+const toSetAuthMethodArg = (input: TSettableAuthMethodInput) => {
+ if (input.method === ResourceAuthMethodType.Aws) {
+ return {
+ method: ResourceAuthMethodType.Aws,
+ stsEndpoint: input.stsEndpoint,
+ allowedPrincipalArns: input.allowedPrincipalArns,
+ allowedAccountIds: input.allowedAccountIds
+ } as const;
+ }
+ if (input.method === ResourceAuthMethodType.Kubernetes) {
+ return {
+ method: ResourceAuthMethodType.Kubernetes,
+ kubernetesHost: input.kubernetesHost,
+ caCertificate: input.caCertificate,
+ tokenReviewerJwt: input.tokenReviewerJwt,
+ allowedNamespaces: input.allowedNamespaces,
+ allowedNames: input.allowedNames,
+ allowedAudience: input.allowedAudience,
+ verifyTlsCertificate: input.verifyTlsCertificate
+ } as const;
+ }
+ return { method: ResourceAuthMethodType.Token } as const;
+};
export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
// ─── POST / ──────────────────────────────────────────────────────────────
@@ -102,17 +174,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const authMethodArg =
- req.body.authMethod.method === ResourceAuthMethodType.Aws
- ? {
- method: ResourceAuthMethodType.Aws,
- config: {
- stsEndpoint: req.body.authMethod.stsEndpoint,
- allowedPrincipalArns: req.body.authMethod.allowedPrincipalArns,
- allowedAccountIds: req.body.authMethod.allowedAccountIds
- }
- }
- : { method: ResourceAuthMethodType.Token };
+ const authMethodArg = toCreateAuthMethodArg(req.body.authMethod);
const gateway = await server.services.gatewayV2.createGateway({
orgId: req.permission.orgId,
@@ -183,15 +245,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
if (req.body.authMethod) {
- const setInput =
- req.body.authMethod.method === ResourceAuthMethodType.Aws
- ? {
- method: ResourceAuthMethodType.Aws,
- stsEndpoint: req.body.authMethod.stsEndpoint,
- allowedPrincipalArns: req.body.authMethod.allowedPrincipalArns,
- allowedAccountIds: req.body.authMethod.allowedAccountIds
- }
- : { method: ResourceAuthMethodType.Token };
+ const setInput = toSetAuthMethodArg(req.body.authMethod);
const result = await server.services.resourceAuthMethod.setMethod({
resource: { type: "gateway", id: req.params.gatewayId },
@@ -207,14 +261,25 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
metadata: {
resourceType: "gateway",
resourceId: req.params.gatewayId,
- method: result.method as "aws" | "token",
- methodConfigId: result.method === ResourceAuthMethodType.Aws ? result.config.id : req.params.gatewayId,
+ method: result.method as "aws" | "kubernetes" | "token",
+ methodConfigId:
+ result.method === ResourceAuthMethodType.Aws || result.method === ResourceAuthMethodType.Kubernetes
+ ? result.config.id
+ : req.params.gatewayId,
...(result.method === ResourceAuthMethodType.Aws
? {
stsEndpoint: result.config.stsEndpoint,
allowedPrincipalArns: result.config.allowedPrincipalArns,
allowedAccountIds: result.config.allowedAccountIds
}
+ : {}),
+ ...(result.method === ResourceAuthMethodType.Kubernetes
+ ? {
+ kubernetesHost: result.config.kubernetesHost,
+ allowedNamespaces: result.config.allowedNamespaces,
+ allowedNames: result.config.allowedNames,
+ allowedAudience: result.config.allowedAudience
+ }
: {})
}
}
@@ -229,7 +294,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
resourceType: "gateway",
resourceId: req.params.gatewayId,
orgId: req.permission.orgId,
- method: result.method as "aws" | "token"
+ method: result.method as "aws" | "kubernetes" | "token"
}
})
.catch((err) => {
@@ -296,7 +361,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
params: z.object({ gatewayId: z.string().trim().uuid() }),
response: {
200: z.object({
- method: z.enum(["aws", "token"])
+ method: z.enum(["aws", "kubernetes", "token"])
})
}
},
@@ -326,7 +391,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
});
// ─── POST /login ─────────────────────────────────────────────────────────
- // Gateway login. Discriminated body covers both methods. Single rate limit (10/min).
+ // Gateway login. Discriminated body covers every method. Single rate limit (10/min).
server.route({
method: "POST",
url: "/login",
@@ -334,7 +399,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
schema: {
operationId: "loginGateway",
tags: [ApiDocsTags.GatewaysV3],
- description: "Gateway login. Body discriminates on `method` for AWS or token authentication.",
+ description: "Gateway login. Body discriminates on `method` for AWS, Kubernetes, or token authentication.",
body: z.discriminatedUnion("method", [
z.object({
method: z.literal(ResourceAuthMethodType.Aws),
@@ -343,6 +408,11 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
iamRequestBody: z.string().describe(GATEWAYS.LOGIN.iamRequestBody),
iamRequestHeaders: z.string().describe(GATEWAYS.LOGIN.iamRequestHeaders)
}),
+ z.object({
+ method: z.literal(ResourceAuthMethodType.Kubernetes),
+ gatewayId: z.string().trim().uuid().describe(GATEWAYS.LOGIN.gatewayId),
+ jwt: z.string().trim().min(1).max(8192).describe(GATEWAYS.LOGIN.jwt)
+ }),
z.object({
method: z.literal(ResourceAuthMethodType.Token),
token: z.string().min(1).describe(GATEWAYS.LOGIN.token)
@@ -436,6 +506,83 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
}
}
+ if (req.body.method === ResourceAuthMethodType.Kubernetes) {
+ try {
+ const result = await server.services.resourceAuthMethod.loginWithKubernetes({
+ resource: { type: "gateway", id: req.body.gatewayId },
+ jwt: req.body.jwt
+ });
+
+ await server.services.auditLog
+ .createAuditLog({
+ orgId: result.orgId,
+ actor: { type: ActorType.GATEWAY, metadata: { gatewayId: result.resourceId } },
+ event: {
+ type: EventType.RESOURCE_AUTH_METHOD_LOGIN,
+ metadata: {
+ resourceType: "gateway",
+ resourceId: result.resourceId,
+ method: "kubernetes",
+ methodConfigId: result.configId,
+ kubernetesNamespace: result.namespace,
+ kubernetesServiceAccountName: result.serviceAccountName
+ }
+ },
+ ipAddress: req.ip,
+ userAgent: req.headers["user-agent"] ?? "",
+ userAgentType: UserAgentType.OTHER
+ })
+ .catch(() => {});
+
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.ResourceAuthMethodLogin,
+ distinctId: `gateway-${result.resourceId}`,
+ organizationId: result.orgId,
+ properties: {
+ resourceType: "gateway",
+ resourceId: result.resourceId,
+ orgId: result.orgId,
+ method: "kubernetes"
+ }
+ })
+ .catch((err) => {
+ logger.error(err, `Failed to send telemetry [gatewayId=${result.resourceId}]`);
+ });
+
+ return {
+ accessToken: result.accessToken,
+ gatewayId: result.resourceId,
+ tokenType: "Bearer" as const
+ };
+ } catch (error) {
+ if (error instanceof UnauthorizedError && error.detail?.resourceId) {
+ await server.services.auditLog
+ .createAuditLog({
+ orgId: error.detail.orgId as string,
+ actor: { type: ActorType.GATEWAY, metadata: { gatewayId: error.detail.resourceId as string } },
+ event: {
+ type: EventType.RESOURCE_AUTH_METHOD_LOGIN_FAILED,
+ metadata: {
+ resourceType: "gateway",
+ resourceId: error.detail.resourceId as string,
+ method: "kubernetes",
+ reasonCode: error.detail.reasonCode as string,
+ message: error.message,
+ kubernetesNamespace: error.detail.namespace as string | undefined,
+ kubernetesServiceAccountName: error.detail.serviceAccountName as string | undefined
+ }
+ },
+ ipAddress: req.ip,
+ userAgent: req.headers["user-agent"] ?? "",
+ userAgentType: UserAgentType.OTHER
+ })
+ .catch(() => {});
+ }
+ throw error;
+ }
+ }
+
const result = await server.services.resourceAuthMethod.loginWithToken({
token: req.body.token,
expectedResourceType: "gateway"
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5b5d31b571..a15bf834b9 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -6736,7 +6736,7 @@ interface GatewayEnrollEvent {
};
}
-type ResourceAuthMethodKind = "aws" | "token";
+type ResourceAuthMethodKind = "aws" | "kubernetes" | "token";
type ResourceAuthMethodResourceType = "gateway" | "relay" | "kmip";
interface ResourceAuthMethodLoginEvent {
@@ -6749,6 +6749,8 @@ interface ResourceAuthMethodLoginEvent {
principalArn?: string;
accountId?: string;
enrollmentTokenId?: string;
+ kubernetesNamespace?: string;
+ kubernetesServiceAccountName?: string;
};
}
@@ -6762,6 +6764,8 @@ interface ResourceAuthMethodLoginFailedEvent {
message: string;
principalArn?: string;
accountId?: string;
+ kubernetesNamespace?: string;
+ kubernetesServiceAccountName?: string;
};
}
@@ -6775,6 +6779,10 @@ interface ResourceAuthMethodUpdateEvent {
stsEndpoint?: string;
allowedPrincipalArns?: string;
allowedAccountIds?: string;
+ kubernetesHost?: string;
+ allowedNamespaces?: string;
+ allowedNames?: string;
+ allowedAudience?: string;
};
}
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index d5eb46c931..fc1a455912 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -37,7 +37,7 @@ import { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-co
import { TRelayDALFactory } from "../relay/relay-dal";
import { TRelayServiceFactory } from "../relay/relay-service";
import { TResourceAuthMethodServiceFactory } from "../resource-auth-method/resource-auth-method-service";
-import { TAwsAuthMethodConfig } from "../resource-auth-method/resource-auth-method-types";
+import { TAwsAuthMethodConfig, TKubernetesAuthMethodConfig } from "../resource-auth-method/resource-auth-method-types";
import {
DEFAULT_HEARTBEAT_TTL,
GATEWAY_ACTOR_OID,
@@ -67,7 +67,13 @@ type TGatewayV2ServiceFactoryDep = {
pkiDiscoveryConfigDAL: Pick<TPkiDiscoveryConfigDALFactory, "findByGatewayId" | "countByGatewayId">;
resourceAuthMethodService: Pick<
TResourceAuthMethodServiceFactory,
- "initAtCreate" | "loadView" | "mintToken" | "loginWithToken"
+ | "initAtCreate"
+ | "loadView"
+ | "mintToken"
+ | "loginWithToken"
+ | "encryptKubernetesSecrets"
+ | "assertKubernetesHostAllowed"
+ | "validateKubernetesConfigReachable"
>;
};
@@ -1186,7 +1192,10 @@ export const gatewayV2ServiceFactory = ({
actorType: ActorType;
actorAuthMethod: ActorAuthMethod;
name: string;
- authMethod: { method: "aws"; config: TAwsAuthMethodConfig } | { method: "token" };
+ authMethod:
+ | { method: "aws"; config: TAwsAuthMethodConfig }
+ | { method: "kubernetes"; config: TKubernetesAuthMethodConfig }
+ | { method: "token" };
}) => {
const { permission } = await permissionService.getOrgPermission({
actor: actorType,
@@ -1202,6 +1211,26 @@ export const gatewayV2ServiceFactory = ({
OrgPermissionSubjects.Gateway
);
+ // The host check (DNS) and the secret encryption (possibly an external KMS) both reach
+ // the network, so they run before the transaction is opened rather than inside it.
+ let authMethodArg = authMethod;
+ if (authMethod.method === "kubernetes") {
+ await resourceAuthMethodService.assertKubernetesHostAllowed(authMethod.config.kubernetesHost);
+ await resourceAuthMethodService.validateKubernetesConfigReachable({
+ kubernetesHost: authMethod.config.kubernetesHost,
+ caCertificate: authMethod.config.caCertificate,
+ tokenReviewerJwt: authMethod.config.tokenReviewerJwt,
+ verifyTlsCertificate: authMethod.config.verifyTlsCertificate
+ });
+ authMethodArg = {
+ method: authMethod.method,
+ config: {
+ ...authMethod.config,
+ ...(await resourceAuthMethodService.encryptKubernetesSecrets(orgId, authMethod.config))
+ }
+ };
+ }
+
const gateway = await gatewayV2DAL.transaction(async (tx) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateGateway(orgId)]);
@@ -1227,7 +1256,10 @@ export const gatewayV2ServiceFactory = ({
throw err;
}
- await resourceAuthMethodService.initAtCreate({ resource: { type: "gateway", id: created.id }, authMethod }, tx);
+ await resourceAuthMethodService.initAtCreate(
+ { resource: { type: "gateway", id: created.id }, authMethod: authMethodArg },
+ tx
+ );
return created;
});
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-auth-dal.ts b/backend/src/ee/services/resource-auth-method/kubernetes-auth-dal.ts
new file mode 100644
index 0000000000..97033dbd59
--- /dev/null
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-auth-dal.ts
@@ -0,0 +1,9 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TResourceKubernetesAuthDALFactory = ReturnType<typeof resourceKubernetesAuthDALFactory>;
+
+export const resourceKubernetesAuthDALFactory = (db: TDbClient) => {
+ return ormify(db, TableName.ResourceKubernetesAuth);
+};
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts b/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts
new file mode 100644
index 0000000000..ea59562c17
--- /dev/null
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts
@@ -0,0 +1,257 @@
+import { isIP } from "node:net";
+
+import { AxiosError } from "axios";
+import https from "https";
+import picomatch from "picomatch";
+import RE2 from "re2";
+
+import { request } from "@app/lib/config/request";
+import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+import {
+ handleAxiosError,
+ KubernetesAuthErrorContext
+} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-error-handlers";
+import { extractK8sUsername } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-fns";
+import { TCreateTokenReviewResponse } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
+import {
+ validateKubernetesHostConnectivity,
+ validateTokenReviewerPermissions
+} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-validators";
+
+const TOKEN_REVIEW_TIMEOUT_MS = 10_000;
+
+// The host is operator-supplied and the backend POSTs to it on every login, so without this an
+// org admin could use the auth config to reach hosts inside our own network. Does a DNS lookup,
+// so call it outside a transaction.
+export const assertKubernetesHostAllowed = async (kubernetesHost: string) => {
+ const url = kubernetesHost.startsWith("https://") ? kubernetesHost : `https://${kubernetesHost}`;
+ try {
+ await blockLocalAndPrivateIpAddresses(url);
+ } catch (err) {
+ if (err instanceof BadRequestError) {
+ throw new BadRequestError({
+ message: `Kubernetes host '${kubernetesHost}' is not an allowed address: ${err.message}. Use an address Infisical can reach over the public internet, or use Token or AWS auth for a private cluster.`
+ });
+ }
+ throw err;
+ }
+};
+
+// Verification is impossible without a CA, since cluster CAs are in no public trust store.
+export const resolveEffectiveVerifyTlsCertificate = (caCertificate: string, storedVerify: boolean) => {
+ if (!caCertificate.length) return false;
+ return storedVerify;
+};
+
+// Surfaces a bad host or reviewer when the config is saved rather than when a gateway later
+// fails to start. Makes network calls, so call it outside a transaction.
+export const validateKubernetesConfigReachable = async ({
+ kubernetesHost,
+ caCertificate,
+ tokenReviewerJwt,
+ verifyTlsCertificate
+}: {
+ kubernetesHost: string;
+ caCertificate?: string;
+ tokenReviewerJwt?: string;
+ verifyTlsCertificate: boolean;
+}) => {
+ const host = kubernetesHost.startsWith("https://") ? kubernetesHost : `https://${kubernetesHost}`;
+ const effectiveVerify = resolveEffectiveVerifyTlsCertificate(caCertificate ?? "", verifyTlsCertificate);
+
+ await validateKubernetesHostConnectivity({
+ kubernetesHost: host,
+ caCert: caCertificate,
+ verifyTlsCertificate: effectiveVerify
+ });
+
+ if (tokenReviewerJwt) {
+ await validateTokenReviewerPermissions({
+ kubernetesHost: host,
+ tokenReviewerJwt,
+ caCert: caCertificate,
+ verifyTlsCertificate: effectiveVerify
+ });
+ }
+};
+
+// Undefined for a bare IP: SNI carries host names only, so an IP host is matched on IP SANs.
+const toServerName = (kubernetesHost: string) => {
+ let servername = new RE2("^https?://").replace(kubernetesHost, "");
+ const lastColonIndex = servername.lastIndexOf(":");
+ if (lastColonIndex !== -1) {
+ servername = servername.substring(0, lastColonIndex);
+ }
+ return isIP(servername) ? undefined : servername;
+};
+
+type TReviewServiceAccountTokenInput = {
+ jwt: string;
+ kubernetesHost: string;
+ caCertificate: string;
+ tokenReviewerJwt: string;
+ verifyTlsCertificate: boolean;
+ allowedAudience: string;
+ errorContext: Record<string, unknown>;
+};
+
+export const reviewServiceAccountToken = async ({
+ jwt,
+ kubernetesHost,
+ caCertificate,
+ tokenReviewerJwt,
+ verifyTlsCertificate,
+ allowedAudience,
+ errorContext
+}: TReviewServiceAccountTokenInput) => {
+ const baseUrl =
+ kubernetesHost.startsWith("http://") || kubernetesHost.startsWith("https://")
+ ? kubernetesHost
+ : `https://${kubernetesHost}`;
+
+ let review: TCreateTokenReviewResponse;
+ try {
+ const res = await request.post<TCreateTokenReviewResponse>(
+ `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`,
+ {
+ apiVersion: "authentication.k8s.io/v1",
+ kind: "TokenReview",
+ spec: {
+ token: jwt,
+ ...(allowedAudience ? { audiences: [allowedAudience] } : {})
+ }
+ },
+ {
+ headers: {
+ "Content-Type": "application/json",
+ // With no reviewer configured the incoming token reviews itself, which works because the
+ // Helm chart grants the gateway's service account system:auth-delegator.
+ Authorization: `Bearer ${tokenReviewerJwt || jwt}`
+ },
+ signal: AbortSignal.timeout(TOKEN_REVIEW_TIMEOUT_MS),
+ timeout: TOKEN_REVIEW_TIMEOUT_MS,
+ httpsAgent: new https.Agent({
+ ca: caCertificate || undefined,
+ rejectUnauthorized: resolveEffectiveVerifyTlsCertificate(caCertificate, verifyTlsCertificate),
+ servername: toServerName(kubernetesHost)
+ })
+ }
+ );
+ review = res.data;
+ } catch (err) {
+ const isAxiosError = err instanceof AxiosError;
+ const status = isAxiosError ? err.response?.status : undefined;
+ // Never log the error object itself: an AxiosError carries `config.data`, which is the
+ // TokenReview body, which contains the service account token.
+ logger.error(
+ { kubernetesHost, status, code: isAxiosError ? err.code : undefined, reason: (err as Error).message },
+ `Resource Kubernetes Auth Login: token review request failed [resourceId=${String(errorContext.resourceId)}] [kubernetesHost=${kubernetesHost}]`
+ );
+
+ // Borrow the identity Kubernetes auth wording, but keep our own error type and reason code
+ // so the audit log still records why the login failed.
+ const reasonCode = status === 401 || status === 403 ? "token_review_forbidden" : "token_review_request_failed";
+ const message = isAxiosError
+ ? handleAxiosError(err, { kubernetesHost }, KubernetesAuthErrorContext.KubernetesApiServer).message
+ : `Could not reach the Kubernetes API server at ${kubernetesHost} to review the service account token.`;
+
+ throw new UnauthorizedError({ message, detail: { reasonCode, ...errorContext } });
+ }
+
+ if (!review?.status) {
+ throw new UnauthorizedError({
+ message: "The Kubernetes API server returned an unexpected token review response.",
+ detail: { reasonCode: "token_review_malformed_response", ...errorContext }
+ });
+ }
+
+ if ("error" in review.status) {
+ throw new UnauthorizedError({
+ message: `Kubernetes token review failed: ${review.status.error}`,
+ detail: { reasonCode: "token_review_error", ...errorContext }
+ });
+ }
+
+ if (!review.status.authenticated) {
+ throw new UnauthorizedError({
+ message: "Access denied: the Kubernetes service account token is not authenticated.",
+ detail: { reasonCode: "token_not_authenticated", ...errorContext }
+ });
+ }
+
+ const { username } = review.status.user;
+ let reviewed: { namespace: string; name: string };
+ try {
+ reviewed = extractK8sUsername(username);
+ } catch {
+ throw new UnauthorizedError({
+ message: `Access denied: '${username}' is not a Kubernetes service account. The gateway must authenticate with a service account token.`,
+ detail: { reasonCode: "not_a_service_account", ...errorContext }
+ });
+ }
+
+ return {
+ namespace: reviewed.namespace,
+ serviceAccountName: reviewed.name,
+ audiences: review.status.audiences ?? []
+ };
+};
+
+const matchesAnyPattern = (value: string, csv: string) =>
+ csv
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0)
+ .some((entry) => entry === value || picomatch.isMatch(value, entry));
+
+type TValidateAllowlistsInput = {
+ namespace: string;
+ serviceAccountName: string;
+ audiences: string[];
+ allowedNamespaces: string;
+ allowedNames: string;
+ allowedAudience: string;
+ errorContext: Record<string, unknown>;
+};
+
+export const validateKubernetesAllowlists = ({
+ namespace,
+ serviceAccountName,
+ audiences,
+ allowedNamespaces,
+ allowedNames,
+ allowedAudience,
+ errorContext
+}: TValidateAllowlistsInput) => {
+ // The route schema enforces this too, but reaching here with no allowlist would let any pod
+ // in the cluster enroll.
+ if (!allowedNamespaces.trim() && !allowedNames.trim()) {
+ throw new UnauthorizedError({
+ message: "Access denied: Kubernetes auth method has no allowlist configured.",
+ detail: { reasonCode: "no_allowlist_configured", ...errorContext }
+ });
+ }
+
+ if (allowedNamespaces.trim() && !matchesAnyPattern(namespace, allowedNamespaces)) {
+ throw new UnauthorizedError({
+ message: `Access denied: Kubernetes namespace '${namespace}' is not allowed.`,
+ detail: { reasonCode: "namespace_not_allowed", namespace, serviceAccountName, ...errorContext }
+ });
+ }
+
+ if (allowedNames.trim() && !matchesAnyPattern(serviceAccountName, allowedNames)) {
+ throw new UnauthorizedError({
+ message: `Access denied: Kubernetes service account '${serviceAccountName}' is not allowed.`,
+ detail: { reasonCode: "name_not_allowed", namespace, serviceAccountName, ...errorContext }
+ });
+ }
+
+ if (allowedAudience.trim() && !audiences.includes(allowedAudience)) {
+ throw new UnauthorizedError({
+ message: `Access denied: the service account token does not carry the required audience '${allowedAudience}'.`,
+ detail: { reasonCode: "audience_not_allowed", namespace, serviceAccountName, ...errorContext }
+ });
+ }
+};
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-auth-validators.ts b/backend/src/ee/services/resource-auth-method/kubernetes-auth-validators.ts
new file mode 100644
index 0000000000..a1970a7174
--- /dev/null
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-auth-validators.ts
@@ -0,0 +1,37 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+// Namespaces are RFC 1123 labels; service account names are RFC 1123 subdomains, which also
+// permit dots. Bounding the character set keeps an entry from matching more than it looks like it
+// does once it reaches picomatch.
+const namespaceEntry = new RE2("^[a-z0-9*]([a-z0-9*-]{0,61}[a-z0-9*])?$");
+const nameEntry = new RE2("^[a-z0-9*]([a-z0-9*.-]{0,251}[a-z0-9*])?$");
+
+const csvOf = (pattern: RE2, field: string, max: number, allowed: string) =>
+ z
+ .string()
+ .trim()
+ .max(max)
+ .refine(
+ (value) =>
+ value
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter((entry) => entry.length > 0)
+ .every((entry) => pattern.test(entry)),
+ { message: `${field} must be a comma-separated list of ${allowed}, optionally containing "*" wildcards` }
+ );
+
+export const validateAllowedNamespaces = csvOf(
+ namespaceEntry,
+ "Allowed namespaces",
+ 1024,
+ "lowercase Kubernetes namespace names"
+);
+
+export const validateAllowedNames = csvOf(
+ nameEntry,
+ "Allowed service account names",
+ 1024,
+ "lowercase Kubernetes service account names"
+);
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts
index 3b448a381d..b2f727be8f 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts
@@ -115,14 +115,16 @@ export const assertKmipServerResource = (resource: { type: string }, methodName:
// All auth method values surfaced anywhere in the system.
//
-// - 'aws' / 'token' — stored in resource_auth_methods.method, settable via the API.
-// - 'identity' — legacy state, derived from gateways_v2.identityId. Returned in
-// the API view but never stored in the registry and never
-// accepted as input to set/mint operations. The "settable" subset
-// is enforced by the discriminated TSetAuthMethodInput type
-// (which only accepts aws/token), not by this enum-like const.
+// - 'aws' / 'kubernetes' / 'token': stored in resource_auth_methods.method and settable
+// via the API.
+// - 'identity': legacy state, derived from gateways_v2.identityId. Returned in the API
+// view but never stored in the registry and never accepted as input to set/mint
+// operations. The "settable" subset is enforced by the discriminated
+// TSetAuthMethodInput type (which only accepts aws/kubernetes/token), not by this
+// enum-like const.
export const ResourceAuthMethodType = {
Aws: "aws",
+ Kubernetes: "kubernetes",
Token: "token",
Identity: "identity"
} as const;
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-schemas.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-schemas.ts
new file mode 100644
index 0000000000..03165d6595
--- /dev/null
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-schemas.ts
@@ -0,0 +1,39 @@
+import { z } from "zod";
+
+import { ResourceAuthMethodType } from "./resource-auth-method-fns";
+
+export const AwsAuthMethodConfigSchema = z.object({
+ id: z.string().uuid(),
+ stsEndpoint: z.string(),
+ allowedPrincipalArns: z.string(),
+ allowedAccountIds: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export const KubernetesAuthMethodConfigSchema = z.object({
+ id: z.string().uuid(),
+ kubernetesHost: z.string(),
+ allowedNamespaces: z.string(),
+ allowedNames: z.string(),
+ allowedAudience: z.string(),
+ verifyTlsCertificate: z.boolean(),
+ caCertificate: z.string(),
+ hasTokenReviewerJwt: z.boolean(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export const TokenAuthMethodConfigSchema = z.object({});
+
+export const IdentityAuthMethodConfigSchema = z.object({
+ identityId: z.string(),
+ identityName: z.string().nullable()
+});
+
+export const AuthMethodViewSchema = z.discriminatedUnion("method", [
+ z.object({ method: z.literal(ResourceAuthMethodType.Aws), config: AwsAuthMethodConfigSchema }),
+ z.object({ method: z.literal(ResourceAuthMethodType.Kubernetes), config: KubernetesAuthMethodConfigSchema }),
+ z.object({ method: z.literal(ResourceAuthMethodType.Token), config: TokenAuthMethodConfigSchema }),
+ z.object({ method: z.literal(ResourceAuthMethodType.Identity), config: IdentityAuthMethodConfigSchema })
+]);
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
index 5a8deedfab..c049a2c4f0 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
@@ -5,6 +5,8 @@ import { OrganizationActionScope } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
import { TKmipServerDALFactory } from "../kmip-server/kmip-server-dal";
@@ -18,6 +20,13 @@ import { TPermissionServiceFactory } from "../permission/permission-service-type
import { TRelayDALFactory } from "../relay/relay-dal";
import { TResourceAwsAuthDALFactory } from "./aws-auth-dal";
import { validateAllowlists, verifyStsAndExtractCaller } from "./aws-auth-fns";
+import { TResourceKubernetesAuthDALFactory } from "./kubernetes-auth-dal";
+import {
+ assertKubernetesHostAllowed,
+ reviewServiceAccountToken,
+ validateKubernetesAllowlists,
+ validateKubernetesConfigReachable
+} from "./kubernetes-auth-fns";
import { TResourceAuthMethodDALFactory } from "./resource-auth-method-dal";
import {
assertGatewayResource,
@@ -35,8 +44,11 @@ import {
import {
TAuthMethodView,
TAwsAuthMethodConfig,
+ TEncryptedKubernetesSecrets,
TGetAuthMethodDTO,
+ TKubernetesAuthMethodConfig,
TLoginWithAwsDTO,
+ TLoginWithKubernetesDTO,
TLoginWithTokenDTO,
TMintTokenDTO,
TRevokeTokenDTO,
@@ -56,7 +68,9 @@ const $generateEnrollmentToken = () => {
type TResourceAuthMethodServiceFactoryDep = {
resourceAuthMethodDAL: TResourceAuthMethodDALFactory;
resourceAwsAuthDAL: TResourceAwsAuthDALFactory;
+ resourceKubernetesAuthDAL: TResourceKubernetesAuthDALFactory;
resourceTokenAuthDAL: TResourceTokenAuthDALFactory;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById" | "updateById">;
relayDAL: Pick<TRelayDALFactory, "findById" | "updateById">;
kmipServerDAL: Pick<TKmipServerDALFactory, "findById" | "updateById">;
@@ -96,7 +110,9 @@ type TBasicResource = { id: string; name: string; orgId: string | null; identity
export const resourceAuthMethodServiceFactory = ({
resourceAuthMethodDAL,
resourceAwsAuthDAL,
+ resourceKubernetesAuthDAL,
resourceTokenAuthDAL,
+ kmsService,
gatewayV2DAL,
relayDAL,
kmipServerDAL,
@@ -222,6 +238,38 @@ export const resourceAuthMethodServiceFactory = ({
};
}
+ if (registry.method === ResourceAuthMethodType.Kubernetes) {
+ const config = await resourceKubernetesAuthDAL.findOne({ authMethodId: registry.id });
+ if (!config) {
+ throw new NotFoundError({ message: `Kubernetes auth config missing for ${resource.type}` });
+ }
+
+ let caCertificate = "";
+ if (config.encryptedKubernetesCaCertificate && loaded.orgId) {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId: loaded.orgId
+ });
+ caCertificate = decryptor({ cipherTextBlob: config.encryptedKubernetesCaCertificate }).toString();
+ }
+
+ return {
+ method: ResourceAuthMethodType.Kubernetes,
+ config: {
+ id: config.id,
+ kubernetesHost: config.kubernetesHost,
+ allowedNamespaces: config.allowedNamespaces,
+ allowedNames: config.allowedNames,
+ allowedAudience: config.allowedAudience,
+ verifyTlsCertificate: config.verifyTlsCertificate,
+ caCertificate,
+ hasTokenReviewerJwt: Boolean(config.encryptedKubernetesTokenReviewerJwt),
+ createdAt: config.createdAt,
+ updatedAt: config.updatedAt
+ }
+ };
+ }
+
if (registry.method === ResourceAuthMethodType.Token) {
return {
method: ResourceAuthMethodType.Token,
@@ -296,6 +344,33 @@ export const resourceAuthMethodServiceFactory = ({
return Boolean(pending);
};
+ // Call before opening a transaction: the KMS round-trip must not hold a pool connection.
+ const encryptKubernetesSecrets = async (
+ orgId: string,
+ config: Pick<TKubernetesAuthMethodConfig, "caCertificate" | "tokenReviewerJwt">
+ ): Promise<TEncryptedKubernetesSecrets> => {
+ if (config.caCertificate === undefined && config.tokenReviewerJwt === undefined) {
+ return {};
+ }
+
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.Organization, orgId });
+
+ const encrypt = (value: string | undefined) => {
+ if (value === undefined) return undefined;
+ if (value === "") return null;
+ return encryptor({ plainText: Buffer.from(value) }).cipherTextBlob;
+ };
+
+ return {
+ ...(config.caCertificate !== undefined && {
+ encryptedKubernetesCaCertificate: encrypt(config.caCertificate)
+ }),
+ ...(config.tokenReviewerJwt !== undefined && {
+ encryptedKubernetesTokenReviewerJwt: encrypt(config.tokenReviewerJwt)
+ })
+ };
+ };
+
const initAtCreate = async (
{
resource,
@@ -304,6 +379,10 @@ export const resourceAuthMethodServiceFactory = ({
resource: ResourceRef;
authMethod:
| { method: typeof ResourceAuthMethodType.Aws; config: TAwsAuthMethodConfig }
+ | {
+ method: typeof ResourceAuthMethodType.Kubernetes;
+ config: TKubernetesAuthMethodConfig & TEncryptedKubernetesSecrets;
+ }
| { method: typeof ResourceAuthMethodType.Token };
},
tx: Knex
@@ -323,6 +402,21 @@ export const resourceAuthMethodServiceFactory = ({
tx
);
}
+ if (authMethod.method === ResourceAuthMethodType.Kubernetes) {
+ await resourceKubernetesAuthDAL.create(
+ {
+ authMethodId: registry.id,
+ kubernetesHost: authMethod.config.kubernetesHost,
+ allowedNamespaces: authMethod.config.allowedNamespaces,
+ allowedNames: authMethod.config.allowedNames,
+ allowedAudience: authMethod.config.allowedAudience,
+ verifyTlsCertificate: authMethod.config.verifyTlsCertificate,
+ encryptedKubernetesCaCertificate: authMethod.config.encryptedKubernetesCaCertificate ?? null,
+ encryptedKubernetesTokenReviewerJwt: authMethod.config.encryptedKubernetesTokenReviewerJwt ?? null
+ },
+ tx
+ );
+ }
};
// tokenVersion is intentionally NOT bumped on method change — running resources keep
@@ -346,6 +440,25 @@ export const resourceAuthMethodServiceFactory = ({
const current = await resourceAuthMethodDAL.findOne(registryFilter);
const previousMethod = current?.method ?? null;
+ let encryptedKubernetesSecrets: TEncryptedKubernetesSecrets = {};
+ if (authMethod.method === ResourceAuthMethodType.Kubernetes) {
+ await assertKubernetesHostAllowed(authMethod.kubernetesHost);
+ // A stored reviewer is left alone; it was already checked when it was set.
+ await validateKubernetesConfigReachable({
+ kubernetesHost: authMethod.kubernetesHost,
+ caCertificate: authMethod.caCertificate,
+ tokenReviewerJwt: authMethod.tokenReviewerJwt,
+ verifyTlsCertificate: authMethod.verifyTlsCertificate
+ });
+
+ // Switching in from another method has no stored secret to preserve, so omitted means null.
+ const isMethodChange = previousMethod !== ResourceAuthMethodType.Kubernetes;
+ encryptedKubernetesSecrets = await encryptKubernetesSecrets(actor.orgId, {
+ caCertificate: authMethod.caCertificate ?? (isMethodChange ? "" : undefined),
+ tokenReviewerJwt: authMethod.tokenReviewerJwt ?? (isMethodChange ? "" : undefined)
+ });
+ }
+
await resourceAuthMethodDAL.transaction(async (tx) => {
// 1. Upsert registry row to the new method.
let registryRow = current;
@@ -363,6 +476,13 @@ export const resourceAuthMethodServiceFactory = ({
) {
await resourceAwsAuthDAL.delete({ authMethodId: current.id }, tx);
}
+ if (
+ previousMethod === ResourceAuthMethodType.Kubernetes &&
+ authMethod.method !== ResourceAuthMethodType.Kubernetes &&
+ current
+ ) {
+ await resourceKubernetesAuthDAL.delete({ authMethodId: current.id }, tx);
+ }
if (
previousMethod === ResourceAuthMethodType.Token &&
authMethod.method !== ResourceAuthMethodType.Token &&
@@ -396,6 +516,36 @@ export const resourceAuthMethodServiceFactory = ({
);
}
}
+
+ if (authMethod.method === ResourceAuthMethodType.Kubernetes) {
+ const sharedFields = {
+ kubernetesHost: authMethod.kubernetesHost,
+ allowedNamespaces: authMethod.allowedNamespaces,
+ allowedNames: authMethod.allowedNames,
+ allowedAudience: authMethod.allowedAudience,
+ verifyTlsCertificate: authMethod.verifyTlsCertificate
+ };
+
+ const existingKubernetes = await resourceKubernetesAuthDAL.findOne({ authMethodId: registryRow.id }, tx);
+ if (existingKubernetes) {
+ await resourceKubernetesAuthDAL.updateById(
+ existingKubernetes.id,
+ { ...sharedFields, ...encryptedKubernetesSecrets },
+ tx
+ );
+ } else {
+ await resourceKubernetesAuthDAL.create(
+ {
+ authMethodId: registryRow.id,
+ ...sharedFields,
+ encryptedKubernetesCaCertificate: encryptedKubernetesSecrets.encryptedKubernetesCaCertificate ?? null,
+ encryptedKubernetesTokenReviewerJwt:
+ encryptedKubernetesSecrets.encryptedKubernetesTokenReviewerJwt ?? null
+ },
+ tx
+ );
+ }
+ }
});
const view = await $loadAuthMethodView(resource);
@@ -462,7 +612,7 @@ export const resourceAuthMethodServiceFactory = ({
}
if (loaded.identityId) {
throw new BadRequestError({
- message: `Identity-bound ${resourceLabel.toLowerCase()}s cannot be revoked directly. Create a new ${resourceLabel.toLowerCase()} with AWS or Token auth instead.`
+ message: `Identity-bound ${resourceLabel.toLowerCase()}s cannot be revoked directly. Create a new ${resourceLabel.toLowerCase()} with AWS, Kubernetes, or Token auth instead.`
});
}
@@ -479,7 +629,7 @@ export const resourceAuthMethodServiceFactory = ({
return {
resourceName: loaded.name,
orgId: loaded.orgId,
- method: registry.method as "aws" | "token"
+ method: registry.method as "aws" | "kubernetes" | "token"
};
};
@@ -546,6 +696,83 @@ export const resourceAuthMethodServiceFactory = ({
};
};
+ const loginWithKubernetes = async ({ resource, jwt }: TLoginWithKubernetesDTO) => {
+ const resourceLabel = RESOURCE_LABEL[resource.type];
+ const loaded = await $loadResource(resource);
+ if (!loaded || !loaded.orgId) {
+ throw new UnauthorizedError({ message: `Invalid ${resourceLabel.toLowerCase()} credentials` });
+ }
+ const resourceName = loaded.name;
+ const resourceOrgId = loaded.orgId;
+
+ const registry = await resourceAuthMethodDAL.findOne($registryFilter(resource));
+ if (!registry || registry.method !== ResourceAuthMethodType.Kubernetes) {
+ throw new UnauthorizedError({
+ message: `${resourceLabel} is not configured for Kubernetes authentication`,
+ detail: { reasonCode: "method_mismatch", resourceId: resource.id, orgId: resourceOrgId }
+ });
+ }
+
+ const config = await resourceKubernetesAuthDAL.findOne({ authMethodId: registry.id });
+ if (!config) {
+ throw new UnauthorizedError({
+ message: `${resourceLabel} is not configured for Kubernetes authentication`,
+ detail: { reasonCode: "config_missing", resourceId: resource.id, orgId: resourceOrgId }
+ });
+ }
+
+ const errorContext = { resourceId: resource.id, orgId: resourceOrgId, resourceName };
+
+ let caCertificate = "";
+ let tokenReviewerJwt = "";
+ if (config.encryptedKubernetesCaCertificate || config.encryptedKubernetesTokenReviewerJwt) {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId: resourceOrgId
+ });
+ if (config.encryptedKubernetesCaCertificate) {
+ caCertificate = decryptor({ cipherTextBlob: config.encryptedKubernetesCaCertificate }).toString();
+ }
+ if (config.encryptedKubernetesTokenReviewerJwt) {
+ tokenReviewerJwt = decryptor({ cipherTextBlob: config.encryptedKubernetesTokenReviewerJwt }).toString();
+ }
+ }
+
+ const { namespace, serviceAccountName, audiences } = await reviewServiceAccountToken({
+ jwt,
+ kubernetesHost: config.kubernetesHost,
+ caCertificate,
+ tokenReviewerJwt,
+ verifyTlsCertificate: config.verifyTlsCertificate,
+ allowedAudience: config.allowedAudience,
+ errorContext
+ });
+
+ validateKubernetesAllowlists({
+ namespace,
+ serviceAccountName,
+ audiences,
+ allowedNamespaces: config.allowedNamespaces,
+ allowedNames: config.allowedNames,
+ allowedAudience: config.allowedAudience,
+ errorContext
+ });
+
+ const refreshedTokenVersion = await $bumpTokenVersion(resource);
+
+ const accessToken = $mintJwt(resource, resourceOrgId, refreshedTokenVersion);
+
+ return {
+ accessToken,
+ resourceId: resource.id,
+ resourceName,
+ orgId: resourceOrgId,
+ configId: config.id,
+ namespace,
+ serviceAccountName
+ };
+ };
+
// Single-use: row is deleted on consume, not flagged.
const loginWithToken = async ({ token, expectedResourceType }: TLoginWithTokenDTO) => {
const tokenHash = crypto.nativeCrypto.createHash("sha256").update(token).digest("hex");
@@ -618,11 +845,15 @@ export const resourceAuthMethodServiceFactory = ({
getByKmipServerId,
loadView,
canRevoke,
+ assertKubernetesHostAllowed,
+ validateKubernetesConfigReachable,
+ encryptKubernetesSecrets,
initAtCreate,
setMethod,
mintToken,
revokeAccess,
loginWithAws,
+ loginWithKubernetes,
loginWithToken
};
};
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts
index b9636ec766..6b3d5feedf 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-types.ts
@@ -8,8 +8,38 @@ export type TAwsAuthMethodConfig = {
allowedAccountIds: string;
};
+export type TKubernetesAuthMethodConfig = {
+ kubernetesHost: string;
+ allowedNamespaces: string;
+ allowedNames: string;
+ allowedAudience: string;
+ verifyTlsCertificate: boolean;
+ caCertificate?: string;
+ tokenReviewerJwt?: string;
+};
+
+// A missing key means "keep the stored value"; null means "clear it".
+export type TEncryptedKubernetesSecrets = {
+ encryptedKubernetesCaCertificate?: Buffer | null;
+ encryptedKubernetesTokenReviewerJwt?: Buffer | null;
+};
+
+// The CA certificate round-trips because it is public key material. The reviewer JWT is a live
+// cluster credential, so only its presence is reported.
+export type TKubernetesAuthMethodConfigView = Omit<
+ TKubernetesAuthMethodConfig,
+ "caCertificate" | "tokenReviewerJwt"
+> & {
+ id: string;
+ caCertificate: string;
+ hasTokenReviewerJwt: boolean;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
export type TSetAuthMethodInput =
| ({ method: typeof ResourceAuthMethodType.Aws } & TAwsAuthMethodConfig)
+ | ({ method: typeof ResourceAuthMethodType.Kubernetes } & TKubernetesAuthMethodConfig)
| { method: typeof ResourceAuthMethodType.Token };
export type TSetAuthMethodDTO = {
@@ -33,6 +63,11 @@ export type TLoginWithAwsDTO = {
iamRequestHeaders: string;
};
+export type TLoginWithKubernetesDTO = {
+ resource: ResourceRef;
+ jwt: string;
+};
+
export type TLoginWithTokenDTO = {
token: string;
expectedResourceType: "gateway" | "relay" | "kmip";
@@ -43,6 +78,10 @@ export type TAuthMethodView =
method: typeof ResourceAuthMethodType.Aws;
config: TAwsAuthMethodConfig & { id: string; createdAt: Date; updatedAt: Date };
}
+ | {
+ method: typeof ResourceAuthMethodType.Kubernetes;
+ config: TKubernetesAuthMethodConfigView;
+ }
| {
method: typeof ResourceAuthMethodType.Token;
config: Record<string, never>;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 33907cde81..b91b2dcdbd 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3792,24 +3792,39 @@ export const GATEWAYS = {
CREATE: {
name: "Name of the gateway.",
authMethod:
- "Auth method to configure on the gateway. `aws` carries the AWS allowlists; `token` is configurationless and requires a separate POST /v3/gateways/:id/token call to mint the bootstrap token."
+ "Auth method to configure on the gateway. `aws` carries the AWS allowlists; `kubernetes` carries the cluster host and namespace/service account allowlists; `token` is configurationless and requires a separate POST /v3/gateways/:id/token call to mint the bootstrap token."
},
UPDATE: {
authMethod:
- "Replacement auth method. Same shape as in create — `aws` with allowlists or `token` with no config. Existing gateways keep working until they restart and re-authenticate via the new method."
+ "Replacement auth method. Same shape as in create: `aws` with allowlists, `kubernetes` with cluster config, or `token` with no config. Existing gateways keep working until they restart and re-authenticate via the new method."
},
AUTH_METHOD: {
stsEndpoint: "The endpoint URL for the AWS STS API.",
allowedPrincipalArns:
"The comma-separated list of trusted IAM principal ARNs that are allowed to authenticate with Infisical.",
allowedAccountIds:
- "The comma-separated list of trusted AWS account IDs that are allowed to authenticate with Infisical."
+ "The comma-separated list of trusted AWS account IDs that are allowed to authenticate with Infisical.",
+ kubernetesHost:
+ "The URL of the Kubernetes API server that Infisical reviews the gateway's service account token against (e.g. https://my-cluster.example.com:6443).",
+ caCertificate:
+ "The PEM-encoded CA certificate of the Kubernetes API server. Required to verify the API server's TLS certificate. Write-only: never returned by the API.",
+ tokenReviewerJwt:
+ "A long-lived service account token with the system:auth-delegator ClusterRole used to submit TokenReview requests. Omit to have the gateway's own token act as the reviewer. Write-only: never returned by the API.",
+ allowedNamespaces:
+ "The comma-separated list of Kubernetes namespaces whose service accounts are allowed to authenticate as this gateway. Supports `*` wildcards.",
+ allowedNames:
+ "The comma-separated list of Kubernetes service account names that are allowed to authenticate as this gateway. Supports `*` wildcards.",
+ allowedAudience:
+ "The audience the gateway's service account token must carry. Leave empty to skip the audience check.",
+ verifyTlsCertificate:
+ "Whether to verify the Kubernetes API server's TLS certificate. Only takes effect when a CA certificate is configured."
},
LOGIN: {
- gatewayId: "The ID of the gateway logging in (AWS method only).",
+ gatewayId: "The ID of the gateway logging in (AWS and Kubernetes methods only).",
iamHttpRequestMethod: "The HTTP request method used in the signed STS request.",
iamRequestBody: "The base64-encoded body of the signed STS request.",
iamRequestHeaders: "The base64-encoded headers of the sts:GetCallerIdentity signed request.",
+ jwt: "The projected Kubernetes service account token of the pod the gateway runs in (Kubernetes method only).",
token: "The one-time enrollment token previously issued for this gateway (token method only)."
}
} as const;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 228b8feae3..3ef4b47a99 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -156,6 +156,7 @@ import { orgRelayConfigDalFactory } from "@app/ee/services/relay/org-relay-confi
import { relayDalFactory } from "@app/ee/services/relay/relay-dal";
import { relayServiceFactory } from "@app/ee/services/relay/relay-service";
import { resourceAwsAuthDALFactory } from "@app/ee/services/resource-auth-method/aws-auth-dal";
+import { resourceKubernetesAuthDALFactory } from "@app/ee/services/resource-auth-method/kubernetes-auth-dal";
import { resourceAuthMethodDALFactory } from "@app/ee/services/resource-auth-method/resource-auth-method-dal";
import { resourceAuthMethodServiceFactory } from "@app/ee/services/resource-auth-method/resource-auth-method-service";
import { resourceTokenAuthDALFactory } from "@app/ee/services/resource-auth-method/token-auth-dal";
@@ -1628,6 +1629,7 @@ export const registerRoutes = async (
const resourceTokenAuthDAL = resourceTokenAuthDALFactory(db);
const resourceAuthMethodDAL = resourceAuthMethodDALFactory(db);
const resourceAwsAuthDAL = resourceAwsAuthDALFactory(db);
+ const resourceKubernetesAuthDAL = resourceKubernetesAuthDALFactory(db);
const gatewayPoolDAL = gatewayPoolDalFactory(db);
const gatewayPoolMembershipDAL = gatewayPoolMembershipDalFactory(db);
@@ -1787,7 +1789,9 @@ export const registerRoutes = async (
const resourceAuthMethodService = resourceAuthMethodServiceFactory({
resourceAuthMethodDAL,
resourceAwsAuthDAL,
+ resourceKubernetesAuthDAL,
resourceTokenAuthDAL,
+ kmsService,
gatewayV2DAL,
relayDAL,
kmipServerDAL,
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index dddbb66e0e..2a7179d4f0 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -1175,7 +1175,7 @@ export type TResourceAuthMethodEvent = {
resourceType: "gateway";
resourceId: string;
orgId: string;
- method: "aws" | "token";
+ method: "aws" | "kubernetes" | "token";
};
};
diff --git a/docs/cli/commands/gateway.mdx b/docs/cli/commands/gateway.mdx
index a063706a2f..32eecfcd3e 100644
--- a/docs/cli/commands/gateway.mdx
+++ b/docs/cli/commands/gateway.mdx
@@ -50,27 +50,73 @@ Once started, the gateway component will:
<AccordionGroup>
<Accordion title="--enroll-method">
- The enrollment method to use. Currently only `token` is supported. Additional authentication methods will be available in the future.
-
- <ParamField query="Flags">
- <Expandable title="properties">
- <ParamField query="enroll-method" type="string" required>
- Must be `token` when using an enrollment token.
- </ParamField>
- <ParamField query="token" type="string" required>
- The one-time enrollment token from the Infisical UI.
- </ParamField>
- <ParamField query="domain" type="string" required>
- The URL of your Infisical instance.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- infisical gateway start my-gateway --enroll-method=token --token=<enrollment-token> --domain=https://app.infisical.com
- ```
-
- After enrollment, the gateway saves its credentials locally. You can safely re-run the same command to restart the gateway. It will detect the token has already been used and skip enrollment automatically.
+ How the gateway authenticates with Infisical. Must match the auth method configured on the gateway in the Infisical UI. One of `token`, `aws`, or `kubernetes`.
+
+ <Tabs>
+ <Tab title="token">
+ A one-time enrollment token from the Infisical UI bootstraps the gateway.
+
+ <ParamField query="Flags">
+ <Expandable title="properties">
+ <ParamField query="token" type="string" required>
+ The one-time enrollment token from the Infisical UI.
+ </ParamField>
+ <ParamField query="domain" type="string" required>
+ The URL of your Infisical instance.
+ </ParamField>
+ </Expandable>
+ </ParamField>
+
+ ```bash
+ infisical gateway start my-gateway --enroll-method=token --token=<enrollment-token> --domain=https://app.infisical.com
+ ```
+
+ After enrollment, the gateway saves its credentials locally. You can safely re-run the same command to restart the gateway. It will detect the token has already been used and skip enrollment automatically.
+ </Tab>
+ <Tab title="aws">
+ The gateway signs an `sts:GetCallerIdentity` request with whatever AWS credentials it can resolve on the host (instance role, environment variables, shared profile), and re-authenticates on every start. No token is stored on disk.
+
+ <ParamField query="Flags">
+ <Expandable title="properties">
+ <ParamField query="gateway-id" type="string" required>
+ The gateway ID from the Infisical UI.
+ </ParamField>
+ <ParamField query="domain" type="string" required>
+ The URL of your Infisical instance.
+ </ParamField>
+ </Expandable>
+ </ParamField>
+
+ ```bash
+ infisical gateway start my-gateway --enroll-method=aws --gateway-id=<gateway-id> --domain=https://app.infisical.com
+ ```
+ </Tab>
+ <Tab title="kubernetes">
+ The gateway authenticates with the projected service account token of the pod it runs in, so no credential has to be distributed to the cluster. Infisical verifies the token against your cluster's TokenReview API and re-authenticates on every start. No token is stored on disk.
+
+ This method requires the gateway to run inside a Kubernetes pod. Deploying with the [Helm chart](/self-hosting/helm-charts/gateway) is the recommended path.
+
+ <ParamField query="Flags">
+ <Expandable title="properties">
+ <ParamField query="gateway-id" type="string" required>
+ The gateway ID from the Infisical UI.
+ </ParamField>
+ <ParamField query="domain" type="string" required>
+ The URL of your Infisical instance.
+ </ParamField>
+ <ParamField query="service-account-token-path" type="string">
+ Path to the projected service account token. Defaults to `/var/run/secrets/kubernetes.io/serviceaccount/token`.
+ </ParamField>
+ </Expandable>
+ </ParamField>
+
+ ```bash
+ infisical gateway start my-gateway --enroll-method=kubernetes --gateway-id=<gateway-id> --domain=https://app.infisical.com
+ ```
+
+ See [Gateway Deployment](/documentation/platform/gateways/gateway-deployment) for the cluster host and allowlist configuration this method needs.
+ </Tab>
+ </Tabs>
</Accordion>
@@ -128,13 +174,18 @@ sudo infisical gateway systemd install my-gateway --enroll-method=token --token=
<AccordionGroup>
<Accordion title="--enroll-method">
- The enrollment method to use. Currently only `token` is supported.
+ How the gateway authenticates with Infisical. One of `token` or `aws`.
```bash
- # Example
+ # Enrollment token
sudo infisical gateway systemd install my-gateway --enroll-method=token --token=<enrollment-token> --domain=<domain>
+
+ # AWS auth, re-authenticated on every service start
+ sudo infisical gateway systemd install my-gateway --enroll-method=aws --gateway-id=<gateway-id> --domain=<domain>
```
+ `kubernetes` is not available here. In-cluster gateways are not managed by systemd, so run `infisical gateway start --enroll-method=kubernetes` as the container command instead.
+
</Accordion>
<Accordion title="--token">
diff --git a/docs/documentation/platform/gateways/gateway-deployment.mdx b/docs/documentation/platform/gateways/gateway-deployment.mdx
index 6377ccb6db..a73474551f 100644
--- a/docs/documentation/platform/gateways/gateway-deployment.mdx
+++ b/docs/documentation/platform/gateways/gateway-deployment.mdx
@@ -24,9 +24,10 @@ This guide covers everything you need to deploy and configure Infisical Gateways
![Create Gateway button](/images/platform/gateways/gateway-create-button.png)
3. Enter a name for the gateway.
![Create Gateway form](/images/platform/gateways/gateway-create-form.png)
- 4. (Optional) Open the new gateway's detail page and click the edit icon next to **Authentication** to switch the auth method. Two methods are supported:
+ 4. (Optional) Open the new gateway's detail page and change the method under **Authentication** in the **Details** card. Three methods are supported:
- **Token** (default): a one-time enrollment token (1h expiry) bootstraps the gateway.
- **AWS**: the gateway authenticates by signing an `sts:GetCallerIdentity` request with whatever AWS credentials it can resolve on the host (instance role, env vars, shared profile). Configure the allowed principal ARNs and/or account IDs that match your hosts.
+ - **Kubernetes**: the gateway authenticates with the projected service account token of the pod it runs in, so no credential has to be distributed to the cluster. Configure the cluster's API server URL and the allowed namespaces and/or service account names.
5. Click **Show deploy command** in the **Deployment** card. Pick a relay (or "Auto Select Relay") and copy the generated CLI command.
</Step>
<Step title="Install the Infisical CLI">
@@ -154,6 +155,63 @@ This guide covers everything you need to deploy and configure Infisical Gateways
</Tab>
</Tabs>
</Accordion>
+ <Accordion title="Kubernetes Auth">
+ The gateway sends the projected service account token of its own pod, and Infisical verifies it against your cluster's TokenReview API. Nothing has to be copied into the cluster, so this is the method to use when gateway creation is automated. The gateway re-authenticates on every start.
+
+ Before deploying, configure the Kubernetes auth method on the gateway's detail page:
+
+ | Field | Description |
+ | --- | --- |
+ | **Kubernetes Host** | The cluster API server URL, reachable from Infisical (for example `https://my-cluster.example.com:6443`). |
+ | **Allowed Namespaces** | Namespaces whose service accounts may authenticate as this gateway. Supports `*` wildcards. |
+ | **Allowed Service Account Names** | Service account names that may authenticate as this gateway. Supports `*` wildcards. |
+ | **Allowed Audience** | Optional. The audience the token must carry. |
+ | **CA Certificate** | Optional, but required to verify the API server's TLS certificate. |
+ | **Token Reviewer JWT** | Optional. A token with the `system:auth-delegator` ClusterRole. Leave empty to let the gateway's own service account review its token, which the Helm chart configures by default. |
+
+ At least one of **Allowed Namespaces** or **Allowed Service Account Names** must be set, so that not every pod in the cluster can enroll as the gateway.
+
+ <Tabs>
+ <Tab title="Kubernetes (Helm)">
+ Install the Infisical Helm chart repository:
+ ```bash
+ helm repo add infisical https://dl.cloudsmith.io/public/infisical/helm-charts/helm/charts/
+ helm repo update
+ ```
+
+ Install the gateway:
+ ```bash
+ helm install infisical-gateway infisical/infisical-gateway \
+ --namespace infisical-gateway --create-namespace \
+ --set gateway.name=<gateway-name> \
+ --set gateway.enrollment.method=kubernetes \
+ --set gateway.enrollment.kubernetes.gatewayId=<gateway-id> \
+ --set gateway.domain=<your-infisical-domain>
+ ```
+
+ <Info>
+ The chart binds the gateway's service account to the `system:auth-delegator` ClusterRole by default, which is what lets its own token act as the token reviewer. Set `serviceAccount.createAsAuthDelegator=false` only if you configure a separate **Token Reviewer JWT** on the gateway instead.
+ </Info>
+
+ Make sure the release namespace and service account name match the allowlists you configured. With the command above, that is namespace `infisical-gateway` and service account `infisical-gateway`.
+ </Tab>
+ <Tab title="Other in-cluster deployment">
+ If you deploy the gateway container yourself rather than through the chart, run it with:
+ ```bash
+ infisical gateway start <gateway-name> \
+ --enroll-method=kubernetes \
+ --gateway-id=<gateway-id> \
+ --domain=<your-infisical-domain>
+ ```
+
+ The pod needs its service account token automounted (the default), and either the service account must hold the `system:auth-delegator` ClusterRole or a separate **Token Reviewer JWT** must be configured on the gateway.
+ </Tab>
+ </Tabs>
+
+ <Warning>
+ Infisical must be able to reach the cluster's API server to review the token. For a cluster with no publicly reachable API server, use Token or AWS auth instead.
+ </Warning>
+ </Accordion>
</AccordionGroup>
<Warning>
@@ -180,8 +238,8 @@ This guide covers everything you need to deploy and configure Infisical Gateways
From the gateway's detail page (click the gateway row in the list):
-- **Show deploy command** — Generates a fresh enrollment token (token method) or re-displays the AWS start command. Clicking this on a token-method gateway does **not** disconnect the running gateway; the next login with the new token rotates credentials atomically.
-- **Edit auth method** — Switch between Token and AWS, or update the AWS allowlists. Existing gateways keep their JWT until they restart and re-authenticate.
+- **Show deploy command**: Generates a fresh enrollment token (token method) or re-displays the start command for the AWS and Kubernetes methods. Clicking this on a token-method gateway does **not** disconnect the running gateway; the next login with the new token rotates credentials atomically.
+- **Edit auth method**: Switch between Token, AWS, and Kubernetes, or update the allowlists of the current method. Existing gateways keep their JWT until they restart and re-authenticate.
- **Options → Revoke Access** — Disconnects the running gateway and invalidates outstanding enrollment tokens. The gateway must re-authenticate to reconnect. Gated by the dedicated `revoke-gateway-access` permission, separate from `edit-gateways`.
- **Options → Delete Gateway** — Permanently removes the gateway.
@@ -230,6 +288,8 @@ If the gateway cannot connect to the relay:
For token method: ensure the enrollment token has not expired or already been used. Open the gateway's detail page and click **Show deploy command** to generate a fresh token.
For AWS method: ensure the host has AWS credentials available (instance role, env vars, or shared profile) and the resolved principal/account is in the allowlist on the gateway's detail page.
+
+For Kubernetes method: ensure Infisical can reach the configured Kubernetes host, that the pod's namespace and service account are in the allowlists, and that the reviewer (the gateway's own service account by default) holds the `system:auth-delegator` ClusterRole. The gateway's audit log records the reviewed namespace and service account name for each login, and the reason code for each failure.
</Accordion>
<Accordion title="Where can I find gateway logs?">
@@ -252,7 +312,7 @@ For **token-method** gateways, the access token and domain are saved to a config
- **Running as root/sudo:** `/etc/infisical/gateways/<gateway-name>.conf`
- **Running as a regular user:** `~/.infisical/gateways/<gateway-name>.conf`
-For **AWS-method** gateways, no JWT is persisted to disk. The gateway re-authenticates by signing a fresh STS request on every start using the host's AWS credentials. Only the gateway id and domain are stored locally.
+For **AWS-method** and **Kubernetes-method** gateways, no JWT is persisted to disk. The gateway re-authenticates on every start, by signing a fresh STS request with the host's AWS credentials or by presenting the pod's service account token. Only the gateway id and domain are stored locally.
For systemd-based installations, the configuration is at `/etc/infisical/gateways/<gateway-name>.conf`. All config files are created with restricted permissions (0600).
</Accordion>
diff --git a/docs/self-hosting/helm-charts/gateway.mdx b/docs/self-hosting/helm-charts/gateway.mdx
index 3c7786b6e4..102ecf2fe2 100644
--- a/docs/self-hosting/helm-charts/gateway.mdx
+++ b/docs/self-hosting/helm-charts/gateway.mdx
@@ -48,6 +48,29 @@ For a full overview of how gateways work, see the [Gateway documentation](/docum
--set serviceAccount.annotations."eks\.amazonaws\.com/role-arn"=arn:aws:iam::<account-id>:role/<role-name>
```
</Tab>
+
+ <Tab title="Kubernetes Auth">
+ ```bash
+ helm install infisical-gateway infisical-helm-charts/infisical-gateway \
+ --namespace infisical-gateway \
+ --create-namespace \
+ --set gateway.name=<gateway-name> \
+ --set gateway.enrollment.method=kubernetes \
+ --set gateway.enrollment.kubernetes.gatewayId=<gateway-id> \
+ --set gateway.domain=https://app.infisical.com
+ ```
+
+ The gateway authenticates with the projected service account token of its own pod, so no
+ credential has to be distributed to the cluster. The chart binds its service account to the
+ `system:auth-delegator` ClusterRole by default, which is what lets that token be reviewed.
+
+ <Warning>
+ The release namespace and service account name must match the allowlists configured on the
+ gateway in Infisical. With the command above those are `infisical-gateway` and
+ `infisical-gateway`. See [Gateway Deployment](/documentation/platform/gateways/gateway-deployment)
+ for the full configuration.
+ </Warning>
+ </Tab>
</Tabs>
</Step>
@@ -70,14 +93,16 @@ helm uninstall infisical-gateway --namespace infisical-gateway
|-----------|---------|-------------|
| `gateway.name` | `""` | Name of the gateway as created in the Infisical UI. |
| `gateway.domain` | `""` | Infisical instance URL (e.g., `https://app.infisical.com`). |
-| `gateway.enrollment.method` | `""` | Enrollment method: `token` or `aws`. |
+| `gateway.enrollment.method` | `""` | Enrollment method: `token`, `aws`, or `kubernetes`. |
| `gateway.enrollment.token.value` | `""` | Inline enrollment token. Mutually exclusive with `existingSecretRef`. |
| `gateway.enrollment.token.existingSecretRef` | `""` | Kubernetes secret containing the enrollment token. |
| `gateway.enrollment.token.secretKey` | `"enrollment-token"` | Key in the secret that holds the token. |
| `gateway.enrollment.aws.gatewayId` | `""` | Gateway ID from the Infisical UI. Required for AWS auth. |
+| `gateway.enrollment.kubernetes.gatewayId` | `""` | Gateway ID from the Infisical UI. Required for Kubernetes auth. |
+| `gateway.enrollment.kubernetes.serviceAccountTokenPath` | `""` | Override the projected service account token path. Defaults to `/var/run/secrets/kubernetes.io/serviceaccount/token`. |
| `gateway.enrollment.credentialsSecretRef` | `""` | Kubernetes secret with credentials injected as env vars. |
| `gateway.relayName` | `""` | Specific relay to connect to. Empty for automatic selection. |
-| `persistence.enabled` | `true` | Enable persistent storage. Required for token auth. |
+| `persistence.enabled` | `true` | Enable persistent storage. Required for token auth, optional for AWS and Kubernetes auth. |
| `persistence.storageClass` | `""` | Storage class for the PVC. |
| `persistence.size` | `5Gi` | PVC size. |
| `persistence.existingClaim` | `""` | Use an existing PVC. |
@@ -117,7 +142,7 @@ gateway:
domain: ""
enrollment:
- # Enrollment method: "token" or "aws".
+ # Enrollment method: "token", "aws", or "kubernetes".
# Leave empty to use the legacy machine identity flow (env vars from secret.name).
method: ""
@@ -135,6 +160,16 @@ gateway:
# Required when method=aws. Gateway ID from the Infisical UI.
gatewayId: ""
+ # Kubernetes enrollment settings (method=kubernetes).
+ # The gateway authenticates with the projected service account token of its own pod, so no
+ # credential needs to be distributed. Requires serviceAccount.createAsAuthDelegator (default)
+ # unless a separate token reviewer is configured on the gateway in Infisical.
+ kubernetes:
+ # Required when method=kubernetes. Gateway ID from the Infisical UI.
+ gatewayId: ""
+ # Path to the projected service account token. Only override for a non-default mount.
+ serviceAccountTokenPath: ""
+
# Name of a K8s Secret whose key-value pairs are injected as env vars.
# Use this to provide credentials for the enrollment method (e.g. AWS keys, GCP credentials).
# Not needed when credentials are provided via workload identity (IRSA, GCP Workload Identity, etc.).
@@ -147,7 +182,8 @@ gateway:
# Persistent storage for the gateway (credentials and session recordings).
# Required when enrollment.method=token so credentials survive pod restarts.
-# Optional when enrollment.method=aws since it re-authenticates via STS on every start.
+# Optional when enrollment.method=aws or enrollment.method=kubernetes, since both re-authenticate
+# on every start.
# For legacy machine-identity installs (no enrollment.method), persistence only takes effect
# when existingClaim is provided.
persistence:
diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.ts
index 0be7b0ba06..460b8c0dd4 100644
--- a/frontend/src/hooks/api/gateways-v2/types.ts
+++ b/frontend/src/hooks/api/gateways-v2/types.ts
@@ -24,6 +24,19 @@ export type GatewayAwsAuthConfig = {
updatedAt: string;
};
+export type GatewayKubernetesAuthConfig = {
+ id: string;
+ kubernetesHost: string;
+ allowedNamespaces: string;
+ allowedNames: string;
+ allowedAudience: string;
+ verifyTlsCertificate: boolean;
+ caCertificate: string;
+ hasTokenReviewerJwt: boolean;
+ createdAt: string;
+ updatedAt: string;
+};
+
export type GatewayTokenAuthConfig = Record<string, never>;
export type GatewayIdentityAuthConfig = {
@@ -33,6 +46,7 @@ export type GatewayIdentityAuthConfig = {
export type GatewayAuthMethodView =
| { method: "aws"; config: GatewayAwsAuthConfig }
+ | { method: "kubernetes"; config: GatewayKubernetesAuthConfig }
| { method: "token"; config: GatewayTokenAuthConfig }
| { method: "identity"; config: GatewayIdentityAuthConfig };
@@ -47,6 +61,17 @@ export type SettableAuthMethodInput =
allowedPrincipalArns: string;
allowedAccountIds: string;
}
+ | {
+ method: "kubernetes";
+ kubernetesHost: string;
+ caCertificate?: string;
+ // Write-only. Omitted means "keep the stored value"; an empty string clears it.
+ tokenReviewerJwt?: string;
+ allowedNamespaces: string;
+ allowedNames: string;
+ allowedAudience?: string;
+ verifyTlsCertificate?: boolean;
+ }
| { method: "token" };
export type TGatewayEnrollmentToken = {
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
new file mode 100644
index 0000000000..8629534eec
--- /dev/null
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/KubernetesStartCommandDialog.tsx
@@ -0,0 +1,92 @@
+import { useMemo, useState } from "react";
+
+import {
+ CodeBlock,
+ Field,
+ FieldDescription,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ TabsContent
+} from "@app/components/v3";
+import { useGetRelays } from "@app/hooks/api/relays/queries";
+
+type Props = {
+ gatewayId: string;
+ gatewayName: string;
+};
+
+const AUTO_RELAY_OPTION = { id: "_auto", name: "Auto Select Relay" };
+
+export const KubernetesStartCommandContent = ({ gatewayId, gatewayName }: Props) => {
+ const { protocol, hostname, port } = window.location;
+ const portSuffix = port && port !== "80" ? `:${port}` : "";
+ const siteURL = `${protocol}//${hostname}${portSuffix}`;
+
+ const { data: relays, isPending: isRelaysLoading } = useGetRelays();
+ const [relay, setRelay] = useState<{ id: string; name: string }>(AUTO_RELAY_OPTION);
+
+ const resolvedRelayName = relay.id === "_auto" ? "" : relay.name;
+
+ const helmCommand = useMemo(() => {
+ const relayPart = resolvedRelayName
+ ? ` \\\n --set gateway.relayName=${resolvedRelayName}`
+ : "";
+ return `helm repo add infisical-helm-charts https://dl.infisical.com/helm-charts
+helm install infisical-gateway infisical-helm-charts/infisical-gateway \\
+ --namespace infisical-gateway --create-namespace \\
+ --set gateway.name=${gatewayName} \\
+ --set gateway.domain=${siteURL} \\
+ --set gateway.enrollment.method=kubernetes \\
+ --set gateway.enrollment.kubernetes.gatewayId=${gatewayId}${relayPart}`;
+ }, [gatewayName, gatewayId, resolvedRelayName, siteURL]);
+
+ const cliCommand = useMemo(() => {
+ const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";
+ return `infisical gateway start ${gatewayName} --enroll-method=kubernetes --gateway-id=${gatewayId}${relayPart} --domain=${siteURL}`;
+ }, [gatewayName, gatewayId, resolvedRelayName, siteURL]);
+
+ return (
+ <div className="min-w-0 space-y-4">
+ <TabsContent value="helm" className="mt-0 min-w-0">
+ <CodeBlock value={helmCommand} label="Install chart" />
+ </TabsContent>
+ <TabsContent value="cli" className="mt-0 min-w-0">
+ <CodeBlock value={cliCommand} label="Container command" />
+ </TabsContent>
+ <Field>
+ <Select
+ value={relay.id}
+ onValueChange={(id) =>
+ setRelay(
+ [AUTO_RELAY_OPTION, ...(relays || [])].find((item) => item.id === id) ||
+ AUTO_RELAY_OPTION
+ )
+ }
+ disabled={isRelaysLoading}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select relay" />
+ </SelectTrigger>
+ <SelectContent>
+ {[AUTO_RELAY_OPTION, ...(relays || [])].map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {relay.id !== "_auto" && (
+ <FieldDescription>
+ * Auto Select chooses a healthy relay and fails over if needed.
+ </FieldDescription>
+ )}
+ </Field>
+ <p className="text-xs text-muted">
+ The gateway must run in a namespace and service account matching the configured allowlists.
+ </p>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayAuth.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayAuth.tsx
deleted file mode 100644
index 13291be879..0000000000
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayAuth.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { GatewayAuthMethodView } from "@app/hooks/api/gateways-v2/types";
-
-import { ViewGatewayAwsAuthContent } from "./ViewGatewayAwsAuthContent";
-import { ViewGatewayIdentityAuthContent } from "./ViewGatewayIdentityAuthContent";
-
-type Props = {
- authMethod: GatewayAuthMethodView;
-};
-
-export const ViewGatewayAuth = ({ authMethod }: Props) => {
- if (authMethod.method === "aws") {
- return <ViewGatewayAwsAuthContent config={authMethod.config} />;
- }
- if (authMethod.method === "token") {
- return null;
- }
- return <ViewGatewayIdentityAuthContent config={authMethod.config} />;
-};
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayAwsAuthContent.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayAwsAuthContent.tsx
deleted file mode 100644
index 084da4bd51..0000000000
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayAwsAuthContent.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { Detail, DetailLabel, DetailValue } from "@app/components/v3";
-import { GatewayAwsAuthConfig } from "@app/hooks/api/gateways-v2/types";
-
-const Field = ({
- label,
- children,
- className
-}: {
- label: string;
- children: React.ReactNode;
- className?: string;
-}) => (
- <Detail className={className}>
- <DetailLabel>{label}</DetailLabel>
- <DetailValue>
- {children ? <p className="break-words">{children}</p> : <p className="text-muted">—</p>}
- </DetailValue>
- </Detail>
-);
-
-type Props = {
- config: GatewayAwsAuthConfig;
-};
-
-export const ViewGatewayAwsAuthContent = ({ config }: Props) => {
- return (
- <div className="grid grid-cols-1 gap-x-4 gap-y-2 md:grid-cols-2">
- <Field label="Allowed Principal ARNs" className="md:col-span-2">
- {config.allowedPrincipalArns
- ?.split(",")
- .map((a) => a.trim())
- .join(", ")}
- </Field>
- <Field label="Allowed Account IDs" className="md:col-span-2">
- {config.allowedAccountIds
- ?.split(",")
- .map((id) => id.trim())
- .join(", ")}
- </Field>
- <Field label="STS Endpoint" className="md:col-span-2">
- {config.stsEndpoint}
- </Field>
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayIdentityAuthContent.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayIdentityAuthContent.tsx
deleted file mode 100644
index 646ce1b37e..0000000000
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayAuthMethod/ViewGatewayIdentityAuthContent.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Link } from "@tanstack/react-router";
-import { ExternalLinkIcon } from "lucide-react";
-
-import { Detail, DetailLabel, DetailValue } from "@app/components/v3";
-import { useOrganization } from "@app/context";
-import { GatewayIdentityAuthConfig } from "@app/hooks/api/gateways-v2/types";
-
-type Props = {
- config: GatewayIdentityAuthConfig;
-};
-
-export const ViewGatewayIdentityAuthContent = ({ config }: Props) => {
- const { currentOrg } = useOrganization();
-
- return (
- <Detail>
- <DetailLabel>Machine Identity</DetailLabel>
- <DetailValue>
- {config.identityName ? (
- <Link
- to="/organizations/$orgId/identities/$identityId"
- params={{ orgId: currentOrg.id, identityId: config.identityId }}
- className="inline-flex items-center gap-1 underline"
- >
- {config.identityName}
- <ExternalLinkIcon className="size-3.5 text-mineshaft-400" />
- </Link>
- ) : (
- <span className="text-muted">Identity has been deleted</span>
- )}
- </DetailValue>
- </Detail>
- );
-};
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
index c392db6cf3..23e1443660 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDeploySection/GatewayDeploySection.tsx
@@ -28,6 +28,7 @@ import { GatewayAuthMethodView, TGatewayEnrollmentToken } from "@app/hooks/api/g
import { AwsStartCommandContent } from "../GatewayAuthMethod/AwsStartCommandDialog";
import { EnrollmentTokenContent } from "../GatewayAuthMethod/EnrollmentTokenDialog";
+import { KubernetesStartCommandContent } from "../GatewayAuthMethod/KubernetesStartCommandDialog";
type Props = {
gatewayId: string;
@@ -36,7 +37,8 @@ type Props = {
};
export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Props) => {
- const [deploymentMethod, setDeploymentMethod] = useState("cli");
+ const isKubernetes = authMethod.method === "kubernetes";
+ const [deploymentMethod, setDeploymentMethod] = useState("");
const [mintedEnrollment, setMintedEnrollment] = useState<
(TGatewayEnrollmentToken & { gatewayId: string }) | null
>(null);
@@ -51,7 +53,13 @@ export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Pro
if (authMethod.method === "identity") return null;
- const showDeploymentControls = authMethod.method === "aws" || Boolean(enrollment);
+ const showDeploymentControls = authMethod.method === "aws" || isKubernetes || Boolean(enrollment);
+
+ // Derived, so switching auth method can't leave a tab selected that the new method lacks.
+ const deploymentTabs = isKubernetes ? ["helm", "cli"] : ["cli", "systemd"];
+ const activeTab = deploymentTabs.includes(deploymentMethod)
+ ? deploymentMethod
+ : deploymentTabs[0];
const handleGenerate = async () => {
try {
@@ -63,19 +71,32 @@ export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Pro
};
return (
- <Tabs value={deploymentMethod} onValueChange={setDeploymentMethod} className="min-w-0">
+ <Tabs value={activeTab} onValueChange={setDeploymentMethod} className="min-w-0">
<Card className="min-w-0" aria-labelledby="gateway-deployment-title">
<CardHeader>
<CardTitle>
<h2 id="gateway-deployment-title">Deployment</h2>
<DocumentationLinkBadge href="https://infisical.com/docs/cli/overview" />
</CardTitle>
- <CardDescription>Run this gateway on a target host.</CardDescription>
+ <CardDescription>
+ {isKubernetes
+ ? "Run this gateway in your Kubernetes cluster."
+ : "Run this gateway on a target host."}
+ </CardDescription>
{canEditGateway && showDeploymentControls && (
<CardAction>
<TabsList variant="filled">
- <TabsTrigger value="cli">CLI</TabsTrigger>
- <TabsTrigger value="systemd">System service</TabsTrigger>
+ {isKubernetes ? (
+ <>
+ <TabsTrigger value="helm">Helm</TabsTrigger>
+ <TabsTrigger value="cli">Container command</TabsTrigger>
+ </>
+ ) : (
+ <>
+ <TabsTrigger value="cli">CLI</TabsTrigger>
+ <TabsTrigger value="systemd">System service</TabsTrigger>
+ </>
+ )}
</TabsList>
</CardAction>
)}
@@ -95,6 +116,10 @@ export const GatewayDeploySection = ({ gatewayId, gatewayName, authMethod }: Pro
<AwsStartCommandContent gatewayId={gatewayId} gatewayName={gatewayName} />
)}
+ {isKubernetes && (
+ <KubernetesStartCommandContent gatewayId={gatewayId} gatewayName={gatewayName} />
+ )}
+
{authMethod.method === "token" && !enrollment && (
<Button
variant="neutral"
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
index 26e6e00ff6..cc06d8ad29 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
@@ -34,7 +34,10 @@ import { useUpdateGateway } from "@app/hooks/api/gateways-v2";
import { TGatewayV2, TGatewayV2WithAuthMethod } from "@app/hooks/api/gateways-v2/types";
import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
-import { NetworkingAuthMethodForm } from "../../../components/NetworkingAuthMethodForm";
+import {
+ NetworkingAuthMethodForm,
+ toNetworkingAuthMethodInput
+} from "../../../components/NetworkingAuthMethodForm";
const HealthBadge = ({ gateway }: { gateway: TGatewayV2 }) => {
if (!gateway.heartbeat && !gateway.heartbeatTTL) {
@@ -147,19 +150,12 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
currentMethod={authMethod}
isDisabled={!isAllowed}
isPending={isUpdatingAuthMethod}
+ availableMethods={["token", "aws", "kubernetes"]}
onUpdate={async (form) => {
try {
await updateGateway({
gatewayId: gateway.id,
- authMethod:
- form.method === "aws"
- ? {
- method: "aws",
- stsEndpoint: form.stsEndpoint,
- allowedPrincipalArns: form.allowedPrincipalArns,
- allowedAccountIds: form.allowedAccountIds
- }
- : { method: "token" }
+ authMethod: toNetworkingAuthMethodInput(form)
});
createNotification({ type: "success", text: "Auth method updated" });
return true;
diff --git a/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx b/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx
index e7f06775ae..0b776db4ef 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx
@@ -1,6 +1,7 @@
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
+import { HelpCircleIcon, InfoIcon } from "lucide-react";
import { z } from "zod";
import {
@@ -10,7 +11,12 @@ import {
FieldError,
FieldLabel,
FilterableSelect,
- Input
+ Input,
+ Switch,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
} from "@app/components/v3";
import { useOrganization } from "@app/context";
@@ -23,10 +29,17 @@ import {
const schema = z
.object({
- method: z.enum(["aws", "token"]),
+ method: z.enum(["aws", "kubernetes", "token"]),
stsEndpoint: z.string(),
allowedPrincipalArns: z.string(),
- allowedAccountIds: z.string()
+ allowedAccountIds: z.string(),
+ kubernetesHost: z.string(),
+ caCertificate: z.string(),
+ tokenReviewerJwt: z.string(),
+ allowedNamespaces: z.string(),
+ allowedNames: z.string(),
+ allowedAudience: z.string(),
+ verifyTlsCertificate: z.boolean()
})
.superRefine((data, ctx) => {
if (
@@ -46,9 +59,62 @@ const schema = z
message
});
}
+
+ if (data.method === "kubernetes") {
+ if (!data.kubernetesHost.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["kubernetesHost"],
+ message: "Kubernetes host is required"
+ });
+ }
+ if (!data.allowedNamespaces.trim() && !data.allowedNames.trim()) {
+ const message =
+ "At least one of allowed namespaces or allowed service account names must be set";
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["allowedNamespaces"],
+ message
+ });
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["allowedNames"],
+ message
+ });
+ }
+ }
});
-type FormData = z.infer<typeof schema>;
+export type NetworkingAuthMethodFormData = z.infer<typeof schema>;
+
+type FormData = NetworkingAuthMethodFormData;
+
+export const toNetworkingAuthMethodInput = (form: FormData) => {
+ if (form.method === "aws") {
+ return {
+ method: "aws" as const,
+ stsEndpoint: form.stsEndpoint,
+ allowedPrincipalArns: form.allowedPrincipalArns,
+ allowedAccountIds: form.allowedAccountIds
+ };
+ }
+
+ if (form.method === "kubernetes") {
+ return {
+ method: "kubernetes" as const,
+ kubernetesHost: form.kubernetesHost,
+ caCertificate: form.caCertificate,
+ // Write-only, so a blank field means "leave the stored value alone".
+ tokenReviewerJwt: form.tokenReviewerJwt.trim() ? form.tokenReviewerJwt : undefined,
+ allowedNamespaces: form.allowedNamespaces,
+ allowedNames: form.allowedNames,
+ allowedAudience: form.allowedAudience,
+ verifyTlsCertificate: form.verifyTlsCertificate
+ };
+ }
+
+ return { method: "token" as const };
+};
type AuthMethod =
| {
@@ -59,6 +125,18 @@ type AuthMethod =
allowedAccountIds: string;
};
}
+ | {
+ method: "kubernetes";
+ config: {
+ kubernetesHost: string;
+ allowedNamespaces: string;
+ allowedNames: string;
+ allowedAudience: string;
+ verifyTlsCertificate: boolean;
+ caCertificate: string;
+ hasTokenReviewerJwt: boolean;
+ };
+ }
| {
method: "token";
config?: unknown;
@@ -68,6 +146,8 @@ type Props = {
currentMethod: AuthMethod;
isDisabled?: boolean;
isPending: boolean;
+ // Kubernetes auth is gateway-only, since only gateways run inside the cluster.
+ availableMethods?: NetworkingAuthMethod[];
onUpdate: (authMethod: FormData) => Promise<boolean>;
};
@@ -75,16 +155,29 @@ export const NetworkingAuthMethodForm = ({
currentMethod,
isDisabled = false,
isPending,
+ availableMethods = ["token", "aws"],
onUpdate
}: Props) => {
const { isSubOrganization } = useOrganization();
const initialMethod: NetworkingAuthMethod = currentMethod.method;
const initialAws = currentMethod.method === "aws" ? currentMethod.config : undefined;
+ const initialKubernetes =
+ currentMethod.method === "kubernetes" ? currentMethod.config : undefined;
+ const methodOptions = NETWORKING_AUTH_METHOD_OPTIONS.filter(({ value }) =>
+ availableMethods.includes(value)
+ );
const defaultValues: FormData = {
method: initialMethod,
stsEndpoint: initialAws?.stsEndpoint ?? "https://sts.amazonaws.com/",
allowedPrincipalArns: initialAws?.allowedPrincipalArns ?? "",
- allowedAccountIds: initialAws?.allowedAccountIds ?? ""
+ allowedAccountIds: initialAws?.allowedAccountIds ?? "",
+ kubernetesHost: initialKubernetes?.kubernetesHost ?? "",
+ caCertificate: initialKubernetes?.caCertificate ?? "",
+ tokenReviewerJwt: "",
+ allowedNamespaces: initialKubernetes?.allowedNamespaces ?? "",
+ allowedNames: initialKubernetes?.allowedNames ?? "",
+ allowedAudience: initialKubernetes?.allowedAudience ?? "",
+ verifyTlsCertificate: initialKubernetes?.verifyTlsCertificate ?? true
};
const {
@@ -107,6 +200,12 @@ export const NetworkingAuthMethodForm = ({
initialAws?.stsEndpoint,
initialAws?.allowedPrincipalArns,
initialAws?.allowedAccountIds,
+ initialKubernetes?.kubernetesHost,
+ initialKubernetes?.allowedNamespaces,
+ initialKubernetes?.allowedNames,
+ initialKubernetes?.allowedAudience,
+ initialKubernetes?.verifyTlsCertificate,
+ initialKubernetes?.caCertificate,
reset
]);
@@ -126,8 +225,7 @@ export const NetworkingAuthMethodForm = ({
name="method"
render={({ field }) => {
const selected =
- NETWORKING_AUTH_METHOD_OPTIONS.find((option) => option.value === field.value) ??
- NETWORKING_AUTH_METHOD_OPTIONS[0];
+ methodOptions.find((option) => option.value === field.value) ?? methodOptions[0];
return (
<FilterableSelect
@@ -136,7 +234,7 @@ export const NetworkingAuthMethodForm = ({
const next = option as { value: NetworkingAuthMethod } | null;
if (next) field.onChange(next.value);
}}
- options={NETWORKING_AUTH_METHOD_OPTIONS}
+ options={methodOptions}
isSearchable={false}
isClearable={false}
isDisabled={isDisabled || isSaving}
@@ -210,6 +308,298 @@ export const NetworkingAuthMethodForm = ({
</>
)}
+ {method === "kubernetes" && (
+ <>
+ <Controller
+ control={control}
+ name="kubernetesHost"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="k8s-host" className="inline-flex items-center gap-1.5">
+ Kubernetes Host / Base Kubernetes API URL
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ <div className="flex flex-col gap-1">
+ <p>
+ The host string, host:port pair, or URL to the base of the Kubernetes API
+ server. This can usually be obtained by running &apos;kubectl
+ cluster-info&apos;
+ </p>
+ <p>
+ Must be reachable from Infisical, which reviews the token on each login.
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ id="k8s-host"
+ autoComplete="off"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ placeholder="https://my-example-k8s-api-host.com"
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="allowedNamespaces"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel
+ htmlFor="k8s-allowed-namespaces"
+ className="inline-flex items-center gap-1.5"
+ >
+ Allowed Namespaces
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ <div className="flex flex-col gap-1">
+ <p>
+ A comma-separated list of trusted namespaces that service accounts must
+ belong to authenticate as this gateway.
+ </p>
+ <p>
+ Wildcard patterns are supported. Use <span className="font-mono">*</span>{" "}
+ to explicitly allow all.
+ </p>
+ <p className="text-sm">
+ Examples: <span className="font-mono">dev-*</span>,{" "}
+ <span className="font-mono">staging-*</span>
+ </p>
+ <p>
+ At least one of allowed namespaces or service account names is required.
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ id="k8s-allowed-namespaces"
+ autoComplete="off"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ placeholder="namespaceA, namespaceB, dev-*"
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="allowedNames"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel
+ htmlFor="k8s-allowed-names"
+ className="inline-flex items-center gap-1.5"
+ >
+ Allowed Service Account Names
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ <div className="flex flex-col gap-1">
+ <p>
+ A comma-separated list of trusted service account names that are allowed
+ to authenticate as this gateway.
+ </p>
+ <p>
+ Wildcard patterns are supported. Use <span className="font-mono">*</span>{" "}
+ to explicitly allow all.
+ </p>
+ <p className="text-sm">
+ Examples: <span className="font-mono">dev-*</span>,{" "}
+ <span className="font-mono">app-*-prod</span>
+ </p>
+ <p>
+ At least one of allowed namespaces or service account names is required.
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ id="k8s-allowed-names"
+ autoComplete="off"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ placeholder="service-account-1-name, sa-*, app-*-prod"
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="allowedAudience"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel
+ htmlFor="k8s-allowed-audience"
+ className="inline-flex items-center gap-1.5"
+ >
+ Allowed Audience (optional)
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ An optional audience claim that the service account JWT token must have to
+ authenticate with Infisical. Leave empty to allow any audience claim.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <Input
+ {...field}
+ id="k8s-allowed-audience"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ placeholder="https://kubernetes.default.svc"
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="caCertificate"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="k8s-ca-cert" className="inline-flex items-center gap-1.5">
+ CA Certificate (optional)
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ The PEM-encoded CA certificate that issued the Kubernetes API server&apos;s
+ TLS certificate. Required for TLS certificate verification to take effect.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ id="k8s-ca-cert"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ rows={3}
+ className="font-mono text-xs"
+ placeholder="-----BEGIN CERTIFICATE----- ..."
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="tokenReviewerJwt"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel
+ htmlFor="k8s-token-reviewer"
+ className="inline-flex items-center gap-1.5"
+ >
+ Token Reviewer JWT (optional)
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ Optional JWT token for accessing Kubernetes TokenReview API. If provided, this
+ long-lived token will be used to validate service account tokens during
+ authentication. If omitted, the gateway&apos;s own JWT will be used instead,
+ which requires the gateway to have the system:auth-delegator ClusterRole
+ binding.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <TextArea
+ {...field}
+ id="k8s-token-reviewer"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ rows={2}
+ className="font-mono text-xs"
+ placeholder={
+ initialKubernetes?.hasTokenReviewerJwt
+ ? "A reviewer token is configured. Paste a new one to replace it."
+ : "eyJhbGciOiJSUzI1NiIs..."
+ }
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="verifyTlsCertificate"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <div className="flex items-center gap-2">
+ <Switch
+ id="gateway-k8s-verify-tls"
+ variant="org"
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ disabled={isDisabled || isSaving}
+ />
+ <FieldLabel
+ htmlFor="gateway-k8s-verify-tls"
+ className="mb-0 inline-flex items-center gap-1.5"
+ >
+ Verify TLS Certificate
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircleIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ <div className="flex flex-col gap-2">
+ <p>
+ When enabled, Infisical validates the Kubernetes API server&apos;s TLS
+ certificate against the CA certificate provided above.
+ </p>
+ <p>
+ This only takes effect while a CA certificate is configured. Without one
+ there is nothing to verify against, so the API server&apos;s identity is
+ not checked even when this is enabled. The connection is still over
+ HTTPS.
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ </div>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ </>
+ )}
+
{isDirty && (
<div className="flex justify-end gap-2">
<Button
diff --git a/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodLabel.tsx b/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodLabel.tsx
index 591fe28243..c40f148130 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodLabel.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodLabel.tsx
@@ -5,7 +5,7 @@ import {
} from "react-select";
import { CheckIcon, KeyIcon } from "lucide-react";
-export type NetworkingAuthMethod = "aws" | "token";
+export type NetworkingAuthMethod = "aws" | "kubernetes" | "token";
export type NetworkingAuthMethodOption = {
value: NetworkingAuthMethod;
@@ -14,20 +14,33 @@ export type NetworkingAuthMethodOption = {
export const NETWORKING_AUTH_METHOD_OPTIONS: NetworkingAuthMethodOption[] = [
{ value: "token", label: "Token Auth" },
- { value: "aws", label: "AWS Auth" }
+ { value: "aws", label: "AWS Auth" },
+ { value: "kubernetes", label: "Kubernetes Auth" }
];
-const NetworkingAuthMethodIcon = ({ method }: { method: NetworkingAuthMethod }) =>
- method === "aws" ? (
- <img
- src="/images/integrations/Amazon Web Services.png"
- alt=""
- aria-hidden
- className="size-4 object-contain"
- />
- ) : (
- <KeyIcon className="size-4 text-accent" />
- );
+const NetworkingAuthMethodIcon = ({ method }: { method: NetworkingAuthMethod }) => {
+ if (method === "aws") {
+ return (
+ <img
+ src="/images/integrations/Amazon Web Services.png"
+ alt=""
+ aria-hidden
+ className="size-4 object-contain"
+ />
+ );
+ }
+ if (method === "kubernetes") {
+ return (
+ <img
+ src="/images/integrations/Kubernetes.png"
+ alt=""
+ aria-hidden
+ className="size-4 object-contain"
+ />
+ );
+ }
+ return <KeyIcon className="size-4 text-accent" />;
+};
export const NetworkingAuthMethodLabel = ({
method,
diff --git a/helm-charts/infisical-gateway/CHANGELOG.md b/helm-charts/infisical-gateway/CHANGELOG.md
index 6547cf60f8..78a22331c3 100644
--- a/helm-charts/infisical-gateway/CHANGELOG.md
+++ b/helm-charts/infisical-gateway/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 1.3.0 (August 4, 2026)
+* Added Kubernetes auth enrollment (`gateway.enrollment.method: kubernetes`). The gateway authenticates with the projected service account token of its own pod, so no enrollment token or cloud credential needs to be distributed to the cluster.
+* Added `gateway.enrollment.kubernetes.gatewayId` and `gateway.enrollment.kubernetes.serviceAccountTokenPath`.
+
## 1.2.0 (July 17, 2026)
* Added `extraEnv` for injecting additional environment variables into the gateway container.
* Added `extraEnvFrom` for loading environment variables from Secrets or ConfigMaps.
diff --git a/helm-charts/infisical-gateway/Chart.yaml b/helm-charts/infisical-gateway/Chart.yaml
index 78dd022d17..840777a907 100644
--- a/helm-charts/infisical-gateway/Chart.yaml
+++ b/helm-charts/infisical-gateway/Chart.yaml
@@ -15,7 +15,7 @@ type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
-version: 1.2.0
+version: 1.3.0
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
diff --git a/helm-charts/infisical-gateway/templates/deployment.yaml b/helm-charts/infisical-gateway/templates/deployment.yaml
index 9ff2ceaa73..ed99fc3822 100644
--- a/helm-charts/infisical-gateway/templates/deployment.yaml
+++ b/helm-charts/infisical-gateway/templates/deployment.yaml
@@ -1,5 +1,10 @@
{{- $sessionPath := .Values.gateway.pamSessionRecordingsDirectory | default "/var/lib/infisical/session_recordings" }}
{{- $usePVC := and .Values.persistence.enabled (or .Values.gateway.enrollment.method .Values.persistence.existingClaim) }}
+{{- if eq .Values.gateway.enrollment.method "kubernetes" }}
+ {{- if not .Values.serviceAccount.automount }}
+ {{- fail "serviceAccount.automount must be true when gateway.enrollment.method is 'kubernetes'. The gateway authenticates with the projected service account token of its own pod." }}
+ {{- end }}
+{{- end }}
{{- if eq .Values.gateway.enrollment.method "token" }}
{{- if not .Values.persistence.enabled }}
{{- fail "persistence.enabled must be true when gateway.enrollment.method is 'token'. The enrollment token is single-use and credentials must persist across pod restarts." }}
@@ -105,6 +110,12 @@ spec:
{{- if eq .Values.gateway.enrollment.method "aws" }}
- --gateway-id={{ required "gateway.enrollment.aws.gatewayId is required when gateway.enrollment.method is 'aws'" .Values.gateway.enrollment.aws.gatewayId }}
{{- end }}
+ {{- if eq .Values.gateway.enrollment.method "kubernetes" }}
+ - --gateway-id={{ required "gateway.enrollment.kubernetes.gatewayId is required when gateway.enrollment.method is 'kubernetes'" .Values.gateway.enrollment.kubernetes.gatewayId }}
+ {{- if .Values.gateway.enrollment.kubernetes.serviceAccountTokenPath }}
+ - --service-account-token-path={{ .Values.gateway.enrollment.kubernetes.serviceAccountTokenPath }}
+ {{- end }}
+ {{- end }}
{{- if .Values.gateway.relayName }}
- --target-relay-name={{ .Values.gateway.relayName }}
{{- end }}
diff --git a/helm-charts/infisical-gateway/values.yaml b/helm-charts/infisical-gateway/values.yaml
index c4fd86c0c5..4d27f335aa 100644
--- a/helm-charts/infisical-gateway/values.yaml
+++ b/helm-charts/infisical-gateway/values.yaml
@@ -16,7 +16,7 @@ gateway:
domain: ""
enrollment:
- # Enrollment method: "token" or "aws".
+ # Enrollment method: "token", "aws", or "kubernetes".
# Leave empty to use the legacy machine identity flow (env vars from secret.name).
method: ""
@@ -34,6 +34,16 @@ gateway:
# Required when method=aws. Gateway ID from the Infisical UI.
gatewayId: ""
+ # Kubernetes enrollment settings (method=kubernetes).
+ # The gateway authenticates with the projected service account token of its own pod, so no
+ # credential needs to be distributed. Requires serviceAccount.createAsAuthDelegator (default)
+ # unless a separate token reviewer is configured on the gateway in Infisical.
+ kubernetes:
+ # Required when method=kubernetes. Gateway ID from the Infisical UI.
+ gatewayId: ""
+ # Path to the projected service account token. Only override for a non-default mount.
+ serviceAccountTokenPath: ""
+
# Name of a K8s Secret whose key-value pairs are injected as env vars.
# Use this to provide credentials for the enrollment method (e.g. AWS keys, GCP credentials).
# Not needed when credentials are provided via workload identity (IRSA, GCP Workload Identity, etc.).
@@ -46,7 +56,8 @@ gateway:
# Persistent storage for the gateway (credentials and session recordings).
# Required when enrollment.method=token so credentials survive pod restarts.
-# Optional when enrollment.method=aws since it re-authenticates via STS on every start.
+# Optional when enrollment.method=aws or enrollment.method=kubernetes, since both re-authenticate
+# on every start.
# For legacy machine-identity installs (no enrollment.method), persistence only takes effect
# when existingClaim is provided.
persistence: