> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formal.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Kubernetes

> How to connect to a Kubernetes Resource using the Formal Connector

Formal streamlines access and control for any Kubernetes clusters by providing:

* Single Sign-On (SSO) integration with providers like Okta
* Granular role-based access controls with MFA support
* Session recording for compliance
* Automatic cluster discovery (for EKS)

## Requirements

To connect to a Kubernetes cluster through the Connector, you need the following:

* The Formal Endpoint running and authenticated. You can find more information on how to achieve this in [the documentation of the Formal Endpoint](https://docs.formal.ai/docs/guides/client-apps/desktop-app.md).
* At least one Kubernetes cluster linked to the Formal Connector as a Resource, with its Native User set. For AWS EKS clusters, set the Resource name to the cluster name.

The Formal Endpoint will automatically update your local kubeconfig file and change the current context.

## Configuration

### Resource

When creating a Kubernetes resource, use the Kubernetes API endpoint URL with port 443 as the target port.

The Connector uses the resource name to identify which cluster to target when a user tries to access a cluster.

How the Connector finds the upstream cluster depends on the Native User:

* **AWS IAM** and **AWS IAM Role** look up the EKS cluster by the Resource name.
* **Kubeconfig** and **Kubeconfig Path** select the kubeconfig context whose cluster `server` URL matches the Resource hostname and port. Context names are ignored, and exactly one context must match.
* **Azure IAM** and **GCP IAM** connect to the Resource hostname and port directly.

For AWS EKS clusters, the Kubernetes Resource name **must match exactly** the
EKS cluster name.

To remove the `X-Forwarded-For` and `X-Real-IP` headers from requests the Connector sends to the cluster, turn off **Forward client IP** in the Resource's settings, or set `forward_client_ip_headers` to `false` on the `formal_resource` in Terraform.

### Native Users

The Connector supports the following Native User credential types for Kubernetes:

1. **AWS IAM** uses the Connector's ambient AWS identity.
2. **AWS IAM Role** assumes the specified AWS role ARN.
3. **Azure IAM** uses the Connector's ambient Microsoft Entra identity.
4. **GCP IAM** uses the Connector's ambient Google identity.
5. **Kubeconfig Path** reads a kubeconfig file from the Connector.
6. **Kubeconfig** uses an inline kubeconfig YAML document.

#### Terraform

For Kubernetes-specific credentials, configure one of the following Native
Users. Kubeconfig paths and documents can be literal values or references to
environment variables available to the Connector.

##### Kubeconfig Path

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "kubeconfig_path" {
  resource_id = formal_resource.cluster.id
  label       = "kubeconfig-path"

  kubernetes_path {
    kubeconfig_path {
      literal = "/etc/formal/kubeconfig"
    }
  }
}
```

##### Kubeconfig

```hcl theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
resource "formal_native_user_v3" "kubeconfig_inline" {
  resource_id = formal_resource.cluster.id
  label       = "kubeconfig-inline"

  kubernetes_inline {
    kubeconfig {
      environment_variable = "KUBECONFIG_YAML"
    }
  }
}
```

See
[Select a default Native User](https://docs.formal.ai/docs/guides/core-concepts/resources/native-users.md#select-a-default-native-user)
for selection examples.

#### AWS IAM permissions

When using **AWS IAM** or **AWS IAM Role**, the Connector needs the following AWS
permissions to fetch the upstream cluster configuration:

```json theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["eks:DescribeCluster", "sts:GetCallerIdentity"],
      "Resource": "*"
    }
  ]
}
```

If the Connector is deployed in an AWS EKS cluster, grant these permissions to the Connector pod's IAM role with [EKS Pod Identity](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html):

1. Create an IAM role trusted by `pods.eks.amazonaws.com`
2. Attach the AWS IAM policy above to that role
3. Associate the role with the Connector service account via EKS Pod Identity
4. Use that service account on the Connector pod

These steps are detailed in the [AWS documentation](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-association.html) and demonstrated in our [example Terraform deployment](https://github.com/formalco/terraform-provider-formal/tree/main/examples/deployments/aws/eks-kubernetes-connector).

#### Upstream Kubernetes permissions

When connected to the target Kubernetes cluster, the Connector inherits the permissions defined by its token's username and groups (e.g. the matching *ClusterRoleBinding* and *ClusterRole*).

If the credentials have limited permissions, the Formal app will show the access logs correctly but users will see errors when attempting `kubectl` commands. For example:

```console theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
$ kubectl get pods
E0526 10:28:09.839098   25809 memcache.go:265] couldn't get current server API group list: the server has asked for the
client to provide credentials
E0526 10:28:10.715348   25809 memcache.go:265] couldn't get current server API group list: the server has asked for the
client to provide credentials
E0526 10:28:11.805740   25809 memcache.go:265] couldn't get current server API group list: the server has asked for the
client to provide credentials
E0526 10:28:12.912758   25809 memcache.go:265] couldn't get current server API group list: the server has asked for the
client to provide credentials
E0526 10:28:13.788519   25809 memcache.go:265] couldn't get current server API group list: the server has asked for the
client to provide credentials
error: You must be logged in to the server (the server has asked for the client to provide credentials)
```

On the opposite, if the permissions are set correctly, users will be able to run `kubectl` commands according to the Connector identity on the Kubernetes cluster. For example, for a *ClusterRole* that allows reading pods but not nodes:

```console theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
$ kubectl get pods
No resources found in default namespace.
$ kubectl get nodes
Error from server (Forbidden): nodes is forbidden: User "arn:aws:sts::123456789012:assumed-role/formal-connector-20240101000000000000000001/1234567890123456789" cannot list resource "nodes" in API group "" at the cluster scope
```

As seen in the last error of the previous example, the Connector identity is used for all commands. If you want the end user identity to propagate, you should use [impersonation](#impersonation) (recommended) or synchronize end users and native users.

#### Upstream Kubernetes permissions (AWS EKS)

If your target Kubernetes resource is an AWS EKS cluster, you need to:

* Allow your Connector role to connect to the EKS cluster with an [Access Entry Configuration](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html)
* Define its permissions with an [Access Entry Policy Association](https://docs.aws.amazon.com/eks/latest/userguide/access-policies.html) that links your previously created Pod Identity IAM role with the cluster access policy of your choice (e.g. `arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy`).

#### Example Terraform deployment

For a complete example of deploying the Formal Connector in an EKS cluster that controls access to that cluster, see our [example Terraform configuration](https://github.com/formalco/terraform-provider-formal/tree/main/examples/deployments/aws/eks-kubernetes-connector). This example demonstrates:

* Deploying the Formal Connector on AWS EKS
* Setting up AWS IAM roles and policies for EKS API access
* Configuring the Kubernetes cluster access permissions for the Connector

## Impersonation

User impersonation provides two key benefits:

1. **Improved audit logs**: Actions in Kubernetes logs are attributed to individual users rather than showing all Formal-mediated actions under a single service account.
2. **Granular access control**: Users' permissions are restricted to match what they would have when connecting directly to the cluster.

For more information about user impersonation, refer to the [Kubernetes documentation](https://kubernetes.io/docs/reference/access-authn-authz/authentication/#user-impersonation).

### Kubernetes RBAC

To impersonate users, the Connector's Kubernetes credential needs the `impersonate` verb on `users` and `groups`. The API server checks every impersonated identity against that permission. Only allow the identities your Formal policies use:

* **Groups:** list the groups your `impersonate` policies set in `resourceNames`. Without `resourceNames`, the credential can impersonate any group, including `system:masters`, which has full cluster-admin access.
* **Users:** if your policies impersonate a fixed set of users, list them in `resourceNames` too. Policies that impersonate `input.user.username` can't be listed in advance, so leave `users` unrestricted. An impersonated user only gets the permissions bound to that username, the groups the policy sets, and `system:authenticated`.
* **`cluster-admin`:** don't bind the Connector's credential to `cluster-admin`, because it can impersonate any user or group.

Here is an example *ClusterRole* and *ClusterRoleBinding* that lets a Connector impersonate end users into two groups:

> [tab] ClusterRole
>
> ```yaml ClusterRole theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> apiVersion: rbac.authorization.k8s.io/v1
> kind: ClusterRole
> metadata:
>   annotations:
>     rbac.authorization.kubernetes.io/autoupdate: "true"
>   labels:
>   name: impersonate
> rules:
>   - apiGroups:
>       - ""
>     resources:
>       - "*"
>     verbs:
>       - get
>       - list
>       - watch
>   - apiGroups:
>       - extensions
>     resources:
>       - "*"
>     verbs:
>       - get
>       - list
>       - watch
>   - apiGroups:
>       - apps
>     resources:
>       - "*"
>     verbs:
>       - get
>       - list
>       - watch
>   - apiGroups: # Impersonate end users
>       - ""
>     resources:
>       - users
>     verbs:
>       - impersonate
>   - apiGroups: # Only the groups your impersonate policies set
>       - ""
>     resources:
>       - groups
>     resourceNames:
>       - k8s-viewers
>       - k8s-editors
>     verbs:
>       - impersonate
>   - apiGroups:
>       - "authorization.k8s.io"
>     resources:
>       - selfsubjectaccessreviews
>     verbs:
>       - create
> ```

> [tab] ClusterRoleBinding
>
> ```yaml ClusterRoleBinding theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> apiVersion: rbac.authorization.k8s.io/v1
> kind: ClusterRoleBinding
> metadata:
>   name: formal
> subjects:
> - kind: Group
>   name: formal-connector # Name of the Connector group
>   apiGroup: rbac.authorization.k8s.io
> roleRef:
>   apiGroup: rbac.authorization.k8s.io
>   kind: ClusterRole
>   name: impersonate # Name of the ClusterRole you want the Connector to use
> ```

### Formal policy

The Connector decides whether to impersonate users based on policies.

This policy runs each request as the calling user, with the user's groups that are also in `kubernetes_groups`, instead of as the native user. The API server rejects the request if the policy sets a group the Connector's credential can't impersonate. Filter the groups to the same list as the `resourceNames` in your *ClusterRole*.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if
import future.keywords.in

kubernetes_groups := {"k8s-viewers", "k8s-editors"}

session := {
  "action": "impersonate",
  "user": input.user.username,
  "groups": [g | some g in input.user.groups; g in kubernetes_groups],
} if {
  input.datastore.technology == "kubernetes"
}
```

