Dev.to Security 🔐 Cybersecurity 👁 0 📖 10 min read

OIDC and kubectl: kill lifetime kubeconfigs and prove who deleted a namespace

Every cluster I audit has the same artifact lying around: a kubeconfig with an embedded client certificate, valid for a year (or ten), copied into three CI jobs, two laptops and one Confluence page. It has cluster-admin.

Every cluster I audit has the same artifact lying around: a kubeconfig with an embedded client certificate, valid for a year (or ten), copied into three CI jobs, two laptops and one Confluence page. It has cluster-admin. Nobody can revoke it, and when a namespace disappears on a Friday afternoon, the audit log says the culprit was kubernetes-admin or system:admin.

This article walks through the full path out of that: plugging the API server into an OIDC provider (Keycloak or Microsoft Entra ID), using kubelogin on the client side, binding RBAC to groups instead of users, and writing an audit-policy.yaml that lets you answer "who deleted prod-payments?" with a name, a group list and a source IP.

The problem with lifetime kubeconfigs

What a client certificate actually gives you

Kubernetes client certificate authentication maps CN to the username and each O to a group. That is the entire identity model. Three consequences:

  • No revocation. kube-apiserver does not check CRLs or OCSP. A leaked client cert is valid until notAfter, period. Your only real remediation is rotating the cluster CA — a disruptive operation on every node and every component.
  • No lifecycle. When an engineer leaves, nothing in the cluster knows. Their cert keeps working.
  • No second factor, no conditional access. The file is the credential.

What the audit log shows today

With a shared admin kubeconfig, every entry looks like this:

{"user":{"username":"kubernetes-admin","groups":["system:masters"]},"verb":"delete","objectRef":{"resource":"namespaces","name":"prod-payments"}}

system:masters also bypasses RBAC entirely, so there is no policy layer to constrain it. You have an event, but no accountable human. For SOC 2, ISO 27001 or PCI-DSS, "we think it was someone on the platform team" is not an answer.

How OIDC authentication works in the API server

The flow is stateless on the server side, which is why it scales well:

  1. kubectl calls an exec credential plugin (kubelogin), which runs an OAuth 2.0 authorization code flow with PKCE against the identity provider, opening your browser.
  2. The IdP returns an ID token (a signed JWT) and a refresh token. kubelogin caches them under ~/.kube/cache/oidc-login/.
  3. kubectl sends the ID token as Authorization: Bearer <jwt>.
  4. The API server validates the signature against the issuer's JWKS (fetched and cached from /.well-known/openid-configuration), checks iss, aud and exp, then maps claims to a username and a list of groups.

The API server never calls the IdP per request. Downside: an issued ID token cannot be revoked. That is why ID token lifetime must be short (5–10 minutes) and why revoking the IdP session (killing the refresh token) is what actually locks someone out.

Wiring the API server to the provider

Vanilla Kubernetes: the legacy flags

On a kubeadm cluster, edit /etc/kubernetes/manifests/kube-apiserver.yaml:

spec:
  containers:
  - command:
    - kube-apiserver
    - --oidc-issuer-url=https://keycloak.example.com/realms/platform
    - --oidc-client-id=kubernetes
    - --oidc-username-claim=email
    - --oidc-username-prefix=oidc:
    - --oidc-groups-claim=groups
    - --oidc-groups-prefix=oidc:
    - --oidc-ca-file=/etc/kubernetes/pki/keycloak-ca.crt
    - --oidc-signing-algs=RS256

The prefixes are not cosmetic. Without oidc:, an IdP group literally named system:masters would grant cluster-admin to whoever can create that group in Keycloak. Always prefix both username and groups.

Structured authentication configuration (1.30+)

The flags only support one issuer and no validation logic. Since v1.30 (beta, --authentication-config), you can use a config file with CEL rules:

apiVersion: apiserver.config.k8s.io/v1beta1
kind: AuthenticationConfiguration
jwt:
- issuer:
    url: https://keycloak.example.com/realms/platform
    audiences:
    - kubernetes
    certificateAuthority: |
      -----BEGIN CERTIFICATE-----
      ... Keycloak CA ...
      -----END CERTIFICATE-----
  claimMappings:
    username:
      claim: email
      prefix: "oidc:"
    groups:
      claim: groups
      prefix: "oidc:"
    uid:
      claim: sub
  claimValidationRules:
  - expression: 'claims.email_verified == true'
    message: the email claim must be verified
  userValidationRules:
  - expression: "!user.username.startsWith('system:')"
    message: usernames cannot use the system: prefix

Reference it with --authentication-config=/etc/kubernetes/auth/authn.yaml (and mount the file into the static pod). It is hot-reloaded, so you can rotate the issuer CA without restarting the API server.

OpenShift

You cannot edit API server flags on OpenShift. The supported path is the built-in OAuth server acting as a broker: it authenticates users against Keycloak/Entra ID and issues OpenShift access tokens that carry an expiry and are revocable server-side.

oc create secret generic keycloak-client-secret \
  --from-literal=clientSecret="$KEYCLOAK_CLIENT_SECRET" \
  -n openshift-config

