Skip to content

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

feat(pam): gateway auth for kubernetes (#6021)

Saif Ur Rahmane9d059229de3
diff --git a/backend/src/ee/services/pam-account/pam-account-fns.ts b/backend/src/ee/services/pam-account/pam-account-fns.ts
index 679710e0ba..c0e4fd90df 100644
--- a/backend/src/ee/services/pam-account/pam-account-fns.ts
+++ b/backend/src/ee/services/pam-account/pam-account-fns.ts
@@ -1,6 +1,7 @@
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { KubernetesAuthMethod } from "../pam-resource/kubernetes/kubernetes-resource-enums";
import { PamResource } from "../pam-resource/pam-resource-enums";
import { TPamAccountCredentials, TPamResourceInternalMetadata } from "../pam-resource/pam-resource-types";
import { SSHAuthMethod } from "../pam-resource/ssh/ssh-resource-enums";
@@ -71,7 +72,12 @@ export const decryptAccountMessage = async ({
// Returns false for account types where all credential fields are already visible in the sanitized view
export const hasSensitiveCredentials = (resourceType: string, credentials: TPamAccountCredentials): boolean => {
if (resourceType === PamResource.AwsIam) return false;
- if (resourceType === PamResource.Kubernetes) return false;
+ if (
+ resourceType === PamResource.Kubernetes &&
+ "authMethod" in credentials &&
+ credentials.authMethod === KubernetesAuthMethod.GatewayKubernetesAuth
+ )
+ return false;
if (
resourceType === PamResource.SSH &&
"authMethod" in credentials &&
@@ -87,6 +93,7 @@ const hasConfiguredCredentials = (credentials: TPamAccountCredentials): boolean
if ("serviceAccountToken" in credentials && credentials.serviceAccountToken) return true;
if ("targetRoleArn" in credentials && credentials.targetRoleArn) return true;
if ("authMethod" in credentials && credentials.authMethod === SSHAuthMethod.Certificate) return true;
+ if ("authMethod" in credentials && credentials.authMethod === KubernetesAuthMethod.GatewayKubernetesAuth) return true;
return false;
};
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts
index 21d7da806c..a846debbe4 100644
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts
+++ b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-enums.ts
@@ -1,3 +1,4 @@
export enum KubernetesAuthMethod {
- ServiceAccountToken = "service-account-token"
+ ServiceAccountToken = "service-account-token",
+ GatewayKubernetesAuth = "gateway-kubernetes-auth"
}
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts
index d2c50dfc3a..ab847ca87a 100644
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts
+++ b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-factory.ts
@@ -2,7 +2,7 @@ import axios, { AxiosError } from "axios";
import https from "https";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway/types";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { logger } from "@app/lib/logger";
@@ -71,6 +71,38 @@ export const executeWithGateway = async <T>(
);
};
+const validateWithGatewayHttp = async <T>(
+ config: {
+ gatewayId: string;
+ },
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
+ operation: (baseUrl: string) => Promise<T>
+): Promise<T> => {
+ // For gateway-auth validation, the gateway auto-discovers the K8s API from env vars,
+ // so we use a placeholder host/port. The actual target is resolved by the gateway's
+ // use-k8s-sa handler via KUBERNETES_SERVICE_HOST env var.
+ const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId: config.gatewayId,
+ targetHost: "kubernetes.default.svc.cluster.local",
+ targetPort: 443
+ });
+ if (!platformConnectionDetails) {
+ throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
+ }
+ return withGatewayV2Proxy(
+ async (proxyPort) => {
+ const baseUrl = `http://localhost:${proxyPort}`;
+ return operation(baseUrl);
+ },
+ {
+ protocol: GatewayProxyProtocol.Http,
+ relayHost: platformConnectionDetails.relayHost,
+ gateway: platformConnectionDetails.gateway,
+ relay: platformConnectionDetails.relay
+ }
+ );
+};
+
export const kubernetesResourceFactory: TPamResourceFactory<
TKubernetesResourceConnectionDetails,
TKubernetesAccountCredentials,
@@ -127,13 +159,15 @@ export const kubernetesResourceFactory: TPamResourceFactory<
if (!gatewayId) {
throw new BadRequestError({ message: "Gateway ID is required" });
}
- try {
- await executeWithGateway(
- { connectionDetails, gatewayId, resourceType },
- gatewayV2Service,
- async (baseUrl, httpsAgent) => {
- const { authMethod } = credentials;
- if (authMethod === KubernetesAuthMethod.ServiceAccountToken) {
+
+ const { authMethod } = credentials;
+
+ if (authMethod === KubernetesAuthMethod.ServiceAccountToken) {
+ try {
+ await executeWithGateway(
+ { connectionDetails, gatewayId, resourceType },
+ gatewayV2Service,
+ async (baseUrl, httpsAgent) => {
// Validate service account token using SelfSubjectReview API (whoami)
// This endpoint doesn't require any special permissions from the service account
try {
@@ -169,22 +203,97 @@ export const kubernetesResourceFactory: TPamResourceFactory<
}
throw error;
}
- } else {
- throw new BadRequestError({
- message: `Unsupported Kubernetes auth method: ${authMethod as string}`
- });
}
+ );
+ return credentials;
+ } catch (error) {
+ if (error instanceof BadRequestError) {
+ throw error;
}
- );
- return credentials;
- } catch (error) {
- if (error instanceof BadRequestError) {
- throw error;
+ throw new BadRequestError({
+ message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
+ });
}
- throw new BadRequestError({
- message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
- });
}
+
+ if (authMethod === KubernetesAuthMethod.GatewayKubernetesAuth) {
+ // Validate gateway auth by performing an impersonated SelfSubjectReview through the gateway.
+ // The gateway's use-k8s-sa handler injects its own pod token and discovers the K8s API.
+ // We add Impersonate-User header which passes through untouched.
+ // This validates that the gateway has RBAC permission to impersonate the specified SA.
+ // NOTE: It does NOT verify the SA exists — K8s impersonation is a pure permission check.
+ // A non-existent SA passes validation here but fails at session time with 403.
+ try {
+ await validateWithGatewayHttp({ gatewayId }, gatewayV2Service, async (baseUrl) => {
+ const impersonateUser = `system:serviceaccount:${credentials.namespace}:${credentials.serviceAccountName}`;
+ try {
+ await axios.post(
+ `${baseUrl}/apis/authentication.k8s.io/v1/selfsubjectreviews`,
+ {
+ apiVersion: "authentication.k8s.io/v1",
+ kind: "SelfSubjectReview"
+ },
+ {
+ headers: {
+ "Content-Type": "application/json",
+ "x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount,
+ "Impersonate-User": impersonateUser
+ },
+ signal: AbortSignal.timeout(EXTERNAL_REQUEST_TIMEOUT),
+ timeout: EXTERNAL_REQUEST_TIMEOUT
+ }
+ );
+
+ logger.info(
+ `[Kubernetes Resource Factory] Gateway K8s auth validation successful [namespace=${credentials.namespace}] [sa=${credentials.serviceAccountName}]`
+ );
+ } catch (error) {
+ if (error instanceof AxiosError) {
+ const errorMessage =
+ (error.response?.data as { message?: string })?.message || error.response?.statusText || error.message;
+
+ if (errorMessage?.includes("failed to read k8s sa auth token")) {
+ throw new BadRequestError({
+ message:
+ "Gateway is not running inside a Kubernetes cluster. Gateway auth requires the gateway to be deployed as a pod."
+ });
+ }
+ if (error.response?.status === 403) {
+ if (errorMessage?.includes("impersonate")) {
+ throw new BadRequestError({
+ message: `Gateway service account lacks impersonation permissions for service account "${credentials.serviceAccountName}" in namespace "${credentials.namespace}". Ensure the gateway's ClusterRole includes the impersonate verb for this service account.`
+ });
+ }
+ throw new BadRequestError({
+ message: `Unable to impersonate service account "${credentials.serviceAccountName}" in namespace "${credentials.namespace}": ${errorMessage}`
+ });
+ }
+ if (error.code === "ECONNABORTED" || error.code === "ERR_CANCELED") {
+ throw new BadRequestError({
+ message: "Unable to reach the Kubernetes API server through the gateway."
+ });
+ }
+ throw new BadRequestError({
+ message: `Unable to validate gateway auth credentials: ${errorMessage}`
+ });
+ }
+ throw error;
+ }
+ });
+ return credentials;
+ } catch (error) {
+ if (error instanceof BadRequestError) {
+ throw error;
+ }
+ throw new BadRequestError({
+ message: `Unable to validate account credentials for ${resourceType}: ${(error as Error).message || String(error)}`
+ });
+ }
+ }
+
+ throw new BadRequestError({
+ message: `Unsupported Kubernetes auth method: ${authMethod as string}`
+ });
};
const rotateAccountCredentials: TPamResourceFactoryRotateAccountCredentials<
@@ -215,6 +324,9 @@ export const kubernetesResourceFactory: TPamResourceFactory<
}
}
+ // Gateway auth has no sensitive fields (namespace and serviceAccountName are identifiers, not secrets),
+ // so no sentinel handling is needed — fall through to return as-is.
+
return updatedAccountCredentials;
};
diff --git a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts
index aa60e91fb4..fddc7d5e48 100644
--- a/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts
+++ b/backend/src/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas.ts
@@ -36,8 +36,15 @@ export const KubernetesServiceAccountTokenCredentialsSchema = z.object({
serviceAccountToken: z.string().trim().max(10000)
});
+export const KubernetesGatewayAuthCredentialsSchema = z.object({
+ authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
+ namespace: z.string().trim().min(1).max(63),
+ serviceAccountName: z.string().trim().min(1).max(253)
+});
+
export const KubernetesAccountCredentialsSchema = z.discriminatedUnion("authMethod", [
- KubernetesServiceAccountTokenCredentialsSchema
+ KubernetesServiceAccountTokenCredentialsSchema,
+ KubernetesGatewayAuthCredentialsSchema
]);
export const KubernetesResourceSchema = BaseKubernetesResourceSchema.extend({
@@ -51,6 +58,11 @@ export const SanitizedKubernetesResourceSchema = BaseKubernetesResourceSchema.ex
.discriminatedUnion("authMethod", [
z.object({
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken)
+ }),
+ z.object({
+ authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
+ namespace: z.string(),
+ serviceAccountName: z.string()
})
])
.nullable()
@@ -85,6 +97,11 @@ export const SanitizedKubernetesAccountWithResourceSchema = BasePamAccountSchema
credentials: z.discriminatedUnion("authMethod", [
z.object({
authMethod: z.literal(KubernetesAuthMethod.ServiceAccountToken)
+ }),
+ z.object({
+ authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
+ namespace: z.string(),
+ serviceAccountName: z.string()
})
])
});
diff --git a/docs/documentation/platform/pam/getting-started/resources/kubernetes.mdx b/docs/documentation/platform/pam/getting-started/resources/kubernetes.mdx
index 1a9d7d1a3d..1b4e421717 100644
--- a/docs/documentation/platform/pam/getting-started/resources/kubernetes.mdx
+++ b/docs/documentation/platform/pam/getting-started/resources/kubernetes.mdx
@@ -4,11 +4,18 @@ sidebarTitle: "Kubernetes"
description: "Learn how to configure Kubernetes cluster access through Infisical PAM for secure, audited, and just-in-time access to your Kubernetes clusters."
---
-Infisical PAM supports secure, just-in-time access to Kubernetes clusters through service account token authentication. This allows your team to access Kubernetes clusters without sharing long-lived credentials, while maintaining a complete audit trail of who accessed what and when.
+Infisical PAM supports secure, just-in-time access to Kubernetes clusters. Your team can access Kubernetes clusters without sharing long-lived credentials, while maintaining a complete audit trail of who accessed what and when.
+
+There are two ways to authenticate:
+
+- **Service Account Token** — you provide a static token that the Gateway injects into requests. Simple to set up, but the token is long-lived and stored in Infisical.
+- **Gateway** — the Gateway uses its own pod identity and [Kubernetes impersonation](https://kubernetes.io/docs/reference/access-authn-authz/authentication/#user-impersonation) to act as a target service account. No tokens are stored in Infisical — you only provide a service account name and namespace.
## How It Works
-Kubernetes access in Infisical PAM uses an Infisical Gateway to securely proxy connections to your Kubernetes API server. When a user requests access, Infisical generates a temporary kubeconfig that routes traffic through the Gateway, enabling secure access without exposing your cluster directly.
+### Service Account Token
+
+When using a service account token, the Gateway forwards kubectl requests to the Kubernetes API server using the provided token.
```mermaid
sequenceDiagram
@@ -31,15 +38,46 @@ sequenceDiagram
CLI-->>User: kubectl output
```
+### Gateway (Impersonation)
+
+When using Gateway auth, the Gateway authenticates as itself using its own pod service account, then tells the Kubernetes API to treat the request as if it came from the target service account.
+
+```mermaid
+sequenceDiagram
+ participant User
+ participant CLI as Infisical CLI
+ participant Infisical
+ participant Gateway as Infisical Gateway
+ participant K8s as Kubernetes API Server
+
+ User->>CLI: Request Kubernetes access
+ CLI->>Infisical: Authenticate & request session
+ Infisical-->>CLI: Session credentials & Gateway info
+ CLI->>CLI: Start local proxy
+ CLI->>Gateway: Establish secure tunnel
+ Gateway->>Infisical: Fetch session credentials (SA name + namespace)
+ User->>CLI: kubectl commands
+ CLI->>Gateway: Proxy kubectl requests
+ Gateway->>K8s: Forward with own token + Impersonate-User header
+ K8s->>K8s: Verify impersonation permission, apply target SA's RBAC
+ K8s-->>Gateway: Response
+ Gateway-->>CLI: Return response
+ CLI-->>User: kubectl output
+```
+
+No tokens are stored in Infisical. The Gateway reads its own pod token from the filesystem (auto-mounted by Kubernetes) and auto-discovers the Kubernetes API server from environment variables.
+
### Key Concepts
1. **Gateway**: An Infisical Gateway deployed in your network that can reach the Kubernetes API server. The Gateway handles secure communication between users and your cluster.
2. **Service Account Token**: A Kubernetes service account token that grants access to the cluster. This token is stored securely in Infisical and used by the Gateway to authenticate with the Kubernetes API.
-3. **Local Proxy**: The Infisical CLI starts a local proxy on your machine that intercepts kubectl commands and routes them securely through the Gateway to your cluster.
+3. **Impersonation**: A Kubernetes feature where one identity (the Gateway) can act on behalf of another (the target service account). The Gateway authenticates as itself and adds `Impersonate-User` headers. Kubernetes checks if the Gateway has permission to impersonate the target, then applies the target's RBAC rules.
+
+4. **Local Proxy**: The Infisical CLI starts a local proxy on your machine that intercepts kubectl commands and routes them securely through the Gateway to your cluster.
-4. **Session Tracking**: All access sessions are logged, including when the session was created, who accessed the cluster, session duration, and when it ended.
+5. **Session Tracking**: All access sessions are logged, including when the session was created, who accessed the cluster, session duration, and when it ended.
### Session Tracking
@@ -59,11 +97,13 @@ Infisical tracks:
Before configuring Kubernetes access in Infisical PAM, you need:
1. **Infisical Gateway** - A Gateway deployed in your network with access to the Kubernetes API server
-2. **Service Account** - A Kubernetes service account with appropriate RBAC permissions
-3. **Infisical CLI** - The Infisical CLI installed on user machines
+2. **Infisical CLI** - The Infisical CLI installed on user machines
+3. Depending on your auth method:
+ - **Service Account Token**: A Kubernetes service account with appropriate RBAC permissions and a static token
+ - **Gateway**: The Gateway must be deployed **inside the Kubernetes cluster** as a pod, with a ClusterRole that allows impersonation of target service accounts
<Warning>
- **Gateway Required**: Unlike AWS Console access, Kubernetes access requires an Infisical Gateway to be deployed and registered with your Infisical instance. The Gateway must have network connectivity to your Kubernetes API server.
+ **Gateway Required**: Kubernetes access requires an Infisical Gateway to be deployed and registered with your Infisical instance. For Gateway auth, the Gateway must be running as a pod inside the cluster.
</Warning>
## Create the PAM Resource
@@ -79,90 +119,186 @@ The PAM Resource represents the connection between Infisical and your Kubernetes
1. Navigate to your PAM project and go to the **Resources** tab
2. Click **Add Resource** and select **Kubernetes**
3. Enter a name for the resource (e.g., `production-k8s`, `staging-cluster`)
- 4. Enter the **Kubernetes API Server URL** - the URL to your Kubernetes API endpoint (e.g.`https://kubernetes.example.com:6443`)
+ 4. Enter the **Kubernetes API Server URL** - the URL to your Kubernetes API endpoint (e.g.`https://kubernetes.example.com:6443`). If using Gateway auth with an in-cluster gateway, use `https://kubernetes.default.svc.cluster.local`.
5. Select the **Gateway** that has access to this cluster
6. Configure SSL verification options if needed
<Note>
- **SSL Verification**: You may need to disable SSL verification if your Kubernetes API server uses a self-signed certificate or if the certificate's hostname doesn't match the URL you're using to access it.
+ **SSL Verification**: You may need to disable SSL verification if your Kubernetes API server uses a self-signed certificate or an in-cluster CA. For Gateway auth with `https://kubernetes.default.svc.cluster.local`, disable SSL verification here — the Gateway will use strict TLS with the in-cluster CA certificate during sessions.
</Note>
</Step>
</Steps>
-## Create a Service Account
-
-Infisical PAM currently supports service account token authentication for Kubernetes. You'll need to create a service account with appropriate permissions in your cluster.
-
-<Steps>
- <Step title="Create the Service Account YAML">
- Create a file named `sa.yaml` with the following content:
-
- ```yaml sa.yaml
- apiVersion: v1
- kind: ServiceAccount
- metadata:
- name: infisical-pam-sa
- namespace: kube-system
- ---
- # Bind the ServiceAccount to the desired ClusterRole
- # This example uses cluster-admin - adjust based on your needs
- apiVersion: rbac.authorization.k8s.io/v1
- kind: ClusterRoleBinding
- metadata:
- name: infisical-pam-binding
- subjects:
- - kind: ServiceAccount
- name: infisical-pam-sa
- namespace: kube-system
- roleRef:
- kind: ClusterRole
- name: cluster-admin # Change this to a more restrictive role as needed
- apiGroup: rbac.authorization.k8s.io
- ---
- # Create a static, non-expiring token for the ServiceAccount
- apiVersion: v1
- kind: Secret
- metadata:
- name: infisical-pam-sa-token
- namespace: kube-system
- annotations:
- kubernetes.io/service-account.name: infisical-pam-sa
- type: kubernetes.io/service-account-token
- ```
-
- <Warning>
- **Security Best Practice**: The example above uses `cluster-admin` for simplicity. In production environments, you should create custom ClusterRoles or Roles with the minimum permissions required for each use case.
- </Warning>
- </Step>
-
- <Step title="Apply the Service Account">
- Apply the configuration to your cluster:
-
- ```bash
- kubectl apply -f sa.yaml
- ```
-
- This creates:
- - A ServiceAccount named `infisical-pam-sa` in the `kube-system` namespace
- - A ClusterRoleBinding that grants the service account its permissions
- - A Secret containing a static, non-expiring token for the service account
- </Step>
-
- <Step title="Retrieve the Service Account Token">
- Get the service account token that you'll use when creating the PAM account:
-
- ```bash
- kubectl -n kube-system get secret infisical-pam-sa-token -o jsonpath='{.data.token}' | base64 -d
- ```
-
- Copy this token - you'll need it in the next step.
- </Step>
-</Steps>
+## Set Up Authentication
+
+Choose one of the two authentication methods below based on your setup.
+
+<Tabs>
+ <Tab title="Service Account Token">
+ Use this method when you have a static service account token, or when the Gateway is not running inside the Kubernetes cluster.
+
+ ### Create a Service Account
+
+ <Steps>
+ <Step title="Create the Service Account YAML">
+ Create a file named `sa.yaml` with the following content:
+
+ ```yaml sa.yaml
+ apiVersion: v1
+ kind: ServiceAccount
+ metadata:
+ name: infisical-pam-sa
+ namespace: kube-system
+ ---
+ # Bind the ServiceAccount to the desired ClusterRole
+ # This example uses cluster-admin - adjust based on your needs
+ apiVersion: rbac.authorization.k8s.io/v1
+ kind: ClusterRoleBinding
+ metadata:
+ name: infisical-pam-binding
+ subjects:
+ - kind: ServiceAccount
+ name: infisical-pam-sa
+ namespace: kube-system
+ roleRef:
+ kind: ClusterRole
+ name: cluster-admin # Change this to a more restrictive role as needed
+ apiGroup: rbac.authorization.k8s.io
+ ---
+ # Create a static, non-expiring token for the ServiceAccount
+ apiVersion: v1
+ kind: Secret
+ metadata:
+ name: infisical-pam-sa-token
+ namespace: kube-system
+ annotations:
+ kubernetes.io/service-account.name: infisical-pam-sa
+ type: kubernetes.io/service-account-token
+ ```
+
+ <Warning>
+ **Security Best Practice**: The example above uses `cluster-admin` for simplicity. In production environments, you should create custom ClusterRoles or Roles with the minimum permissions required for each use case.
+ </Warning>
+ </Step>
+
+ <Step title="Apply the Service Account">
+ Apply the configuration to your cluster:
+
+ ```bash
+ kubectl apply -f sa.yaml
+ ```
+
+ This creates:
+ - A ServiceAccount named `infisical-pam-sa` in the `kube-system` namespace
+ - A ClusterRoleBinding that grants the service account its permissions
+ - A Secret containing a static, non-expiring token for the service account
+ </Step>
+
+ <Step title="Retrieve the Service Account Token">
+ Get the service account token that you'll use when creating the PAM account:
+
+ ```bash
+ kubectl -n kube-system get secret infisical-pam-sa-token -o jsonpath='{.data.token}' | base64 -d
+ ```
+
+ Copy this token - you'll need it in the next step.
+ </Step>
+ </Steps>
+ </Tab>
+
+ <Tab title="Gateway (Impersonation)">
+ Use this method when the Gateway is deployed **inside the Kubernetes cluster** as a pod. No tokens need to be created or stored — the Gateway uses its own pod identity to impersonate target service accounts.
+
+ <Info>
+ When creating the resource in the step above, use `https://kubernetes.default.svc.cluster.local` as the URL and **disable SSL verification**. The Gateway handles TLS with the correct in-cluster CA automatically during sessions.
+ </Info>
+
+ ### Set Up Impersonation Permissions
+
+ The Gateway's pod service account needs a ClusterRole that allows it to impersonate the target service accounts.
+
+ <Steps>
+ <Step title="Create the Impersonation ClusterRole">
+ Create a file named `gateway-impersonation.yaml`:
+
+ ```yaml gateway-impersonation.yaml
+ apiVersion: rbac.authorization.k8s.io/v1
+ kind: ClusterRole
+ metadata:
+ name: infisical-gateway-impersonator
+ rules:
+ - apiGroups: [""]
+ resources: ["serviceaccounts"]
+ verbs: ["impersonate"]
+ resourceNames:
+ - "deploy-bot" # Add each SA the gateway should be able to impersonate
+ - "ci-runner"
+ - apiGroups: [""]
+ resources: ["groups"]
+ verbs: ["impersonate"]
+ resourceNames:
+ - "system:serviceaccounts"
+ - "system:serviceaccounts:default" # Match the namespace(s) of the target SAs
+ - "system:authenticated"
+ ---
+ apiVersion: rbac.authorization.k8s.io/v1
+ kind: ClusterRoleBinding
+ metadata:
+ name: infisical-gateway-impersonator-binding
+ subjects:
+ - kind: ServiceAccount
+ name: <gateway-pod-service-account> # The Gateway pod's own service account
+ namespace: <gateway-namespace>
+ roleRef:
+ kind: ClusterRole
+ name: infisical-gateway-impersonator
+ apiGroup: rbac.authorization.k8s.io
+ ```
+
+ <Note>
+ **Scoped by `resourceNames`**: The `resourceNames` field limits which service accounts the Gateway can impersonate. If someone creates a PAM account pointing at a service account not in this list, the session will fail with a 403 from Kubernetes. This is how you control which accounts are accessible through Infisical.
+ </Note>
+ </Step>
+
+ <Step title="Apply the ClusterRole">
+ ```bash
+ kubectl apply -f gateway-impersonation.yaml
+ ```
+ </Step>
+
+ <Step title="Ensure target service accounts exist">
+ The service accounts you want to impersonate must already exist in the cluster with their own RBAC permissions. For example:
+
+ ```yaml
+ apiVersion: v1
+ kind: ServiceAccount
+ metadata:
+ name: deploy-bot
+ namespace: default
+ ---
+ apiVersion: rbac.authorization.k8s.io/v1
+ kind: ClusterRoleBinding
+ metadata:
+ name: deploy-bot-binding
+ subjects:
+ - kind: ServiceAccount
+ name: deploy-bot
+ namespace: default
+ roleRef:
+ kind: ClusterRole
+ name: view # Or whatever permissions this SA should have
+ apiGroup: rbac.authorization.k8s.io
+ ```
+
+ The target SA's own RBAC rules determine what the user can do during the session.
+ </Step>
+ </Steps>
+ </Tab>
+</Tabs>
## Create PAM Accounts
-Once you have configured the PAM resource, you'll need to configure a PAM account for your Kubernetes resource.
-A PAM Account represents a specific service account that users can request access to. You can create multiple accounts per resource, each with different permission levels.
+Once you have configured the PAM resource and set up authentication, create a PAM account to grant access.
<Steps>
<Step title="Navigate to Resource">
@@ -173,8 +309,11 @@ A PAM Account represents a specific service account that users can request acces
Click **Add Account**.
</Step>
- <Step title="Fill in Account Details">
- Fill in the account details and paste the service account token you retrieved earlier.
+ <Step title="Select Authentication Method">
+ Choose the authentication method:
+
+ - **Service Account Token** — paste the service account token you retrieved earlier.
+ - **Gateway** — enter the **Service Account Name** and **Namespace** of the Kubernetes service account you want to impersonate. No token is needed.
</Step>
</Steps>
@@ -185,7 +324,7 @@ Once your resource and accounts are configured, users can request access through
<Steps>
<Step title="Get the Access Command">
1. Navigate to the **Resources** tab in your PAM project and open the Kubernetes resource
- 2. In the resource’s accounts section, find the account you want to access
+ 2. In the resource's accounts section, find the account you want to access
3. Click the **Access** button for that account
4. Copy the provided CLI command
@@ -222,3 +361,36 @@ Once your resource and accounts are configured, users can request access through
You can view session logs in the **Sessions** page of your PAM project.
</Step>
</Steps>
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="Which auth method should I use?">
+ - Use **Gateway** if your Gateway is deployed as a pod inside the Kubernetes cluster. No tokens to create or manage — just enter a service account name and namespace.
+ - Use **Service Account Token** if your Gateway runs outside the cluster (e.g., on a separate VM) and only has network access to the Kubernetes API. You'll need to create a service account token and paste it into Infisical.
+ </Accordion>
+
+ <Accordion title="Do I still need to enter a Kubernetes API URL when using Gateway auth?">
+ Yes. The resource URL is still required even when using Gateway auth. For in-cluster gateways, enter `https://kubernetes.default.svc.cluster.local`. The Gateway auto-discovers the actual Kubernetes API address from its pod environment variables, so this URL isn't used for the connection itself — but the field is still required when creating the resource.
+ </Accordion>
+
+ <Accordion title="How does the Gateway find the Kubernetes API server?">
+ When using Gateway auth, the Gateway reads the `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT_HTTPS` environment variables that Kubernetes automatically sets in every pod. It ignores the URL configured on the resource and connects directly to the in-cluster API server.
+ </Accordion>
+
+ <Accordion title="Do I need to configure SSL certificates for Gateway auth?">
+ Just disable SSL verification on the resource — the Gateway handles TLS automatically during sessions using the in-cluster CA certificate mounted in its pod. If the CA certificate is missing or invalid, the session will fail rather than falling back to an insecure connection.
+ </Accordion>
+
+ <Accordion title="What happens if the Gateway can't impersonate a service account?">
+ The Kubernetes API server returns a 403 Forbidden error. Kubernetes itself enforces impersonation permissions — if the Gateway's ClusterRole doesn't include the target service account in its `resourceNames` list, the session fails. You don't need to configure any allowlist in Infisical; just update the ClusterRole in your cluster.
+ </Accordion>
+
+ <Accordion title="Can I use both auth methods on the same Kubernetes resource?">
+ Yes. The auth method is configured per account, not per resource. You can have some accounts using Service Account Token and others using Gateway on the same Kubernetes resource.
+ </Accordion>
+
+ <Accordion title="Does the Gateway need to run inside the Kubernetes cluster?">
+ For Gateway auth, yes — the Gateway must be deployed as a pod inside the cluster so it can read its own service account token and reach the Kubernetes API. For Service Account Token auth, the Gateway just needs network access to the Kubernetes API server and can run anywhere.
+ </Accordion>
+</AccordionGroup>
diff --git a/frontend/src/hooks/api/pam/types/kubernetes-resource.ts b/frontend/src/hooks/api/pam/types/kubernetes-resource.ts
index b7e1501d5f..a8aa34b851 100644
--- a/frontend/src/hooks/api/pam/types/kubernetes-resource.ts
+++ b/frontend/src/hooks/api/pam/types/kubernetes-resource.ts
@@ -3,7 +3,8 @@ import { TBasePamAccount } from "./base-account";
import { TBasePamResource } from "./base-resource";
export enum KubernetesAuthMethod {
- ServiceAccountToken = "service-account-token"
+ ServiceAccountToken = "service-account-token",
+ GatewayKubernetesAuth = "gateway-kubernetes-auth"
}
export type TKubernetesConnectionDetails = {
@@ -17,7 +18,15 @@ export type TKubernetesServiceAccountTokenCredentials = {
serviceAccountToken: string;
};
-export type TKubernetesCredentials = TKubernetesServiceAccountTokenCredentials;
+export type TKubernetesGatewayAuthCredentials = {
+ authMethod: KubernetesAuthMethod.GatewayKubernetesAuth;
+ namespace: string;
+ serviceAccountName: string;
+};
+
+export type TKubernetesCredentials =
+ | TKubernetesServiceAccountTokenCredentials
+ | TKubernetesGatewayAuthCredentials;
// Resources
export type TKubernetesResource = TBasePamResource & {
diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx
index c6f96a9ac3..d426c0ec28 100644
--- a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx
+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx
@@ -14,8 +14,10 @@ import { ProjectPermissionSub } from "@app/context";
import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";
import { useTimedReset } from "@app/hooks";
import {
+ KubernetesAuthMethod,
PamResourceType,
TActiveDirectoryAccount,
+ TKubernetesCredentials,
TPamAccount,
TWindowsAccount
} from "@app/hooks/api/pam";
@@ -107,6 +109,20 @@ const ActiveDirectoryCredentialsContent = ({ account }: { account: TActiveDirect
);
};
+const KubernetesCredentialsContent = ({ credentials }: { credentials: TKubernetesCredentials }) => {
+ if (credentials.authMethod === KubernetesAuthMethod.GatewayKubernetesAuth) {
+ return (
+ <>
+ <CopyableField label="Namespace" value={credentials.namespace} />
+ <CopyableField label="Service Account Name" value={credentials.serviceAccountName} />
+ </>
+ );
+ }
+
+ // ServiceAccountToken: no non-sensitive fields (token is behind the reveal gate)
+ return null;
+};
+
const CredentialsContent = ({ account }: { account: TPamAccount }) => {
const { resourceType } = account.resource;
@@ -125,6 +141,10 @@ const CredentialsContent = ({ account }: { account: TPamAccount }) => {
return <WindowsCredentialsContent account={account as TWindowsAccount} />;
case PamResourceType.ActiveDirectory:
return <ActiveDirectoryCredentialsContent account={account as TActiveDirectoryAccount} />;
+ case PamResourceType.Kubernetes:
+ return (
+ <KubernetesCredentialsContent credentials={account.credentials as TKubernetesCredentials} />
+ );
default:
return null;
}
@@ -232,6 +252,13 @@ const getSensitiveFieldDefs = (account: TPamAccount): SensitiveFieldDef[] => {
return [];
}
+ case PamResourceType.Kubernetes: {
+ const { authMethod } = account.credentials as TKubernetesCredentials;
+ if (authMethod === KubernetesAuthMethod.ServiceAccountToken)
+ return [{ key: "serviceAccountToken", label: "Service Account Token", multiline: true }];
+ return [];
+ }
+
default:
return [];
}
@@ -277,11 +304,7 @@ const RevealedCredentials = ({
export const PamAccountCredentialsSection = ({ account, onEdit }: Props) => {
const { state, startReveal, reset } = useCredentialsReveal(account.id);
- if (
- Object.keys(account.credentials).length <= 0 ||
- [PamResourceType.Kubernetes].includes(account.resource.resourceType)
- )
- return null;
+ if (Object.keys(account.credentials).length <= 0) return null;
const sensitiveFieldDefs = getSensitiveFieldDefs(account);
const hasSensitiveFields = sensitiveFieldDefs.length > 0;
diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx
index 6fee3f0890..12334f219f 100644
--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx
+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/KubernetesAccountForm.tsx
@@ -1,8 +1,8 @@
-import { Controller, FormProvider, useForm, useFormContext } from "react-hook-form";
+import { Controller, FormProvider, useForm, useFormContext, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
-import { FormControl, TextArea } from "@app/components/v2";
+import { FormControl, Input, Select, SelectItem, TextArea } from "@app/components/v2";
import { Button, SheetFooter } from "@app/components/v3";
import { KubernetesAuthMethod, PamResourceType, TKubernetesAccount } from "@app/hooks/api/pam";
import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants";
@@ -13,6 +13,7 @@ import {
genericAccountFieldsSchema
} from "./GenericAccountFields";
import { MetadataFields } from "./MetadataFields";
+import { RequireMfaField } from "./RequireMfaField";
type Props = {
account?: TKubernetesAccount;
@@ -27,41 +28,140 @@ const KubernetesServiceAccountTokenCredentialsSchema = z.object({
serviceAccountToken: z.string().trim().min(1, "Service account token is required")
});
+const KubernetesGatewayAuthCredentialsSchema = z.object({
+ authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
+ namespace: z.string().trim().min(1, "Namespace is required").max(63),
+ serviceAccountName: z.string().trim().min(1, "Service account name is required").max(253)
+});
+
const formSchema = genericAccountFieldsSchema.extend({
- credentials: KubernetesServiceAccountTokenCredentialsSchema
+ credentials: z.discriminatedUnion("authMethod", [
+ KubernetesServiceAccountTokenCredentialsSchema,
+ KubernetesGatewayAuthCredentialsSchema
+ ]),
+ requireMfa: z.boolean().nullable().optional()
});
type FormData = z.infer<typeof formSchema>;
-const KubernetesAccountFields = ({ isUpdate }: { isUpdate: boolean }) => {
- const { control } = useFormContext<FormData>();
+const KubernetesAccountFields = ({
+ isUpdate,
+ originalAuthMethod
+}: {
+ isUpdate: boolean;
+ originalAuthMethod?: KubernetesAuthMethod;
+}) => {
+ const { control, setValue } = useFormContext<FormData>();
+
+ const authMethod =
+ useWatch({ control, name: "credentials.authMethod" }) ||
+ KubernetesAuthMethod.ServiceAccountToken;
return (
<div className="mb-4 rounded-sm border border-mineshaft-600 bg-mineshaft-700/70 p-3">
<Controller
- name="credentials.serviceAccountToken"
+ name="credentials.authMethod"
control={control}
- render={({ field, fieldState: { error } }) => (
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
- className="mb-0"
- errorText={error?.message}
+ className="mb-3"
isError={Boolean(error?.message)}
- label="Service Account Token"
- helperText="The bearer token for the service account"
+ errorText={error?.message}
+ label="Authentication Method"
>
- <TextArea
- {...field}
- value={field.value === UNCHANGED_PASSWORD_SENTINEL ? "" : field.value || ""}
- className="min-h-32 resize-y font-mono text-xs"
- placeholder={
- isUpdate && field.value === UNCHANGED_PASSWORD_SENTINEL
- ? "Token unchanged - click to update"
- : "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
- }
- />
+ <Select
+ value={value || KubernetesAuthMethod.ServiceAccountToken}
+ onValueChange={(newAuthMethod) => {
+ onChange(newAuthMethod);
+ // Clear credentials from other auth methods, restoring sentinel in update mode
+ setValue(
+ "credentials.serviceAccountToken" as never,
+ (newAuthMethod === KubernetesAuthMethod.ServiceAccountToken &&
+ isUpdate &&
+ originalAuthMethod === KubernetesAuthMethod.ServiceAccountToken
+ ? UNCHANGED_PASSWORD_SENTINEL
+ : undefined) as never,
+ { shouldDirty: true }
+ );
+ setValue("credentials.namespace" as never, undefined as never, {
+ shouldDirty: true
+ });
+ setValue("credentials.serviceAccountName" as never, undefined as never, {
+ shouldDirty: true
+ });
+ }}
+ className="w-full border border-mineshaft-500"
+ >
+ <SelectItem value={KubernetesAuthMethod.ServiceAccountToken}>
+ Service Account Token
+ </SelectItem>
+ <SelectItem value={KubernetesAuthMethod.GatewayKubernetesAuth}>Gateway</SelectItem>
+ </Select>
</FormControl>
)}
/>
+
+ {authMethod === KubernetesAuthMethod.ServiceAccountToken && (
+ <Controller
+ name="credentials.serviceAccountToken"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="mb-0"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Service Account Token"
+ helperText="The bearer token for the service account"
+ >
+ <TextArea
+ {...field}
+ value={field.value === UNCHANGED_PASSWORD_SENTINEL ? "" : field.value || ""}
+ className="min-h-32 resize-y font-mono text-xs"
+ placeholder={
+ isUpdate && field.value === UNCHANGED_PASSWORD_SENTINEL
+ ? "Token unchanged - click to update"
+ : "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
+ }
+ />
+ </FormControl>
+ )}
+ />
+ )}
+
+ {authMethod === KubernetesAuthMethod.GatewayKubernetesAuth && (
+ <>
+ <Controller
+ name="credentials.serviceAccountName"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="mb-3"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Service Account Name"
+ helperText="Name of the Kubernetes service account to impersonate"
+ >
+ <Input {...field} placeholder="deploy-bot" autoComplete="off" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.namespace"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className="mb-0"
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Namespace"
+ helperText="Kubernetes namespace where the service account lives"
+ >
+ <Input {...field} placeholder="default" autoComplete="off" />
+ </FormControl>
+ )}
+ />
+ </>
+ )}
</div>
);
};
@@ -69,19 +169,31 @@ const KubernetesAccountFields = ({ isUpdate }: { isUpdate: boolean }) => {
export const KubernetesAccountForm = ({ account, onSubmit, closeSheet }: Props) => {
const isUpdate = Boolean(account);
+ const getDefaultCredentials = () => {
+ if (!account) return undefined;
+
+ if (account.credentials.authMethod === KubernetesAuthMethod.ServiceAccountToken) {
+ return {
+ ...account.credentials,
+ serviceAccountToken: UNCHANGED_PASSWORD_SENTINEL
+ };
+ }
+
+ // Gateway auth has no sensitive fields
+ return account.credentials;
+ };
+
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: account
? {
...account,
- credentials: {
- ...account.credentials,
- serviceAccountToken: UNCHANGED_PASSWORD_SENTINEL
- }
+ credentials: getDefaultCredentials()
}
: {
name: "",
description: "",
+ requireMfa: false,
credentials: {
authMethod: KubernetesAuthMethod.ServiceAccountToken,
serviceAccountToken: ""
@@ -104,8 +216,12 @@ export const KubernetesAccountForm = ({ account, onSubmit, closeSheet }: Props)
>
<div className="flex min-h-0 flex-1 shrink flex-col gap-4 overflow-y-auto p-4 pb-8">
<GenericAccountFields />
- <KubernetesAccountFields isUpdate={isUpdate} />
+ <KubernetesAccountFields
+ isUpdate={isUpdate}
+ originalAuthMethod={account?.credentials.authMethod}
+ />
<AccountPolicyField />
+ <RequireMfaField />
<MetadataFields />
</div>
<SheetFooter className="shrink-0 border-t">
diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx
index 6436be1265..934dcaf680 100644
--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx
+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx
@@ -26,10 +26,22 @@ const KubernetesServiceAccountTokenCredentialsSchema = z.object({
serviceAccountToken: z.string().trim().max(10000)
});
+const KubernetesGatewayAuthCredentialsSchema = z.object({
+ authMethod: z.literal(KubernetesAuthMethod.GatewayKubernetesAuth),
+ namespace: z.string().trim().min(1).max(63),
+ serviceAccountName: z.string().trim().min(1).max(253)
+});
+
const formSchema = genericResourceFieldsSchema.extend({
resourceType: z.literal(PamResourceType.Kubernetes),
connectionDetails: KubernetesConnectionDetailsSchema,
- rotationAccountCredentials: KubernetesServiceAccountTokenCredentialsSchema.nullable().optional()
+ rotationAccountCredentials: z
+ .discriminatedUnion("authMethod", [
+ KubernetesServiceAccountTokenCredentialsSchema,
+ KubernetesGatewayAuthCredentialsSchema
+ ])
+ .nullable()
+ .optional()
});
type FormData = z.infer<typeof formSchema>;