Kubernetes
Go Client
Impersonation
Programming Guide
API Authentication

How to make impersonate work with kubernetes go-client

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Kubernetes impersonation with the Go client is useful for admin tools, policy simulation, and delegated operations. It lets an authenticated caller request actions as another user or group, but only when RBAC explicitly grants impersonation rights. To make it work reliably, configure impersonation in rest.Config, grant minimal RBAC verbs, and verify behavior with authorization checks.

How Impersonation Works

Impersonation does not replace authentication. The real caller still authenticates first, then sends impersonation headers such as user and groups. The API server allows this only if caller permissions include impersonate on relevant resources.

In practical terms:

  1. Real identity authenticates.
  2. Request includes impersonation fields.
  3. API server validates impersonation permission.
  4. Authorization evaluates the impersonated identity.

A failure can happen in step three or step four, so debugging should test both.

Configure client-go Impersonation Fields

Set impersonation once on rest.Config before creating clientset.

go
1package main
2
3import (
4    "context"
5    "fmt"
6
7    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
8    "k8s.io/client-go/kubernetes"
9    "k8s.io/client-go/tools/clientcmd"
10)
11
12func main() {
13    cfg, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
14    if err != nil {
15        panic(err)
16    }
17
18    cfg.Impersonate.UserName = "[email protected]"
19    cfg.Impersonate.Groups = []string{"team-dev"}
20
21    cs, err := kubernetes.NewForConfig(cfg)
22    if err != nil {
23        panic(err)
24    }
25
26    pods, err := cs.CoreV1().Pods("default").List(context.Background(), metav1.ListOptions{})
27    if err != nil {
28        panic(err)
29    }
30
31    fmt.Println("pod count:", len(pods.Items))
32}

If this returns forbidden, inspect RBAC for both impersonation and target resource access.

RBAC Needed for Impersonation

The caller must be allowed to impersonate users or groups.

yaml
1apiVersion: rbac.authorization.k8s.io/v1
2kind: ClusterRole
3metadata:
4  name: can-impersonate-users
5rules:
6  - apiGroups: [""]
7    resources: ["users", "groups"]
8    verbs: ["impersonate"]
9---
10apiVersion: rbac.authorization.k8s.io/v1
11kind: ClusterRoleBinding
12metadata:
13  name: bind-impersonator
14subjects:
15  - kind: User
16    name: [email protected]
17roleRef:
18  apiGroup: rbac.authorization.k8s.io
19  kind: ClusterRole
20  name: can-impersonate-users

Grant only what is required. Broad impersonation scope is a high-risk permission.

Verify with kubectl auth can-i

Quick checks isolate where failure occurs.

bash
kubectl auth can-i impersonate users --as=[email protected]
kubectl auth can-i get pods --as=[email protected] -n default

First command tests whether real caller can impersonate. Second tests whether impersonated identity can access the target resource.

Safer Pattern for Multi-Tenant Admin Tools

In internal platforms, do not allow arbitrary impersonation from request parameters. Enforce allow lists and policy checks before setting cfg.Impersonate fields.

go
1allowed := map[string]bool{
2    "[email protected]": true,
3    "[email protected]": true,
4}
5
6if !allowed[targetUser] {
7    return fmt.Errorf("target user not allowed: %s", targetUser)
8}

Also log who requested impersonation and why. Auditability matters in security reviews.

Common Failure Modes

Typical reasons impersonation appears broken:

  • impersonation role missing.
  • wrong cluster context in kubeconfig.
  • attempting to impersonate a group not covered by policy.
  • target user lacks permission even though impersonation itself is allowed.

Treat these as separate checks, not one combined guess.

Impersonate Extra Fields Carefully

Kubernetes also supports extra impersonation attributes through cfg.Impersonate.Extra. Use this only when your auth stack expects those claims, and validate accepted keys with platform security owners.

go
cfg.Impersonate.Extra = map[string][]string{
    "scopes": {"read:pods"},
}

Extra fields are powerful but can create policy confusion if different services interpret claims differently. Keep usage narrowly documented and audited.

Common Pitfalls

  • Setting impersonation fields but forgetting impersonate RBAC permissions.
  • Assuming cluster-admin authentication automatically grants impersonation.
  • Debugging only target resource permissions and skipping impersonation permission checks.
  • Allowing free-form impersonation targets in multi-tenant tooling.
  • Running impersonated operations without security audit logging.

Summary

  • Configure impersonation in rest.Config before building Kubernetes clients.
  • Grant explicit impersonate RBAC verbs to the real caller identity.
  • Validate both impersonation rights and target resource rights.
  • Restrict impersonation scope in admin tooling.
  • Keep detailed audit logs for all impersonated operations.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.