oc create configmap keycloak-ca --from-file=ca.crt=keycloak-ca.crt -n openshift-config
apiVersion: config.openshift.io/v1
kind: OAuth
metadata:
  name: cluster
spec:
  identityProviders:
  - name: keycloak
    mappingMethod: claim
    type: OpenID
    openID:
      clientID: openshift
      clientSecret:
        name: keycloak-client-secret
      ca:
        name: keycloak-ca
      issuer: https://keycloak.example.com/realms/platform
      extraScopes:
      - email
      - profile
      - groups
      claims:
        preferredUsername:
        - preferred_username
        name:
        - name
        email:
        - email
        groups:
        - groups

Apply it, then watch the rollout:

oc get clusteroperator authentication -w
oc login -u <your-idp-user> --server=https://api.cluster.example.com:6443
oc get groups

The groups claim materialises as OpenShift Group objects on first login, which you then bind in RBAC. Note that OpenShift 4.15+ also offers direct external OIDC (authentication.config.openshift.io with type: OIDC), bypassing the internal OAuth server — GA on ROSA/HCP, still behind a feature gate on self-managed clusters at the time of writing.

Entra ID specifics

Three things bite people:

  • Use the v2.0 issuer: https://login.microsoftonline.com/<tenant-id>/v2.0.
  • The groups claim must be enabled in the app registration's Token configuration, and it emits object IDs (GUIDs), not display names. Your RoleBindings will reference oidc:0a3f.... Add a comment, or configure group name emission for synced AD groups.
  • If a user is in more than ~200 groups, Entra ID replaces the claim with a _claim_names overage pointer and the API server sees no groups at all. Test with your heaviest user.

Client side: kubelogin

kubectl krew install oidc-login
# or: brew install int128/kubelogin/kubelogin

kubectl oidc-login setup \
  --oidc-issuer-url=https://keycloak.example.com/realms/platform \
  --oidc-client-id=kubernetes \
  --oidc-extra-scope=groups,email

The CLI client should be a public client with PKCE and no secret — a secret shipped to every laptop is not a secret. Then the kubeconfig contains no credential at all:

apiVersion: v1
kind: Config
clusters:
- name: prod
  cluster:
    server: https://api.cluster.example.com:6443
    certificate-authority: /etc/pki/cluster-ca.crt
users:
- name: oidc
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: kubectl
      args:
      - oidc-login
      - get-token
      - --oidc-issuer-url=https://keycloak.example.com/realms/platform
      - --oidc-client-id=kubernetes
      - --oidc-extra-scope=groups
      - --oidc-extra-scope=email
      - --oidc-use-pkce
      interactiveMode: IfAvailable
contexts:
- name: prod
  context:
    cluster: prod
    user: oidc
current-context: prod

This file is safe to commit to your internal dotfiles repo. For headless CI runners, do not reuse it: use a ServiceAccount token bound to a specific namespace, or Workload Identity Federation.

Verify the identity the API server sees:

kubectl auth whoami
# ATTRIBUTE   VALUE
# Username    oidc:[email protected]
# Groups      [oidc:platform-admins oidc:staff system:authenticated]

RBAC on groups, not on users

Binding to individual usernames recreates the lifecycle problem in RBAC. Bind to groups, and let the IdP own membership.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: platform-admins
subjects:
- kind: Group
  name: "oidc:platform-admins"
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: payments-devs
  namespace: prod-payments
subjects:
- kind: Group
  name: "oidc:team-payments"
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: edit
  apiGroup: rbac.authorization.k8s.io

The group name must include the prefix you configured. A missing oidc: is the single most common reason for "I'm logged in but I get Forbidden".

kubectl auth can-i delete namespace/prod-payments --as-group="oidc:team-payments" --as=oidc:[email protected]

Audit: making the log usable

The policy file

First matching rule wins, so order matters. This policy drops noise, keeps secret bodies out of the log, and captures full request/response for destructive operations:

apiVersion: audit.k8s.io/v1
kind: Policy
omitStages:
- RequestReceived
rules:
# 1. Drop health/probe noise
- level: None
  nonResourceURLs: ["/healthz*", "/readyz*", "/livez*", "/version", "/metrics"]
- level: None
  users: ["system:kube-proxy", "system:apiserver"]
  verbs: ["watch", "list", "get"]

# 2. NEVER log secret contents - metadata only
- level: Metadata
  resources:
  - group: ""
    resources: ["secrets"]
  - group: ""
    resources: ["serviceaccounts/token"]

# 3. Destructive actions: full bodies
- level: RequestResponse
  verbs: ["delete", "deletecollection"]
  resources:
  - group: ""
    resources: ["namespaces", "persistentvolumeclaims", "nodes", "pods"]
  - group: "apps"
    resources: ["deployments", "statefulsets", "daemonsets"]

# 4. Any RBAC change
- level: RequestResponse
  resources:
  - group: "rbac.authorization.k8s.io"
    resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]

# 5. Everything else that mutates
- level: Request
  verbs: ["create", "update", "patch", "delete"]

# 6. Reads: metadata only
- level: Metadata

API server flags:

