Skip to content

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

feat(gateway): review Kubernetes tokens through a gateway

bernie-g719650bccb78
diff --git a/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts b/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts
index 3aa4b275d6..b0c55c83fd 100644
--- a/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts
+++ b/backend/src/db/migrations/20260804134122_resource-kubernetes-auth.ts
@@ -9,16 +9,32 @@ export async function up(knex: Knex): Promise<void> {
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();
+ // Null when the review runs through a gateway using its own service account, which needs no address.
+ t.string("kubernetesHost", 255).nullable();
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.string("tokenReviewMode", 32).notNullable().defaultTo("api");
+ // RESTRICT rather than SET NULL: nulling the proxy would leave a config that cannot
+ // authenticate, failing at the next login instead of at the delete the user chose.
+ t.uuid("gatewayV2Id").nullable();
+ t.foreign("gatewayV2Id").references("id").inTable(TableName.GatewayV2).onDelete("RESTRICT");
+ t.uuid("gatewayPoolId").nullable();
+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");
t.timestamps(true, true, true);
});
+ // Partial: both are null except when the review is proxied, and the RESTRICT checks need them.
+ await knex.raw(
+ `CREATE INDEX IF NOT EXISTS "resource_kubernetes_auths_gateway_v2_id_index" ON ${TableName.ResourceKubernetesAuth} ("gatewayV2Id") WHERE "gatewayV2Id" IS NOT NULL`
+ );
+ await knex.raw(
+ `CREATE INDEX IF NOT EXISTS "resource_kubernetes_auths_gateway_pool_id_index" ON ${TableName.ResourceKubernetesAuth} ("gatewayPoolId") WHERE "gatewayPoolId" IS NOT NULL`
+ );
+
await createOnUpdateTrigger(knex, TableName.ResourceKubernetesAuth);
}
}
diff --git a/backend/src/db/schemas/resource-kubernetes-auths.ts b/backend/src/db/schemas/resource-kubernetes-auths.ts
index b55aafc890..b8b06cbe2e 100644
--- a/backend/src/db/schemas/resource-kubernetes-auths.ts
+++ b/backend/src/db/schemas/resource-kubernetes-auths.ts
@@ -12,7 +12,7 @@ import { TImmutableDBKeys } from "./models";
export const ResourceKubernetesAuthsSchema = z.object({
id: z.string().uuid(),
authMethodId: z.string().uuid(),
- kubernetesHost: z.string(),
+ kubernetesHost: z.string().nullable().optional(),
encryptedKubernetesCaCertificate: zodBuffer.nullable().optional(),
encryptedKubernetesTokenReviewerJwt: zodBuffer.nullable().optional(),
allowedNamespaces: z.string().default(""),
@@ -20,7 +20,10 @@ export const ResourceKubernetesAuthsSchema = z.object({
allowedAudience: z.string().default(""),
verifyTlsCertificate: z.boolean().default(true),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ tokenReviewMode: z.string().default("api"),
+ gatewayV2Id: z.string().uuid().nullable().optional(),
+ gatewayPoolId: z.string().uuid().nullable().optional()
});
export type TResourceKubernetesAuths = z.infer<typeof ResourceKubernetesAuthsSchema>;
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
index 8f1a8e1849..e5abac9778 100644
--- a/backend/src/ee/routes/v3/gateway-router.ts
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -8,7 +8,10 @@ import {
validateAllowedNamespaces,
validateKubernetesHost
} from "@app/ee/services/resource-auth-method/kubernetes-auth-validators";
-import { ResourceAuthMethodType } from "@app/ee/services/resource-auth-method/resource-auth-method-fns";
+import {
+ KubernetesTokenReviewMode,
+ 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";
@@ -61,9 +64,15 @@ const AwsAuthMethodInputSchema = z
const KubernetesAuthMethodInputSchema = z
.object({
method: z.literal(ResourceAuthMethodType.Kubernetes),
- kubernetesHost: validateKubernetesHost.describe(GATEWAYS.AUTH_METHOD.kubernetesHost),
+ kubernetesHost: validateKubernetesHost.optional().describe(GATEWAYS.AUTH_METHOD.kubernetesHost),
caCertificate: z.string().trim().max(10240).optional().describe(GATEWAYS.AUTH_METHOD.caCertificate),
tokenReviewerJwt: z.string().trim().max(8192).optional().describe(GATEWAYS.AUTH_METHOD.tokenReviewerJwt),
+ tokenReviewMode: z
+ .nativeEnum(KubernetesTokenReviewMode)
+ .default(KubernetesTokenReviewMode.Api)
+ .describe(GATEWAYS.AUTH_METHOD.tokenReviewMode),
+ gatewayV2Id: z.string().uuid().nullable().optional().describe(GATEWAYS.AUTH_METHOD.gatewayV2Id),
+ gatewayPoolId: z.string().uuid().nullable().optional().describe(GATEWAYS.AUTH_METHOD.gatewayPoolId),
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),
@@ -72,6 +81,23 @@ const KubernetesAuthMethodInputSchema = z
.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"]
+ })
+ .refine((data) => !(data.gatewayV2Id && data.gatewayPoolId), {
+ message: "Select either a gateway or a gateway pool to review tokens, not both",
+ path: ["gatewayPoolId"]
+ })
+ .refine(
+ (data) => data.tokenReviewMode !== KubernetesTokenReviewMode.Gateway || data.gatewayV2Id || data.gatewayPoolId,
+ {
+ message: "Gateway review mode requires a gateway or gateway pool to perform the review",
+ path: ["gatewayV2Id"]
+ }
+ )
+ // Only gateway review mode can go without a host, because there the gateway calls its own
+ // API server rather than an address we supply.
+ .refine((data) => data.tokenReviewMode === KubernetesTokenReviewMode.Gateway || Boolean(data.kubernetesHost), {
+ message: "A Kubernetes host is required unless the review mode is Gateway as Reviewer",
+ path: ["kubernetesHost"]
});
const TokenAuthMethodInputSchema = z.object({
@@ -106,6 +132,9 @@ const toCreateAuthMethodArg = (input: TSettableAuthMethodInput) => {
kubernetesHost: input.kubernetesHost,
caCertificate: input.caCertificate,
tokenReviewerJwt: input.tokenReviewerJwt,
+ tokenReviewMode: input.tokenReviewMode,
+ gatewayV2Id: input.gatewayV2Id,
+ gatewayPoolId: input.gatewayPoolId,
allowedNamespaces: input.allowedNamespaces,
allowedNames: input.allowedNames,
allowedAudience: input.allowedAudience,
@@ -131,6 +160,9 @@ const toSetAuthMethodArg = (input: TSettableAuthMethodInput) => {
kubernetesHost: input.kubernetesHost,
caCertificate: input.caCertificate,
tokenReviewerJwt: input.tokenReviewerJwt,
+ tokenReviewMode: input.tokenReviewMode,
+ gatewayV2Id: input.gatewayV2Id,
+ gatewayPoolId: input.gatewayPoolId,
allowedNamespaces: input.allowedNamespaces,
allowedNames: input.allowedNames,
allowedAudience: input.allowedAudience,
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 fc1a455912..f534efd39e 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -72,8 +72,8 @@ type TGatewayV2ServiceFactoryDep = {
| "mintToken"
| "loginWithToken"
| "encryptKubernetesSecrets"
- | "assertKubernetesHostAllowed"
- | "validateKubernetesConfigReachable"
+ | "preflightKubernetesConfig"
+ | "findKubernetesProxyDependents"
>;
};
@@ -1006,6 +1006,13 @@ export const gatewayV2ServiceFactory = ({
OrgPermissionSubjects.Gateway
);
+ const proxyDependents = await resourceAuthMethodService.findKubernetesProxyDependents(gateway.id);
+ if (proxyDependents.length) {
+ throw new BadRequestError({
+ message: `Gateway '${gateway.name}' reviews Kubernetes tokens for ${proxyDependents.map((name) => `'${name}'`).join(", ")}. Point those gateways at a different reviewer before deleting this one.`
+ });
+ }
+
try {
return await gatewayV2DAL.deleteById(gateway.id);
} catch (err) {
@@ -1215,13 +1222,7 @@ export const gatewayV2ServiceFactory = ({
// 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
- });
+ await resourceAuthMethodService.preflightKubernetesConfig(authMethod.config);
authMethodArg = {
method: authMethod.method,
config: {
diff --git a/backend/src/ee/services/resource-auth-method/gateway-proxy-registry.ts b/backend/src/ee/services/resource-auth-method/gateway-proxy-registry.ts
new file mode 100644
index 0000000000..315ed505b0
--- /dev/null
+++ b/backend/src/ee/services/resource-auth-method/gateway-proxy-registry.ts
@@ -0,0 +1,35 @@
+import { InternalServerError } from "@app/lib/errors";
+
+import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";
+
+export type TResolveGatewayProxyDTO = {
+ gatewayV2Id?: string | null;
+ gatewayPoolId?: string | null;
+ targetHost: string;
+ targetPort: number;
+};
+
+export type TGatewayProxyResolver = (dto: TResolveGatewayProxyDTO) => Promise<TGatewayV2ConnectionDetails | undefined>;
+
+// Kubernetes auth can route TokenReview traffic through a gateway, but resolving a gateway's proxy
+// credentials lives on gatewayV2Service and gatewayPoolService, both of which are constructed after
+// resourceAuthMethodService and depend on it. Rather than break that ordering, the resolver is
+// registered here after all three exist, the same way alertProviderRegistry is populated.
+export const gatewayProxyRegistryFactory = () => {
+ let resolver: TGatewayProxyResolver | undefined;
+
+ const register = (fn: TGatewayProxyResolver) => {
+ resolver = fn;
+ };
+
+ const resolve: TGatewayProxyResolver = async (dto) => {
+ if (!resolver) {
+ throw new InternalServerError({ message: "Gateway proxy resolver has not been registered" });
+ }
+ return resolver(dto);
+ };
+
+ return { register, resolve };
+};
+
+export type TGatewayProxyRegistry = ReturnType<typeof gatewayProxyRegistryFactory>;
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
index a0353691cd..b6087a5cd2 100644
--- a/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts
@@ -39,6 +39,64 @@ const toServerName = (kubernetesHost: string) => {
return isIP(servername) ? undefined : servername;
};
+// One shape for both routes to the API server: straight out from Infisical, or tunnelled through a
+// gateway. Callers below only deal in paths, so nothing downstream has to know which is in play.
+export type TKubernetesRequestExecutor = <T = unknown>(
+ method: "get" | "post",
+ path: string,
+ body?: object,
+ headers?: Record<string, string>
+) => Promise<{ status: number; data: T }>;
+
+const withScheme = (kubernetesHost: string) =>
+ new RE2("^https?://").test(kubernetesHost) ? kubernetesHost : `https://${kubernetesHost}`;
+
+export const buildDirectKubernetesExecutor = ({
+ kubernetesHost,
+ caCertificate,
+ verifyTlsCertificate
+}: {
+ kubernetesHost: string;
+ caCertificate?: string;
+ verifyTlsCertificate: boolean;
+}): TKubernetesRequestExecutor => {
+ const baseUrl = withScheme(kubernetesHost);
+
+ return async <T>(method: "get" | "post", path: string, body?: object, headers?: Record<string, string>) => {
+ // Fresh per call: an abort signal must not be shared between requests.
+ const config = {
+ headers,
+ ca: caCertificate || undefined,
+ rejectUnauthorized: verifyTlsCertificate,
+ servername: toServerName(kubernetesHost),
+ timeout: TOKEN_REVIEW_TIMEOUT_MS,
+ signal: AbortSignal.timeout(TOKEN_REVIEW_TIMEOUT_MS),
+ maxContentLength: TOKEN_REVIEW_MAX_RESPONSE_BYTES,
+ validateStatus: () => true
+ };
+
+ // safeRequest pins the connection to the addresses it validated, so a hostname that
+ // re-resolves to a private address between config time and login cannot be reached.
+ const res =
+ method === "get"
+ ? await safeRequest.get<T>(`${baseUrl}${path}`, config)
+ : await safeRequest.post<T>(`${baseUrl}${path}`, body, config);
+
+ return { status: res.status, data: res.data };
+ };
+};
+
+// A gateway cannot vouch for itself: the proxy runs over the gateway's own tunnel, which only
+// exists once it has already authenticated. Left unchecked, this config would never log in.
+export const assertKubernetesProxyNotSelf = (resource: { type: string; id: string }, gatewayV2Id?: string | null) => {
+ if (gatewayV2Id && resource.type === "gateway" && gatewayV2Id === resource.id) {
+ throw new BadRequestError({
+ message:
+ "A gateway cannot review its own Kubernetes token. Select a different gateway, one that is already enrolled and connected."
+ });
+ }
+};
+
export const assertKubernetesHostAllowed = async (kubernetesHost: string) => {
const url = kubernetesHost.startsWith("https://") ? kubernetesHost : `https://${kubernetesHost}`;
try {
@@ -56,40 +114,36 @@ export const assertKubernetesHostAllowed = async (kubernetesHost: string) => {
// 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,
+ executor,
+ target,
tokenReviewerJwt,
- verifyTlsCertificate
+ isGatewayReviewer = false
}: {
- kubernetesHost: string;
- caCertificate?: string;
+ executor: TKubernetesRequestExecutor;
+ // Where the request went, for error messages: a host, or a gateway's name.
+ target: string;
tokenReviewerJwt?: string;
- verifyTlsCertificate: boolean;
+ isGatewayReviewer?: boolean;
}) => {
- const host = kubernetesHost.startsWith("https://") ? kubernetesHost : `https://${kubernetesHost}`;
-
- // Fresh per call: the abort signal must not be shared between the two requests.
- const requestConfig = () => ({
- ca: caCertificate || undefined,
- rejectUnauthorized: verifyTlsCertificate,
- servername: toServerName(kubernetesHost),
- timeout: TOKEN_REVIEW_TIMEOUT_MS,
- signal: AbortSignal.timeout(TOKEN_REVIEW_TIMEOUT_MS),
- maxContentLength: TOKEN_REVIEW_MAX_RESPONSE_BYTES,
- validateStatus: () => true
- });
-
const classify = (err: unknown, context: KubernetesAuthErrorContext) => {
- if (err instanceof BadRequestError) return err;
- if (err instanceof AxiosError) return handleAxiosError(err, { kubernetesHost: host }, context);
+ // Checked before the BadRequestError passthrough: the proxy layer wraps an aborted tunnel as a
+ // BadRequestError whose message is just "canceled". A gateway that is not a pod in the cluster
+ // has no service account to review with, so the request never completes.
+ if (isGatewayReviewer) {
+ return new BadRequestError({
+ message:
+ "The selected gateway could not review the token with its own service account. Gateway as Reviewer requires that gateway to run as a pod inside the cluster with the system:auth-delegator ClusterRole. Use the token reviewer JWT mode for a gateway outside the cluster."
+ });
+ }
+ if (err instanceof AxiosError) return handleAxiosError(err, { kubernetesHost: target }, context);
return new BadRequestError({
- message: `Failed to reach the Kubernetes API server at ${host}: ${(err as Error).message}`
+ message: `Failed to reach the Kubernetes API server at ${target}: ${(err as Error).message}`
});
};
let versionStatus: number;
try {
- const res = await safeRequest.get(`${host}/version`, requestConfig());
+ const res = await executor("get", "/version");
versionStatus = res.status;
} catch (err) {
throw classify(err, KubernetesAuthErrorContext.KubernetesHost);
@@ -98,44 +152,50 @@ export const validateKubernetesConfigReachable = async ({
// the Kubernetes API at all, which is the common typo and used to save happily.
if (versionStatus === 404) {
throw new BadRequestError({
- message: `${host} does not look like a Kubernetes API server: /version returned 404. Verify the host and port.`
+ message: `${target} does not look like a Kubernetes API server: /version returned 404. Verify the host and port.`
});
}
if (versionStatus >= 500) {
throw new BadRequestError({
- message: `Kubernetes API server at ${host} returned ${versionStatus}. Verify the host is correct and healthy.`
+ message: `Kubernetes API server at ${target} returned ${versionStatus}. Verify the host is correct and healthy.`
});
}
- if (!tokenReviewerJwt) return;
+ // Nothing to probe when Infisical will fall back to letting the incoming token review itself:
+ // that token does not exist until a gateway actually logs in.
+ if (!tokenReviewerJwt && !isGatewayReviewer) return;
let review: { status: number; data: unknown };
try {
- review = await safeRequest.post(
- `${host}${TOKEN_REVIEW_PATH}`,
+ review = await executor(
+ "post",
+ TOKEN_REVIEW_PATH,
{
apiVersion: TOKEN_REVIEW_API_VERSION,
kind: TOKEN_REVIEW_KIND,
spec: { token: TOKEN_REVIEW_PROBE_TOKEN }
},
{
- ...requestConfig(),
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${tokenReviewerJwt}` }
+ "Content-Type": "application/json",
+ ...(tokenReviewerJwt ? { Authorization: `Bearer ${tokenReviewerJwt}` } : {})
}
);
} catch (err) {
throw classify(err, KubernetesAuthErrorContext.KubernetesApiServer);
}
+ const reviewer = isGatewayReviewer ? "The gateway's own service account" : "The token reviewer JWT";
+
if (review.status === 401) {
throw new BadRequestError({
- message: "The token reviewer JWT is invalid or expired. Provide a valid service account token."
+ message: isGatewayReviewer
+ ? `${reviewer} is not authorized against the Kubernetes API server. Verify the gateway is deployed correctly.`
+ : `${reviewer} is invalid or expired. Provide a valid service account token.`
});
}
if (review.status === 403) {
throw new BadRequestError({
- message:
- "The token reviewer JWT cannot perform TokenReviews. Ensure its service account has the 'system:auth-delegator' ClusterRole binding."
+ message: `${reviewer} cannot perform TokenReviews. Ensure its service account has the 'system:auth-delegator' ClusterRole binding.`
});
}
if (review.status >= 400) {
@@ -146,32 +206,31 @@ export const validateKubernetesConfigReachable = async ({
type TReviewServiceAccountTokenInput = {
jwt: string;
- kubernetesHost: string;
- caCertificate: string;
+ executor: TKubernetesRequestExecutor;
+ // Where the request went, for error messages and logs: a host, or a gateway's name.
+ target: string;
tokenReviewerJwt: string;
- verifyTlsCertificate: boolean;
+ isGatewayReviewer?: boolean;
allowedAudience: string;
errorContext: Record<string, unknown>;
};
export const reviewServiceAccountToken = async ({
jwt,
- kubernetesHost,
- caCertificate,
+ executor,
+ target,
tokenReviewerJwt,
- verifyTlsCertificate,
+ isGatewayReviewer = false,
allowedAudience,
errorContext
}: TReviewServiceAccountTokenInput) => {
- const baseUrl =
- kubernetesHost.startsWith("http://") || kubernetesHost.startsWith("https://")
- ? kubernetesHost
- : `https://${kubernetesHost}`;
+ const kubernetesHost = target;
let review: TCreateTokenReviewResponse;
try {
- const res = await safeRequest.post<TCreateTokenReviewResponse>(
- `${baseUrl}${TOKEN_REVIEW_PATH}`,
+ const res = await executor<TCreateTokenReviewResponse>(
+ "post",
+ TOKEN_REVIEW_PATH,
{
apiVersion: TOKEN_REVIEW_API_VERSION,
kind: TOKEN_REVIEW_KIND,
@@ -181,20 +240,12 @@ export const reviewServiceAccountToken = async ({
}
},
{
- 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,
- maxContentLength: TOKEN_REVIEW_MAX_RESPONSE_BYTES,
- // safeRequest pins the connection to the addresses it validated, so a hostname that
- // re-resolves to a private address between config time and login cannot be reached.
- ca: caCertificate || undefined,
- rejectUnauthorized: verifyTlsCertificate,
- servername: toServerName(kubernetesHost)
+ "Content-Type": "application/json",
+ // The gateway reviewer supplies its own credential at the far end, so sending one here
+ // would override it. Otherwise, with no reviewer configured the incoming token reviews
+ // itself, which works because the Helm chart grants the gateway's service account
+ // system:auth-delegator.
+ ...(isGatewayReviewer ? {} : { Authorization: `Bearer ${tokenReviewerJwt || jwt}` })
}
);
review = res.data;
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts b/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
new file mode 100644
index 0000000000..e69833e528
--- /dev/null
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
@@ -0,0 +1,89 @@
+import https from "node:https";
+
+import { request as httpRequest } from "@app/lib/config/request";
+import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+
+import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";
+import { TKubernetesRequestExecutor } from "./kubernetes-auth-fns";
+
+const PROXY_TIMEOUT_MS = 10_000;
+const PROXY_MAX_RESPONSE_BYTES = 64 * 1024;
+
+// Where an in-cluster gateway finds its own API server. Carries a scheme to match what machine
+// identity Kubernetes auth sends, and is only routing metadata: in gateway-reviewer mode the
+// gateway resolves the address itself.
+const IN_CLUSTER_API_SERVER = "https://kubernetes.default.svc.cluster.local";
+
+// The proxy target is baked into the client certificate the resolver mints, so the resolver and the
+// executor have to agree on it. Both derive it from here.
+export const resolveKubernetesProxyTarget = (kubernetesHost?: string) => {
+ if (!kubernetesHost) return { targetHost: IN_CLUSTER_API_SERVER, targetPort: 443 };
+
+ const parsed = new URL(kubernetesHost.includes("://") ? kubernetesHost : `https://${kubernetesHost}`);
+ return { targetHost: parsed.hostname, targetPort: parsed.port ? Number(parsed.port) : 443 };
+};
+
+type TBuildInput = {
+ connectionDetails: TGatewayV2ConnectionDetails;
+ // Omitted in gateway-reviewer mode, where the gateway calls its own API server.
+ kubernetesHost?: string;
+ caCertificate?: string;
+ verifyTlsCertificate?: boolean;
+};
+
+// Routes TokenReview traffic through a gateway instead of straight out from Infisical, for clusters
+// whose API server we cannot reach. Two shapes, matching machine identity Kubernetes auth:
+//
+// no kubernetesHost -> HTTP proxy, and the gateway performs the review with its own service
+// account. Only valid when that gateway runs as a pod in the cluster.
+// kubernetesHost -> TCP tunnel to that address, and Infisical performs the review as usual.
+// Works from any gateway that can reach the API server.
+export const buildGatewayKubernetesExecutor = ({
+ connectionDetails,
+ kubernetesHost,
+ caCertificate,
+ verifyTlsCertificate
+}: TBuildInput): TKubernetesRequestExecutor => {
+ const isGatewayReviewer = !kubernetesHost;
+ const { targetHost } = resolveKubernetesProxyTarget(kubernetesHost);
+
+ // In gateway-reviewer mode the gateway presents its own credentials at the far end, so there is
+ // no TLS session for us to configure here.
+ const httpsAgent = isGatewayReviewer
+ ? undefined
+ : new https.Agent({
+ ca: caCertificate || undefined,
+ rejectUnauthorized: verifyTlsCertificate ?? true,
+ servername: targetHost
+ });
+
+ return async <T>(method: "get" | "post", path: string, body?: object, headers?: Record<string, string>) =>
+ withGatewayV2Proxy(
+ async (port) => {
+ const url = `${isGatewayReviewer ? "http" : "https"}://localhost:${port}${path}`;
+ const config = {
+ headers: {
+ ...headers,
+ ...(isGatewayReviewer ? { "x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount } : {})
+ },
+ httpsAgent,
+ timeout: PROXY_TIMEOUT_MS,
+ signal: AbortSignal.timeout(PROXY_TIMEOUT_MS),
+ maxContentLength: PROXY_MAX_RESPONSE_BYTES,
+ validateStatus: () => true
+ };
+
+ const res =
+ method === "get" ? await httpRequest.get<T>(url, config) : await httpRequest.post<T>(url, body, config);
+ return { status: res.status, data: res.data };
+ },
+ {
+ protocol: isGatewayReviewer ? GatewayProxyProtocol.Http : GatewayProxyProtocol.Tcp,
+ relayHost: connectionDetails.relayHost,
+ gateway: connectionDetails.gateway,
+ relay: connectionDetails.relay,
+ httpsAgent
+ }
+ );
+};
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 48da3778b2..f22b8439cb 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
@@ -135,9 +135,20 @@ export const ResourceAuthLoginFailureReason = {
NoAllowlistConfigured: "no_allowlist_configured",
NamespaceNotAllowed: "namespace_not_allowed",
NameNotAllowed: "name_not_allowed",
- AudienceNotAllowed: "audience_not_allowed"
+ AudienceNotAllowed: "audience_not_allowed",
+ GatewayProxyUnavailable: "gateway_proxy_unavailable"
} as const;
+// Who performs the TokenReview. Api means Infisical does, using the configured reviewer token.
+// Gateway means the proxying gateway does, using its own in-cluster service account, which needs
+// no Kubernetes host or reviewer token but requires that gateway to be a pod in the cluster.
+export const KubernetesTokenReviewMode = {
+ Api: "api",
+ Gateway: "gateway"
+} as const;
+
+export type TKubernetesTokenReviewMode = (typeof KubernetesTokenReviewMode)[keyof typeof KubernetesTokenReviewMode];
+
export const ResourceAuthMethodType = {
Aws: "aws",
Kubernetes: "kubernetes",
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
index 03165d6595..17b026ee2f 100644
--- 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
@@ -14,6 +14,9 @@ export const AwsAuthMethodConfigSchema = z.object({
export const KubernetesAuthMethodConfigSchema = z.object({
id: z.string().uuid(),
kubernetesHost: z.string(),
+ tokenReviewMode: z.string(),
+ gatewayV2Id: z.string().nullable(),
+ gatewayPoolId: z.string().nullable(),
allowedNamespaces: z.string(),
allowedNames: z.string(),
allowedAudience: z.string(),
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 10f7c2161f..fbff9326c2 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
@@ -20,18 +20,24 @@ 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 { TGatewayProxyRegistry } from "./gateway-proxy-registry";
import { TResourceKubernetesAuthDALFactory } from "./kubernetes-auth-dal";
import {
assertKubernetesHostAllowed,
+ assertKubernetesProxyNotSelf,
+ buildDirectKubernetesExecutor,
reviewServiceAccountToken,
+ TKubernetesRequestExecutor,
validateKubernetesAllowlists,
validateKubernetesConfigReachable
} from "./kubernetes-auth-fns";
+import { buildGatewayKubernetesExecutor, resolveKubernetesProxyTarget } from "./kubernetes-gateway-executor";
import { TResourceAuthMethodDALFactory } from "./resource-auth-method-dal";
import {
assertGatewayResource,
assertKmipServerResource,
assertRelayResource,
+ KubernetesTokenReviewMode,
mintGatewayJwt,
mintKmipServerJwt,
mintRelayJwt,
@@ -77,6 +83,7 @@ type TResourceAuthMethodServiceFactoryDep = {
kmipServerDAL: Pick<TKmipServerDALFactory, "findById" | "updateById">;
identityDAL: Pick<TIdentityDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ gatewayProxyRegistry: TGatewayProxyRegistry;
};
export type TResourceAuthMethodServiceFactory = ReturnType<typeof resourceAuthMethodServiceFactory>;
@@ -118,7 +125,8 @@ export const resourceAuthMethodServiceFactory = ({
relayDAL,
kmipServerDAL,
identityDAL,
- permissionService
+ permissionService,
+ gatewayProxyRegistry
}: TResourceAuthMethodServiceFactoryDep) => {
// Registry rows carry the resource FK in a per-type column (gatewayId/relayId/kmipServerId).
const $registryFilter = (resource: ResourceRef) => {
@@ -258,7 +266,10 @@ export const resourceAuthMethodServiceFactory = ({
method: ResourceAuthMethodType.Kubernetes,
config: {
id: config.id,
- kubernetesHost: config.kubernetesHost,
+ kubernetesHost: config.kubernetesHost ?? "",
+ tokenReviewMode: config.tokenReviewMode,
+ gatewayV2Id: config.gatewayV2Id ?? null,
+ gatewayPoolId: config.gatewayPoolId ?? null,
allowedNamespaces: config.allowedNamespaces,
allowedNames: config.allowedNames,
allowedAudience: config.allowedAudience,
@@ -345,6 +356,122 @@ export const resourceAuthMethodServiceFactory = ({
return Boolean(pending);
};
+ // Picks the route to the API server: straight out from Infisical, or tunnelled through a gateway.
+ // Makes network calls when proxied, so call it outside a transaction.
+ const $buildKubernetesExecutor = async (config: {
+ kubernetesHost?: string | null;
+ caCertificate?: string;
+ verifyTlsCertificate: boolean;
+ tokenReviewMode?: string | null;
+ gatewayV2Id?: string | null;
+ gatewayPoolId?: string | null;
+ }): Promise<{ executor: TKubernetesRequestExecutor; target: string; isGatewayReviewer: boolean }> => {
+ const proxyId = config.gatewayV2Id ?? config.gatewayPoolId;
+ const isGatewayReviewer = config.tokenReviewMode === KubernetesTokenReviewMode.Gateway;
+
+ if (!proxyId) {
+ if (!config.kubernetesHost) {
+ throw new BadRequestError({ message: "A Kubernetes host is required unless the review runs via a gateway." });
+ }
+ return {
+ executor: buildDirectKubernetesExecutor({
+ kubernetesHost: config.kubernetesHost,
+ caCertificate: config.caCertificate,
+ verifyTlsCertificate: config.verifyTlsCertificate
+ }),
+ target: config.kubernetesHost,
+ isGatewayReviewer: false
+ };
+ }
+
+ // In gateway review mode the gateway calls its own API server, so no host is involved.
+ const proxiedHost = isGatewayReviewer ? undefined : config.kubernetesHost;
+ if (!isGatewayReviewer && !proxiedHost) {
+ throw new BadRequestError({
+ message: "A Kubernetes host is required when the review mode is the token reviewer JWT."
+ });
+ }
+
+ const { targetHost, targetPort } = resolveKubernetesProxyTarget(proxiedHost ?? undefined);
+ const connectionDetails = await gatewayProxyRegistry.resolve({
+ gatewayV2Id: config.gatewayV2Id,
+ gatewayPoolId: config.gatewayPoolId,
+ targetHost,
+ targetPort
+ });
+
+ if (!connectionDetails) {
+ throw new BadRequestError({
+ message: `The gateway selected to review Kubernetes tokens is not reachable. It must be enrolled and connected before another gateway can authenticate through it.`
+ });
+ }
+
+ return {
+ executor: buildGatewayKubernetesExecutor({
+ connectionDetails,
+ kubernetesHost: proxiedHost ?? undefined,
+ caCertificate: config.caCertificate,
+ verifyTlsCertificate: config.verifyTlsCertificate
+ }),
+ target: proxiedHost || "the Kubernetes API server via the selected gateway",
+ isGatewayReviewer
+ };
+ };
+
+ // Whole config-time check for a Kubernetes auth method: the host is only reachable-checked when
+ // Infisical dials it directly, since a proxied address is resolved inside the customer network.
+ // Makes network calls, so call it outside a transaction.
+ const preflightKubernetesConfig = async (
+ config: Pick<
+ TKubernetesAuthMethodConfig,
+ | "kubernetesHost"
+ | "caCertificate"
+ | "tokenReviewerJwt"
+ | "verifyTlsCertificate"
+ | "tokenReviewMode"
+ | "gatewayV2Id"
+ | "gatewayPoolId"
+ >,
+ // Absent when the resource does not exist yet, where it cannot be its own proxy.
+ resource?: ResourceRef
+ ) => {
+ if (resource) assertKubernetesProxyNotSelf(resource, config.gatewayV2Id);
+
+ const isProxied = Boolean(config.gatewayV2Id ?? config.gatewayPoolId);
+ if (!isProxied && config.kubernetesHost) {
+ await assertKubernetesHostAllowed(config.kubernetesHost);
+ }
+
+ const { executor, target, isGatewayReviewer } = await $buildKubernetesExecutor({
+ kubernetesHost: config.kubernetesHost,
+ caCertificate: config.caCertificate,
+ verifyTlsCertificate: config.verifyTlsCertificate,
+ tokenReviewMode: config.tokenReviewMode,
+ gatewayV2Id: config.gatewayV2Id,
+ gatewayPoolId: config.gatewayPoolId
+ });
+
+ await validateKubernetesConfigReachable({
+ executor,
+ target,
+ tokenReviewerJwt: config.tokenReviewerJwt,
+ isGatewayReviewer
+ });
+ };
+
+ // Names the gateways that would break if this one were deleted, so the delete path can say so
+ // instead of surfacing a bare foreign key violation.
+ const findKubernetesProxyDependents = async (gatewayV2Id: string): Promise<string[]> => {
+ const configs = await resourceKubernetesAuthDAL.find({ gatewayV2Id });
+ if (!configs.length) return [];
+
+ const registries = await Promise.all(configs.map((config) => resourceAuthMethodDAL.findById(config.authMethodId)));
+ const dependentIds = registries.map((registry) => registry?.gatewayId).filter(Boolean) as string[];
+
+ const gateways = await Promise.all(dependentIds.map((id) => gatewayV2DAL.findById(id)));
+ return gateways.map((gateway) => gateway?.name).filter(Boolean) as string[];
+ };
+
// Call before opening a transaction: the KMS round-trip must not hold a pool connection.
const encryptKubernetesSecrets = async (
orgId: string,
@@ -407,7 +534,10 @@ export const resourceAuthMethodServiceFactory = ({
await resourceKubernetesAuthDAL.create(
{
authMethodId: registry.id,
- kubernetesHost: authMethod.config.kubernetesHost,
+ kubernetesHost: authMethod.config.kubernetesHost || null,
+ tokenReviewMode: authMethod.config.tokenReviewMode ?? KubernetesTokenReviewMode.Api,
+ gatewayV2Id: authMethod.config.gatewayV2Id ?? null,
+ gatewayPoolId: authMethod.config.gatewayPoolId ?? null,
allowedNamespaces: authMethod.config.allowedNamespaces,
allowedNames: authMethod.config.allowedNames,
allowedAudience: authMethod.config.allowedAudience,
@@ -443,7 +573,10 @@ export const resourceAuthMethodServiceFactory = ({
let encryptedKubernetesSecrets: TEncryptedKubernetesSecrets = {};
if (authMethod.method === ResourceAuthMethodType.Kubernetes) {
- await assertKubernetesHostAllowed(authMethod.kubernetesHost);
+ const isProxied = Boolean(authMethod.gatewayV2Id ?? authMethod.gatewayPoolId);
+ if (!isProxied && authMethod.kubernetesHost) {
+ await assertKubernetesHostAllowed(authMethod.kubernetesHost);
+ }
// Switching in from another method has no stored secret to preserve, so omitted means null.
const isMethodChange = previousMethod !== ResourceAuthMethodType.Kubernetes;
@@ -459,7 +592,11 @@ export const resourceAuthMethodServiceFactory = ({
// token, so it must never travel to an endpoint it was not validated against. Someone with
// edit access could otherwise point the host at a server they control, omit the write-only
// field, and read the stored token off the wire.
+ // Gateway review mode is exempt: the gateway reviews with its own service account, so the
+ // stored token is not sent anywhere and there is no endpoint for it to leak to.
+ const isGatewayReviewer = authMethod.tokenReviewMode === KubernetesTokenReviewMode.Gateway;
if (
+ !isGatewayReviewer &&
stored?.encryptedKubernetesTokenReviewerJwt &&
effectiveReviewer === undefined &&
stored.kubernetesHost !== authMethod.kubernetesHost
@@ -486,11 +623,22 @@ export const resourceAuthMethodServiceFactory = ({
}
}
- await validateKubernetesConfigReachable({
+ assertKubernetesProxyNotSelf(resource, authMethod.gatewayV2Id);
+
+ const validation = await $buildKubernetesExecutor({
kubernetesHost: authMethod.kubernetesHost,
caCertificate: effectiveCa,
+ verifyTlsCertificate: authMethod.verifyTlsCertificate,
+ tokenReviewMode: authMethod.tokenReviewMode,
+ gatewayV2Id: authMethod.gatewayV2Id,
+ gatewayPoolId: authMethod.gatewayPoolId
+ });
+
+ await validateKubernetesConfigReachable({
+ executor: validation.executor,
+ target: validation.target,
tokenReviewerJwt: effectiveReviewer,
- verifyTlsCertificate: authMethod.verifyTlsCertificate
+ isGatewayReviewer: validation.isGatewayReviewer
});
encryptedKubernetesSecrets = await encryptKubernetesSecrets(actor.orgId, {
@@ -559,7 +707,10 @@ export const resourceAuthMethodServiceFactory = ({
if (authMethod.method === ResourceAuthMethodType.Kubernetes) {
const sharedFields = {
- kubernetesHost: authMethod.kubernetesHost,
+ kubernetesHost: authMethod.kubernetesHost || null,
+ tokenReviewMode: authMethod.tokenReviewMode ?? KubernetesTokenReviewMode.Api,
+ gatewayV2Id: authMethod.gatewayV2Id ?? null,
+ gatewayPoolId: authMethod.gatewayPoolId ?? null,
allowedNamespaces: authMethod.allowedNamespaces,
allowedNames: authMethod.allowedNames,
allowedAudience: authMethod.allowedAudience,
@@ -794,12 +945,21 @@ export const resourceAuthMethodServiceFactory = ({
}
}
- const { namespace, serviceAccountName, audiences } = await reviewServiceAccountToken({
- jwt,
+ const login = await $buildKubernetesExecutor({
kubernetesHost: config.kubernetesHost,
caCertificate,
- tokenReviewerJwt,
verifyTlsCertificate: config.verifyTlsCertificate,
+ tokenReviewMode: config.tokenReviewMode,
+ gatewayV2Id: config.gatewayV2Id,
+ gatewayPoolId: config.gatewayPoolId
+ });
+
+ const { namespace, serviceAccountName, audiences } = await reviewServiceAccountToken({
+ jwt,
+ executor: login.executor,
+ target: login.target,
+ tokenReviewerJwt,
+ isGatewayReviewer: login.isGatewayReviewer,
allowedAudience: config.allowedAudience,
errorContext
});
@@ -901,8 +1061,8 @@ export const resourceAuthMethodServiceFactory = ({
getByKmipServerId,
loadView,
canRevoke,
- assertKubernetesHostAllowed,
- validateKubernetesConfigReachable,
+ preflightKubernetesConfig,
+ findKubernetesProxyDependents,
encryptKubernetesSecrets,
initAtCreate,
setMethod,
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 6b3d5feedf..e6928ce6bb 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
@@ -1,6 +1,6 @@
import { OrgServiceActor } from "@app/lib/types";
-import { ResourceAuthMethodType, ResourceRef } from "./resource-auth-method-fns";
+import { ResourceAuthMethodType, ResourceRef, TKubernetesTokenReviewMode } from "./resource-auth-method-fns";
export type TAwsAuthMethodConfig = {
stsEndpoint: string;
@@ -9,13 +9,17 @@ export type TAwsAuthMethodConfig = {
};
export type TKubernetesAuthMethodConfig = {
- kubernetesHost: string;
+ // Omitted only in gateway review mode, where the gateway calls its own API server.
+ kubernetesHost?: string | null;
allowedNamespaces: string;
allowedNames: string;
allowedAudience: string;
verifyTlsCertificate: boolean;
caCertificate?: string;
tokenReviewerJwt?: string;
+ tokenReviewMode?: TKubernetesTokenReviewMode;
+ gatewayV2Id?: string | null;
+ gatewayPoolId?: string | null;
};
// A missing key means "keep the stored value"; null means "clear it".
@@ -28,9 +32,14 @@ export type TEncryptedKubernetesSecrets = {
// cluster credential, so only its presence is reported.
export type TKubernetesAuthMethodConfigView = Omit<
TKubernetesAuthMethodConfig,
- "caCertificate" | "tokenReviewerJwt"
+ "caCertificate" | "tokenReviewerJwt" | "kubernetesHost" | "tokenReviewMode" | "gatewayV2Id" | "gatewayPoolId"
> & {
id: string;
+ // Always present on read, empty when the review runs through a gateway's own service account.
+ kubernetesHost: string;
+ tokenReviewMode: string;
+ gatewayV2Id: string | null;
+ gatewayPoolId: string | null;
caCertificate: string;
hasTokenReviewerJwt: boolean;
createdAt: Date;
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index b9762677e3..b9e3a0b494 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3805,7 +3805,13 @@ export const GATEWAYS = {
allowedAccountIds:
"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).",
+ "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). Omit only when tokenReviewMode is 'gateway', where the reviewing gateway calls its own API server.",
+ tokenReviewMode:
+ "Who performs the TokenReview. 'api' means Infisical does, using the configured token reviewer JWT. 'gateway' means the selected gateway does, using its own in-cluster service account, which requires no Kubernetes host or reviewer token but requires that gateway to run as a pod in the cluster.",
+ gatewayV2Id:
+ "The gateway to route TokenReview traffic through, for clusters whose API server Infisical cannot reach. Must be a different gateway that is already enrolled and connected. Mutually exclusive with gatewayPoolId.",
+ gatewayPoolId:
+ "The gateway pool to route TokenReview traffic through. Any healthy member performs the request, so this survives a single gateway going offline. Mutually exclusive with gatewayV2Id.",
caCertificate:
"The PEM-encoded CA certificate that issued the Kubernetes API server's TLS certificate. Required when the API server uses a certificate the system trust store does not recognise, which is the usual case for a cluster CA.",
tokenReviewerJwt:
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3ef4b47a99..3d46f2d516 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 { gatewayProxyRegistryFactory } from "@app/ee/services/resource-auth-method/gateway-proxy-registry";
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";
@@ -1786,6 +1787,10 @@ export const registerRoutes = async (
keyStore
});
+ // Populated after gatewayV2Service and gatewayPoolService exist; both depend on
+ // resourceAuthMethodService, so the proxy resolver cannot be a constructor dependency.
+ const gatewayProxyRegistry = gatewayProxyRegistryFactory();
+
const resourceAuthMethodService = resourceAuthMethodServiceFactory({
resourceAuthMethodDAL,
resourceAwsAuthDAL,
@@ -1796,7 +1801,8 @@ export const registerRoutes = async (
relayDAL,
kmipServerDAL,
identityDAL,
- permissionService
+ permissionService,
+ gatewayProxyRegistry
});
const relayService = relayServiceFactory({
@@ -1849,6 +1855,14 @@ export const registerRoutes = async (
dynamicSecretDAL
});
+ gatewayProxyRegistry.register(async ({ gatewayV2Id, gatewayPoolId, targetHost, targetPort }) => {
+ if (gatewayPoolId) {
+ return gatewayPoolService.getPlatformConnectionDetailsByPoolId({ poolId: gatewayPoolId, targetHost, targetPort });
+ }
+ if (!gatewayV2Id) return undefined;
+ return gatewayV2Service.getPlatformConnectionDetailsByGatewayId({ gatewayId: gatewayV2Id, targetHost, targetPort });
+ });
+
const pamAccountTemplateService = pamAccountTemplateServiceFactory({
pamAccountTemplateDAL,
pamAccountDAL,
diff --git a/docs/documentation/platform/gateways/gateway-deployment.mdx b/docs/documentation/platform/gateways/gateway-deployment.mdx
index 72b3732379..01c08d66bb 100644
--- a/docs/documentation/platform/gateways/gateway-deployment.mdx
+++ b/docs/documentation/platform/gateways/gateway-deployment.mdx
@@ -162,7 +162,9 @@ This guide covers everything you need to deploy and configure Infisical Gateways
| Field | Description |
| --- | --- |
- | **Kubernetes Host** | The cluster API server URL, reachable from Infisical (for example `https://my-cluster.example.com:6443`). |
+ | **Gateway** | Optional. Routes the check through an existing gateway or gateway pool instead of Infisical calling the API server directly. Use this when the API server has no address Infisical can reach. |
+ | **Review Mode** | Shown once a proxy is selected. See the private cluster section below. |
+ | **Kubernetes Host** | The cluster API server URL, reachable from Infisical (for example `https://my-cluster.example.com:6443`). Not required when Review Mode is Gateway as Reviewer. |
| **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. |
@@ -171,6 +173,23 @@ This guide covers everything you need to deploy and configure Infisical Gateways
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.
+ ### Clusters with a private API server
+
+ By default Infisical calls your API server directly, which requires an address it can reach. If your API server is private, select a gateway or gateway pool under **Gateway** and the check is tunnelled through it instead. Two modes are available:
+
+ | Review Mode | Who performs the check | Requires |
+ | --- | --- | --- |
+ | **Gateway as Reviewer** | The selected gateway, using its own service account | That gateway runs as a pod in the same cluster. No host or reviewer token needed. |
+ | **Manual Token Reviewer JWT (API)** | Infisical, tunnelling through the gateway | A Kubernetes host and a reviewer token. Works from any gateway that can reach the API server, including one on a VM in the same network. |
+
+ Prefer a gateway pool over a single gateway. Any healthy member performs the check, so one gateway going offline does not stop the others from authenticating.
+
+ <Warning>
+ A gateway cannot review its own token. The proxy runs over the gateway's own tunnel, which only exists once it has already authenticated, so the reviewer must be a different gateway that is already enrolled and connected.
+
+ This means the **first** gateway in a private cluster cannot use Kubernetes auth. Enrol it with an enrollment token or AWS auth, then point later gateways at it. Deleting a gateway that other gateways use as their reviewer is refused until they are pointed elsewhere.
+ </Warning>
+
<Tabs>
<Tab title="Kubernetes (Helm)">
Install the Infisical Helm chart repository:
diff --git a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
index d99a6d56ae..a45251bc65 100644
--- a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
+++ b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
@@ -36,6 +36,8 @@ type Props = {
isError?: boolean;
noGatewayLabel?: string;
noGatewayIcon?: LucideIcon;
+ // Hides one gateway from the list, for callers where selecting it would be self-referential.
+ excludeGatewayId?: string;
};
const SectionLabel = ({ children }: { children: React.ReactNode }) => (
@@ -53,7 +55,8 @@ export const GatewayPicker = ({
placeholder,
isError,
noGatewayLabel = "Internet Gateway",
- noGatewayIcon: NoGatewayIcon = GlobeIcon
+ noGatewayIcon: NoGatewayIcon = GlobeIcon,
+ excludeGatewayId
}: Props) => {
const { subscription } = useSubscription();
const { currentOrg } = useOrganization();
@@ -85,7 +88,7 @@ export const GatewayPicker = ({
}
};
- const v2Gateways = gateways?.filter((g) => !g.isV1) ?? [];
+ const v2Gateways = gateways?.filter((g) => !g.isV1 && g.id !== excludeGatewayId) ?? [];
const isOnline = (gw: (typeof v2Gateways)[number]) => isGatewayHealthy(gw);
diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.ts
index 460b8c0dd4..3e4c141c9d 100644
--- a/frontend/src/hooks/api/gateways-v2/types.ts
+++ b/frontend/src/hooks/api/gateways-v2/types.ts
@@ -33,6 +33,9 @@ export type GatewayKubernetesAuthConfig = {
verifyTlsCertificate: boolean;
caCertificate: string;
hasTokenReviewerJwt: boolean;
+ tokenReviewMode: string;
+ gatewayV2Id: string | null;
+ gatewayPoolId: string | null;
createdAt: string;
updatedAt: string;
};
@@ -63,10 +66,14 @@ export type SettableAuthMethodInput =
}
| {
method: "kubernetes";
- kubernetesHost: string;
+ // Omitted only in gateway review mode, where the gateway calls its own API server.
+ kubernetesHost?: string;
caCertificate?: string;
// Write-only. Omitted means "keep the stored value"; an empty string clears it.
tokenReviewerJwt?: string;
+ tokenReviewMode?: string;
+ gatewayV2Id?: string | null;
+ gatewayPoolId?: string | null;
allowedNamespaces: string;
allowedNames: string;
allowedAudience?: string;
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 cc06d8ad29..a8fb70021d 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
@@ -151,6 +151,7 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
isDisabled={!isAllowed}
isPending={isUpdatingAuthMethod}
availableMethods={["token", "aws", "kubernetes"]}
+ currentGatewayId={gateway.id}
onUpdate={async (form) => {
try {
await updateGateway({
diff --git a/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx b/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx
index 54fb7e810a..3ff329faec 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/NetworkingAuthMethodForm.tsx
@@ -18,6 +18,7 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker/GatewayPicker";
import { useOrganization } from "@app/context";
import {
@@ -27,6 +28,11 @@ import {
NetworkingAuthMethodSingleValue
} from "./NetworkingAuthMethodLabel";
+const REVIEW_MODE_OPTIONS = [
+ { value: "gateway" as const, label: "Gateway as Reviewer" },
+ { value: "api" as const, label: "Manual Token Reviewer JWT (API)" }
+];
+
const schema = z
.object({
method: z.enum(["aws", "kubernetes", "token"]),
@@ -40,6 +46,12 @@ const schema = z
allowedNames: z.string(),
allowedAudience: z.string(),
verifyTlsCertificate: z.boolean(),
+ // "gateway" hands the review to the proxying gateway's own service account, which needs no
+ // host and no reviewer token but requires that gateway to run as a pod in the cluster.
+ tokenReviewMode: z.enum(["api", "gateway"]),
+ // Empty string means "no proxy": review straight from Infisical. Only one may be set.
+ gatewayV2Id: z.string(),
+ gatewayPoolId: z.string(),
// True once Reset is clicked, which swaps the stored token for an editable field. Saving with
// that field empty is what removes the token, since a never-returned value cannot be blanked.
resetTokenReviewerJwt: z.boolean()
@@ -64,13 +76,21 @@ const schema = z
}
if (data.method === "kubernetes") {
- if (!data.kubernetesHost.trim()) {
+ const isGatewayReviewer = data.tokenReviewMode === "gateway";
+ if (!isGatewayReviewer && !data.kubernetesHost.trim()) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["kubernetesHost"],
message: "Kubernetes host is required"
});
}
+ if (isGatewayReviewer && !data.gatewayV2Id && !data.gatewayPoolId) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["gatewayV2Id"],
+ message: "Select the gateway or pool that will perform the review"
+ });
+ }
if (!data.allowedNamespaces.trim() && !data.allowedNames.trim()) {
const message =
"At least one of allowed namespaces or allowed service account names must be set";
@@ -108,9 +128,14 @@ export const toNetworkingAuthMethodInput = (form: FormData) => {
}
if (form.method === "kubernetes") {
+ const isGatewayReviewer = form.tokenReviewMode === "gateway";
return {
method: "kubernetes" as const,
- kubernetesHost: form.kubernetesHost,
+ // The gateway resolves its own API server, so sending a host would be meaningless.
+ kubernetesHost: isGatewayReviewer ? undefined : form.kubernetesHost,
+ tokenReviewMode: form.tokenReviewMode,
+ gatewayV2Id: form.gatewayV2Id || null,
+ gatewayPoolId: form.gatewayPoolId || null,
caCertificate: form.caCertificate,
// Write-only: undefined keeps the stored value, empty string removes it.
tokenReviewerJwt: toTokenReviewerJwtInput(form),
@@ -143,6 +168,9 @@ type AuthMethod =
verifyTlsCertificate: boolean;
caCertificate: string;
hasTokenReviewerJwt: boolean;
+ tokenReviewMode: string;
+ gatewayV2Id: string | null;
+ gatewayPoolId: string | null;
};
}
| {
@@ -156,6 +184,8 @@ type Props = {
isPending: boolean;
// Kubernetes auth is gateway-only, since only gateways run inside the cluster.
availableMethods?: NetworkingAuthMethod[];
+ // Excluded from the proxy picker: a gateway cannot review its own token.
+ currentGatewayId?: string;
onUpdate: (authMethod: FormData) => Promise<boolean>;
};
@@ -164,6 +194,7 @@ export const NetworkingAuthMethodForm = ({
isDisabled = false,
isPending,
availableMethods = ["token", "aws"],
+ currentGatewayId,
onUpdate
}: Props) => {
const { isSubOrganization } = useOrganization();
@@ -186,6 +217,9 @@ export const NetworkingAuthMethodForm = ({
allowedNames: initialKubernetes?.allowedNames ?? "",
allowedAudience: initialKubernetes?.allowedAudience ?? "",
verifyTlsCertificate: initialKubernetes?.verifyTlsCertificate ?? true,
+ tokenReviewMode: initialKubernetes?.tokenReviewMode === "gateway" ? "gateway" : "api",
+ gatewayV2Id: initialKubernetes?.gatewayV2Id ?? "",
+ gatewayPoolId: initialKubernetes?.gatewayPoolId ?? "",
resetTokenReviewerJwt: false
};
@@ -216,11 +250,20 @@ export const NetworkingAuthMethodForm = ({
initialKubernetes?.allowedAudience,
initialKubernetes?.verifyTlsCertificate,
initialKubernetes?.caCertificate,
+ initialKubernetes?.tokenReviewMode,
+ initialKubernetes?.gatewayV2Id,
+ initialKubernetes?.gatewayPoolId,
reset
]);
const method = watch("method");
const isSaving = isSubmitting || isPending;
+ const verifyTlsCertificate = watch("verifyTlsCertificate");
+ const tokenReviewMode = watch("tokenReviewMode");
+ const gatewayV2Id = watch("gatewayV2Id");
+ const gatewayPoolId = watch("gatewayPoolId");
+ const isProxied = Boolean(gatewayV2Id || gatewayPoolId);
+ const isGatewayReviewer = tokenReviewMode === "gateway";
const isTokenReviewerJwtConfigured =
Boolean(initialKubernetes?.hasTokenReviewerJwt) && !watch("resetTokenReviewerJwt");
@@ -326,43 +369,123 @@ export const NetworkingAuthMethodForm = ({
<>
<Controller
control={control}
- name="kubernetesHost"
+ name="gatewayV2Id"
render={({ field, fieldState: { error } }) => (
<Field>
- <FieldLabel htmlFor="k8s-host" className="inline-flex items-center gap-1.5">
- Kubernetes Host / Base Kubernetes API URL
+ <FieldLabel className="inline-flex items-center gap-1.5">
+ Gateway (optional)
<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>
+ Routes the TokenReview through an existing gateway, for clusters whose API
+ server Infisical cannot reach. It must be a different gateway that is already
+ enrolled and connected, since a gateway cannot vouch for itself.
</TooltipContent>
</Tooltip>
</FieldLabel>
<FieldContent>
- <Input
- {...field}
- id="k8s-host"
- autoComplete="off"
- disabled={isDisabled || isSaving}
+ <GatewayPicker
+ value={{ gatewayId: field.value || null, gatewayPoolId: gatewayPoolId || null }}
+ onChange={(next) => {
+ setValue("gatewayV2Id", next.gatewayId ?? "", { shouldDirty: true });
+ setValue("gatewayPoolId", next.gatewayPoolId ?? "", { shouldDirty: true });
+ // Without a proxy there is nobody to hand the review to.
+ if (!next.gatewayId && !next.gatewayPoolId) {
+ setValue("tokenReviewMode", "api", { shouldDirty: true });
+ }
+ }}
+ isDisabled={isDisabled || isSaving}
isError={Boolean(error)}
- placeholder="https://my-example-k8s-api-host.com"
+ excludeGatewayId={currentGatewayId}
/>
<FieldError errors={[error]} />
</FieldContent>
</Field>
)}
/>
+ {isProxied && (
+ <Controller
+ control={control}
+ name="tokenReviewMode"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel className="inline-flex items-center gap-1.5">
+ Review Mode
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="size-3.5 text-muted" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-md">
+ Who performs the TokenReview. Gateway as Reviewer has the gateway do it with
+ its own service account, which needs no host or reviewer token but requires
+ that gateway to run as a pod in the cluster. Manual Token Reviewer JWT has
+ Infisical do it, tunnelling through the gateway to the host below.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={REVIEW_MODE_OPTIONS.find((option) => option.value === field.value)}
+ onChange={(option) => {
+ const next = option as { value: "api" | "gateway" } | null;
+ if (next) field.onChange(next.value);
+ }}
+ options={REVIEW_MODE_OPTIONS}
+ isDisabled={isDisabled || isSaving}
+ isSearchable={false}
+ isClearable={false}
+ getOptionLabel={(option) => option.label}
+ getOptionValue={(option) => option.value}
+ />
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ )}
+ {!isGatewayReviewer && (
+ <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"
@@ -494,138 +617,149 @@ export const NetworkingAuthMethodForm = ({
</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. Needed whenever the server uses a certificate the system
- trust store does not recognise, which is the usual case for a cluster CA.
- </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. A stored token is never shown again, so Reset is the only way to
- replace or remove one. Resetting is also required to change the Kubernetes
- host, since a stored token is never sent to a different host.
- </TooltipContent>
- </Tooltip>
- </FieldLabel>
- <FieldContent>
- {isTokenReviewerJwtConfigured ? (
+ {!isGatewayReviewer && (
+ <>
+ <Controller
+ control={control}
+ name="verifyTlsCertificate"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
<div className="flex items-center gap-2">
- <Input id="k8s-token-reviewer" value="Configured" disabled />
- <Button
- type="button"
- size="sm"
- variant="outline"
- isDisabled={isDisabled || isSaving}
- onClick={() =>
- setValue("resetTokenReviewerJwt", true, { shouldDirty: true })
- }
+ <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"
>
- Reset
- </Button>
+ 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 below.
+ </p>
+ <p>
+ With a CA certificate below, the server is verified against it.
+ Without one the system trust store is used, which a cluster CA will
+ not be in, so verification fails. Turn this off only for testing.
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
</div>
- ) : (
- <TextArea
- {...field}
- id="k8s-token-reviewer"
- disabled={isDisabled || isSaving}
- isError={Boolean(error)}
- rows={2}
- className="font-mono text-xs"
- placeholder="eyJhbGciOiJSUzI1NiIs..."
- />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ {verifyTlsCertificate && (
+ <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. Needed whenever the server uses a
+ certificate the system trust store does not recognise, which is the
+ usual case for a cluster CA.
+ </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>
)}
- <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>
- With a CA certificate above, the server is verified against it. Without
- one the system trust store is used, which a cluster CA will not be in,
- so verification fails. Turn this off only for testing.
- </p>
+ />
+ )}
+ <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. A stored token is never shown again, so Reset is the
+ only way to replace or remove one. Resetting is also required to change
+ the Kubernetes host, since a stored token is never sent to a different
+ host.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <FieldContent>
+ {isTokenReviewerJwtConfigured ? (
+ <div className="flex items-center gap-2">
+ <Input id="k8s-token-reviewer" value="Configured" disabled />
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ isDisabled={isDisabled || isSaving}
+ onClick={() =>
+ setValue("resetTokenReviewerJwt", true, { shouldDirty: true })
+ }
+ >
+ Reset
+ </Button>
</div>
- </TooltipContent>
- </Tooltip>
- </FieldLabel>
- </div>
- <FieldError errors={[error]} />
- </Field>
- )}
- />
+ ) : (
+ <TextArea
+ {...field}
+ id="k8s-token-reviewer"
+ disabled={isDisabled || isSaving}
+ isError={Boolean(error)}
+ rows={2}
+ className="font-mono text-xs"
+ placeholder="eyJhbGciOiJSUzI1NiIs..."
+ />
+ )}
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ </>
+ )}
</>
)}