When using impersonation, the Formal Connector adds two headers to the request made:

* `Impersonate-User`: The user specified in the policy under user.
* `Impersonate-Group`: The list of groups in the policy under groups. If using RBAC, it should match the groups used in your Kubernetes cluster.

## Policy Evaluation

Formal supports the following policy evaluation stages for Kubernetes:

* **Session**: Evaluate and enforce policies on every Kubernetes API request. `input.kubernetes` describes that request.

## Kubernetes Input

The Connector populates the `input.kubernetes` object for policy evaluation. See the full reference in [Policy Evaluation](https://docs.formal.ai/docs/guides/policies/evaluation.md#kubernetes-resources).

| Field | Description | Example |
| - | - | - |
| `group` | API group (empty for core resources) | `apps` |
| `group_version` | API version | `v1` |
| `namespace` | Namespace (empty for cluster-scoped resources) | `default` |
| `kind` | Resource kind | `pods` |
| `name` | Resource name (empty for list/collection operations) | `my-pod` |
| `subresource` | Subresource | `exec` |
| `verb` | API verb, or lower-cased HTTP method for non-resource paths | `get`, `list`, `create` |

## Other policies

Additionally, you can apply access restrictions to Kubernetes Resources, similar to any other Resource. This includes the implementation of two additional filters, among others:

1. **Kind**: allow or block access to a specific Kubernetes Kind (e.g. secret)
2. **Namespace**: allow or block access to a specific Kubernetes Namespace

### MFA for `kubectl exec`

This policy requires users to use MFA to run `kubectl exec`.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

session := { "action": "mfa" } if {
  input.kubernetes.subresource == "exec"
}
```

### Block `kube-*` namespaces

The following policy blocks every query to the Connector for namespaces that start with `kube-`.

```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
package formal.v2

import future.keywords.if

session := { "action": "block", "type": "block_with_formal_message" } if {
  startswith(input.kubernetes.namespace, "kube-")
}
```

## Transparent Mode

The Formal Endpoint can intercept `kubectl` traffic in [Transparent Mode](https://docs.formal.ai/docs/guides/client-apps/transparent-mode.md) and forward it to the Connector.

### Network rule

Kubernetes requires `forward_to_connector: true`.

```cel theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
{
  "condition": {
    "pre_tcp": port == 443,
    "pre_tls": resource.technology == "kubernetes",
    "post_tls": resource.technology == "kubernetes"
  },
  "outputs": {
    "forward_to_connector": true
  }
}
```

### Configure `kubectl`

Do not point `kubectl` at the Connector hostname, because Transparent Mode bypasses Connector hostnames. Point `kubectl` at the cluster hostname instead.

Omit `certificate-authority-data` so `kubectl` trusts Formal's Local CA from the OS trust store, and replace any `exec` auth plugin with a placeholder token:

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
kubectl config set-cluster formal-cluster \
  --server=https://<CLUSTER_HOSTNAME>:443
kubectl config set-credentials formal-transparent --token=formal-transparent
kubectl config set-context formal-cluster \
  --cluster=formal-cluster \
  --user=formal-transparent
kubectl config use-context formal-cluster
```

**Verify:**

```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
formal transparent-proxy status
kubectl get ns
```

## Recordings

The Formal Connector records `kubectl exec` and `kubectl attach` sessions. Other requests, including `kubectl port-forward`, are logged but not recorded. The session recordings can be accessed and reviewed in the [Sessions application](https://docs.formal.ai/docs/guides/observability/sessions.md).

![](https://mintcdn.com/formal/z9GNtynV1YHUDYCN/assets/images/session_recording.png?fit=max\&auto=format\&n=z9GNtynV1YHUDYCN\&q=85\&s=03d5c312758e5adda1462681ff06e108)


## Related topics

- [Kubernetes Operator](https://docs.formal.ai/docs/changelog/kubernetes-operator.md)
- [Formal Kubernetes Operator](https://docs.formal.ai/docs/guides/core-concepts/kubernetes-operator/introduction.md)
- [Deploy the Kubernetes Operator](https://docs.formal.ai/docs/guides/core-concepts/kubernetes-operator/deployment.md)
- [Formal Endpoint for Kubernetes](https://docs.formal.ai/docs/guides/client-apps/kubernetes-egress.md)
- [Kubernetes Operator Custom Resources](https://docs.formal.ai/docs/guides/core-concepts/kubernetes-operator/custom-resources.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.