- --audit-policy-file=/etc/kubernetes/audit/audit-policy.yaml
- --audit-log-path=/var/log/kubernetes/audit/audit.log
- --audit-log-format=json
- --audit-log-maxage=30
- --audit-log-maxbackup=10
- --audit-log-maxsize=200

OpenShift

OpenShift ships audit logging enabled by default. You tune the profile per group:

apiVersion: config.openshift.io/v1
kind: APIServer
metadata:
  name: cluster
spec:
  audit:
    profile: Default
    customRules:
    - group: system:authenticated:oauth
      profile: WriteRequestBodies
    - group: oidc:platform-admins
      profile: AllRequestBodies

Proving who deleted the namespace

oc adm node-logs --role=master --path=kube-apiserver/audit.log \
  | jq -c 'select(.verb=="delete" and .objectRef.resource=="namespaces")
           | {t:.requestReceivedTimestamp, who:.user.username,
              groups:.user.groups, ns:.objectRef.name,
              ip:.sourceIPs[0], ua:.userAgent,
              code:.responseStatus.code, id:.auditID}'
{"t":"2024-11-08T16:42:10Z","who":"oidc:[email protected]",
 "groups":["oidc:platform-admins","system:authenticated"],
 "ns":"prod-payments","ip":"10.4.12.77","ua":"kubectl/v1.30.2",
 "code":200,"id":"7a1c9f3e-..."}

That is the whole point of the exercise: a human identity, their group membership at the time of the action, the client IP and a correlation auditID you can pivot on across the admission chain.

Two fields worth knowing: impersonatedUser (someone used --as) and, since v1.32, user.extra["authentication.kubernetes.io/credential-id"], which carries the JWT jti. That lets you tie many API calls to one specific token issuance — invaluable when investigating a stolen token.

Ship these logs off-cluster (webhook backend, Vector, Fluent Bit → Loki/Elastic/S3 with object lock). Audit logs stored only on the control plane node are evidence an attacker can delete.

Decommissioning permanent certificates

Enabling OIDC changes nothing until the old credentials are gone.

# Who still authenticates with a certificate? Look for the absence of an oidc: prefix
oc adm node-logs --role=master --path=kube-apiserver/audit.log \
  | jq -r 'select(.user.groups != null and (.user.groups | index("system:masters")))
           | [.requestReceivedTimestamp, .user.username, .sourceIPs[0]] | @tsv' \
  | sort -u

# Remove the OpenShift bootstrap admin
oc delete secret kubeadmin -n kube-system

# Remove RBAC bound to certificate identities
kubectl get clusterrolebindings -o json \
  | jq -r '.items[] | select(.subjects[]?.kind=="User" and (.subjects[].name | startswith("oidc:") | not))
           | .metadata.name'

For the break-glass credential you still need (IdP outage), keep one short-lived client certificate sealed in a vault, with a dedicated CN, an alert on any audit entry matching it, and a documented rotation after every use. Set --oidc-signing-algs and keep the issuer reachable from every control plane node — if Keycloak is down and your only admin path was OIDC, you have built a very secure brick.

Security best practices

  • ID token TTL of 5–10 minutes. Tokens are not revocable; refresh tokens are. Revoking the IdP session must be part of your offboarding runbook.
  • Always prefix usernames and groups (oidc:). Add a userValidationRule rejecting system: prefixes.
  • Validate the audience. Use audiences: in the structured config, or --oidc-required-claim=aud=kubernetes, so a token minted for your intranet app cannot be replayed against the API.
  • One OIDC client per cluster, public + PKCE for CLI, confidential for the OpenShift OAuth broker. Never share client secrets with end users.
  • Pin the issuer CA (certificateAuthority / --oidc-ca-file) instead of trusting the system trust store.
  • Never log secret bodies. The Metadata-only rule for secrets must come before any RequestResponse rule, otherwise a delete secret writes the payload into your SIEM.
  • No system:masters for humans. It bypasses RBAC and admission webhooks. Bind a real cluster-admin ClusterRole to an OIDC group instead.
  • Alert on the signals that matter: delete namespaces, any write on clusterrolebindings, responseStatus.code == 403 bursts, use of the break-glass CN, and a rise in authentication_attempts{result="error"}.
  • Test the overage case on Entra ID and the group-sync latency on Keycloak before you cut over production.

Conclusion

Replacing client certificates with OIDC is less about cryptography and more about accountability. Three pieces do the work:

  1. The API server trusts an issuer, not a static file — via --oidc-issuer-url and a groups claim, or the structured AuthenticationConfiguration on 1.30+, or the OAuth/OpenID identity provider on OpenShift.
  2. kubelogin removes credentials from the kubeconfig entirely: the file becomes a pointer to an IdP, safe to distribute, and every token expires in minutes.
  3. audit-policy.yaml turns the API server into a witness: user.username, user.groups, sourceIPs and auditID on every destructive verb, shipped to immutable storage.

Bind RBAC to groups, decommission every permanent certificate you find in the audit log, and keep exactly one documented break-glass path. After that, "who deleted prod-payments?" is a jq one-liner, not a forensic investigation.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.