Skip to content

Kubernetes Security: RBAC, ServiceAccounts, Pod Security Admission, Policy Engines, Audit ​

"All parts of an API request must be allowed by some authorization mechanism in order to proceed. In other words: access is denied by default." — Kubernetes documentation, Authorization

Summary: Every change to a Kubernetes cluster is an HTTPS request to kube-apiserver, and every request is authenticated and authorized. Requests that create, update, patch or delete objects then pass admission control (is this object acceptable) and are persisted, with an audit trail beside all of it. CONNECT requests to subresources such as pods/exec, pods/attach, pods/portforward and proxy also pass admission but store no object; reads (get, list, watch) skip admission entirely: "reads bypass the admission control layer". This chapter is about configuring those gates so people, pipelines and Pods get exactly the access they need, and about the network layer (NetworkPolicy) that limits what a compromised Pod can reach once it is running. Focus: The request flow; authentication with client certificates, OIDC and ServiceAccount tokens (bound, projected, time-limited, the TokenRequest API, automountServiceAccountToken); RBAC (Role, ClusterRole, RoleBinding, ClusterRoleBinding, verbs, resources and subresources such as pods/exec and pods/log, nonResourceURLs, resourceNames, aggregated ClusterRoles, the default ClusterRoles view, edit, admin and cluster-admin), kubectl auth can-i and impersonation with --as, least privilege and the escalation paths (escalate and bind verbs, creating Pods, nodes/proxy, system:masters); workload identity to cloud IAM (IRSA, EKS Pod Identity, GKE Workload Identity, Azure Workload Identity); Pod Security Admission labels, modes, versions and exemptions; admission webhooks (ValidatingWebhookConfiguration, MutatingWebhookConfiguration, failurePolicy), ValidatingAdmissionPolicy with CEL, Kyverno and OPA Gatekeeper with three example policies (require non-root, disallow latest tag, require limits); image signature verification with cosign and Kyverno; audit logging (policy levels, stages, backends, what to alert on); NetworkPolicy (default deny, ingress and egress, selectors, ipBlock, DNS egress, CNI support) with a preview of Cilium and Calico L7 policies; Secrets RBAC; API server and kubelet hardening with the CIS Kubernetes Benchmark and kube-bench; multi-tenancy (the namespace boundary, hierarchical namespaces, vCluster); a Go service that reads ConfigMaps in its own namespace with client-go, and a Laravel Pod with no API access at all. Learning goal: Read any RBAC binding and say what it really grants; design ServiceAccounts, Roles and bindings for a service, a team and a CI pipeline without cluster-admin; label namespaces for Pod Security Admission and roll out a policy engine without an outage; write an audit policy that catches exec and Secret reads without logging Secret values; lock a namespace down with NetworkPolicy and know when the CNI will ignore it; and give a Go service exactly one permission it can verify at start-up.

This chapter is the API-side security chapter of the Kubernetes group. Its neighbours own the rest: what the Pod Security Standards levels forbid, securityContext, capabilities, seccomp, image scanning and signing are Container Security; the API server, etcd, kubeconfig and the object model are Kubernetes Architecture & Setup; Pods, Deployments and probes are Kubernetes Workloads; Secret types, encryption at rest and External Secrets are Config, Secrets & Storage; reading audit logs and events while debugging is Kubernetes Observability & Troubleshooting; Argo CD's own RBAC and GitOps flow are GitOps; CI runners and their OIDC federation are CI/CD Pipelines. The general theory of RBAC, ABAC and zero trust is Authorization: RBAC, ABAC & Zero Trust, OIDC itself is OAuth 2.0, OIDC & SSO, service-to-service mTLS is mTLS & Service Security, incident process is Secure SDLC & Incident Response, node and cloud firewalls are Firewalls, iptables, nftables & Security Groups, and verifying tokens in your own Go code is Authentication in Go.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why the API server has four gatesWhy it exists
ABAC to RBAC, PSP to PSA, Secret tokens to bound tokens, webhooks to CELWhere it comes from
authentication → authorization → admission control, the request flowRequest flow
Client certificates, OIDC, structured authentication config, anonymous requestsAuthentication
ServiceAccount token, bound service account token, projected token, TokenRequest API, automountServiceAccountTokenServiceAccounts
Role, ClusterRole, RoleBinding, ClusterRoleBindingRBAC objects
Verbs get list watch create update patch delete, resources, subresources, nonResourceURLsRules
Default ClusterRoles view edit admin cluster-admin; aggregated ClusterRoleDefault and aggregated roles
kubectl auth can-i, impersonation --as, SelfSubjectAccessReviewChecking access
Least privilege; escalate bind verbs; privilege escalation via create podsEscalation paths
Workload identity: IRSA, EKS Pod Identity, GKE Workload Identity, Azure Workload IdentityWorkload identity
Pod Security Admission labels, audit warn modes, versions, exemptionsPod Security Admission
Admission webhooks, ValidatingWebhookConfiguration, MutatingWebhookConfiguration, failurePolicyAdmission webhooks
ValidatingAdmissionPolicy, CEL, MutatingAdmissionPolicyValidatingAdmissionPolicy
Kyverno ClusterPolicy and ValidatingPolicy, OPA Gatekeeper ConstraintTemplatePolicy engines
Image signature verification, cosign, Kyverno verifyImagesSigned images only
Audit logging, audit policy levels None Metadata Request RequestResponse, audit backendsAudit logging
NetworkPolicy, default deny, podSelector namespaceSelector ipBlock, DNS egressNetworkPolicy
Cilium, Calico, CiliumNetworkPolicy L7, toFQDNsCNI policy extensions
Secrets RBAC, encryption at rest linkSecrets access
API server flags anonymous-auth, authorization-mode, kubelet authentication, CIS Kubernetes Benchmark, kube-benchHardening
Multi-tenancy, namespace boundary, hierarchical namespaces, vClusterMulti-tenancy
Evaluation order, the token JWT, admission order, knobs, error messagesMechanics
CodeGo, Laravel
Eight classic problems and their fixesSolving the classic problems
Which policy layer, which human login, which workload identity, which CNI, which tenancyChoosing
From one namespace to many clustersIn architecture
Commands with expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four gates of one request (kube-apiserver, Kubernetes v1.37).

GateQuestionConfigured byFailureTypical tools
AuthenticationWho is calling?--client-ca-file, --authentication-config (OIDC JWT authenticators), ServiceAccount token keys401 Unauthorized, or system:anonymous if no credential and anonymous is onClient certificates, Dex, Keycloak, Okta, Entra ID, EKS access entries
AuthorizationMay this user do this verb on this resource?--authorization-mode=Node,RBAC (or --authorization-config)403 ForbiddenRBAC objects, kubectl auth can-i
Admission controlIs this object acceptable (and should it be changed)? For create/update/patch/delete and CONNECT (exec, attach, portforward, proxy); get/list/watch bypass itBuilt-in plugins, Pod Security Admission labels, ValidatingAdmissionPolicy, webhooksadmission webhook ... denied the request, violates PodSecurityPSA, CEL policies, Kyverno, OPA Gatekeeper
PersistenceStore itetcd, --encryption-provider-config(none: the object exists)KMS provider for Secrets
Audit (beside all four)What happened, by whom?--audit-policy-file, log or webhook backendNo policy file = no audit eventsFalco, a SIEM, cloud audit logs
Network (after the Pod runs)What may this Pod connect to?NetworkPolicy objects, enforced by the CNIConnection dropped (timeout)Calico, Cilium, cloud CNIs

RBAC in one table.

ObjectScopeHoldsPlain words
RoleOne namespaceRules (apiGroups × resources × verbs)"In shop, reading ConfigMaps"
ClusterRoleClusterRules, cluster-scoped resources, nonResourceURLs, optional aggregationRuleA reusable permission set, or one for nodes, namespaces, /healthz
RoleBindingOne namespaceroleRef (Role or ClusterRole) + subjects"Grant this set, but only inside shop"
ClusterRoleBindingClusterroleRef (ClusterRole) + subjects"Grant this set everywhere": rarely right
Subject—User, Group or ServiceAccountUsers and groups are strings from authentication; there is no User object
Built-in ClusterRoles—view, edit, admin, cluster-adminview cannot read Secrets; edit can, and can run Pods as any ServiceAccount

The policy layers in one table.

LayerWhat it decidesRuns whereFails howUse it for
Pod Security AdmissionPods against privileged / baseline / restrictedIn kube-apiserverCannot fail (no network call)The floor for every namespace
ValidatingAdmissionPolicyAny object, CEL expressionsIn kube-apiserverCEL error → failurePolicySimple organisation rules, no extra component
KyvernoValidate, mutate, generate, verify images; background reportsWebhook DeploymentWebhook down → its failurePolicyImage signatures, digests, defaults, reports
OPA GatekeeperRego constraints, audit of existing objectsWebhook DeploymentDefault Ignore (fail open) per its docsTeams already using OPA and Rego elsewhere
NetworkPolicyPod-to-pod and egress at L3/L4The CNI on every nodeUnsupported CNI: silently ignoredDefault deny, explicit allows
Audit policyWhat is recordedkube-apiserverLog backend blocks by defaultDetection and forensics
kubectl apply: four gates, one audit trail; get/list/watch skip step 3, CONNECT skips step 4clientkubectl, CI,a Pod (client-go)1 Authenticationclient cert, OIDC JWT,ServiceAccount token2 AuthorizationNode, RBAC, Webhookfirst allow/deny wins3 Admissionmutate, validateschema, then validate4 etcdobject stored,watchers notifiedbad credential: 401none: system:anonymousno authorizer allows:403 Forbiddenany plugin rejects:denied, nothing storedStep 3 runs for create/update/patch/delete and CONNECT (exec, attach, portforward, proxy: nothing stored)mutating: ServiceAccount plugin addsthe token volume; MutatingAdmissionPolicy;MutatingWebhookConfigurationobject schemavalidation (types,required fields)validating: PodSecurity (PSA labels), ResourceQuota,ValidatingAdmissionPolicy (CEL, in process),ValidatingWebhookConfiguration (Kyverno, Gatekeeper)Audit (--audit-policy-file)stages RequestReceived, ResponseStarted, ResponseComplete, Panic; level None / Metadata / Request / RequestResponserecords user, groups, verb, resource, decision and (for PSA audit mode or VAP Audit) the policy annotation

Why it exists ​

The Kubernetes API is the control plane of everything that runs on the cluster. Whoever can create a Pod can choose its image, its ServiceAccount, its volumes and, unless something stops them, privileged: true and hostPath: /. That makes "write access to the API" equivalent to "root on the nodes" unless the gates narrow it. Before RBAC, clusters used ABAC (a JSON policy file on the API server that needed a restart to change) or simply trusted everyone with a certificate. Before bound tokens, every ServiceAccount had a Secret holding a token that never expired; any backup of etcd or any kubectl get secret -o yaml leaked permanent credentials. Before Pod Security Admission, PodSecurityPolicy combined authorization and admission in a way so confusing that it was removed.

The design that replaced them is layered on purpose. Authentication says who; RBAC says what verbs on what resources; admission looks inside the object (RBAC cannot express "Pods but not privileged ones"); audit records it all; NetworkPolicy limits the blast radius when the application inside a correctly admitted Pod is compromised anyway.

Simpler choiceRicher choiceWhat you buyWhat you pay
Everyone shares one admin kubeconfigOIDC login, groups, RoleBindings per namespacePer-person audit trail, revocation in the IdPAn identity provider and group hygiene
cluster-admin for CIA deployer Role per namespace, short TokenRequest tokensA leaked runner token is one namespace, for minutesOne Role per app namespace to maintain
The default ServiceAccount everywhereOne ServiceAccount per workload, token automount offA compromised Pod has no API accessA few more objects per app
Static cloud keys in SecretsWorkload identity (IRSA, GKE, Azure)No long-lived cloud credentials in the clusterOIDC trust set-up per cluster
No admission policyPSA restricted + one policy enginePrivileged Pods and :latest cannot be deployedPolicies to test, a webhook to operate
Flat networkDefault-deny NetworkPolicy + allowsRCE in one Pod cannot reach the database or the metadata APIEvery new dependency needs an allow rule
No auditMetadata-level audit, alerts on exec and Secret readsYou can answer "who did this?"Log volume and storage

The analogy used through this page: an office building. Authentication is the badge reader at the door: it only establishes who you are (a contractor with a temporary badge is still somebody). Authorization is the access list for each room and cabinet: the badge opens the finance floor or it does not, and there is no "deny" sticker, only rooms you were or were not given. Admission is the security desk that opens your box before it enters the building: you may be allowed into the server room and still not be allowed to bring in a ladder. The audit log is the camera system. NetworkPolicy is the internal doors between departments, which matter on the day someone's badge is stolen. A ServiceAccount token is a badge printed for a robot; a bound token is a badge that stops working when the robot leaves the building, and expires at the end of the shift anyway.

Three common misunderstandings, up front ​

  1. "RBAC can deny." It cannot: "Permissions are purely additive (there are no "deny" rules)." If any binding grants a verb, the request is allowed by RBAC; to stop it you must remove the grant. Deny-style rules ("no privileged Pods", "no :latest") belong in admission. See RBAC objects.
  2. "Read-only access is safe." get, list and watch on Secrets all return Secret data: "The get, list and watch verbs can all return the full details of a resource." And create on Pods in a namespace lets you run as any ServiceAccount there and mount any Secret. See Escalation paths.
  3. "A NetworkPolicy object means the traffic is blocked." Only if the network plugin enforces it: "Creating a NetworkPolicy resource without a controller that implements it will have no effect." See NetworkPolicy.

Where it comes from ​

WhenWhat happenedSource
v1.6 → v1.8 (Oct 2017)RBAC beta in 1.6, promoted to GA in 1.8 (rbac.authorization.k8s.io/v1), with the default ClusterRoles edit, view and admin; ABAC remains as a file-based modeKubernetes blog, "Using RBAC, Generally Available in Kubernetes v1.8"
v1.14The system:basic-user and system:discovery roles stop being bound to system:unauthenticated by defaultRBAC reference, default roles table
v1.21PodSecurityPolicy deprecatedPSA stable blog
v1.22Bound service account token volumes stable: Pods get time-limited tokens via TokenRequest instead of Secret-based tokensServiceAccount admin reference
v1.24LegacyServiceAccountTokenNoAutoGeneration on by default: no more auto-created token Secrets (GA, gate removed in v1.27)Service accounts concept page
25 Aug 2022, v1.25Pod Security Admission stable; PodSecurityPolicy removedKubernetes blog, "Pod Security Admission Controller in Stable"
v1.29Unused auto-generated legacy token Secrets are invalidated after one year and later purgedServiceAccount admin reference
v1.30 (Apr 2024)ValidatingAdmissionPolicy GA: CEL policies inside the API serverKubernetes blog, VAP GA; VAP reference
v1.33Creating node-bound ServiceAccount tokens is GAServiceAccount admin reference
v1.34Structured authentication configuration (AuthenticationConfiguration, first in v1.29) and anonymous-endpoint configuration (first in v1.31) are stableAuthentication reference
v1.35kubectl --as-user-extra for impersonating extra fieldsUser impersonation reference
v1.36MutatingAdmissionPolicy stable (first in v1.30): CEL mutations without webhooksMutatingAdmissionPolicy reference
2025The Hierarchical Namespace Controller repository is archived under kubernetes-retiredGitHub repository metadata
2026Kubernetes 1.37 is current (1.37.2 released 2026-10-13); Kyverno 1.18 docs mark ClusterPolicy deprecated in favour of ValidatingPolicy and ImageValidatingPolicy; Gatekeeper v3.23 bundles OPA v1.17kubernetes.io/releases, Kyverno docs, Gatekeeper OPA versions page

Two lineages meet in today's clusters. The API-server lineage moved logic from external webhooks into the server itself: PSA replaced PSP, ValidatingAdmissionPolicy and MutatingAdmissionPolicy now cover what used to need a webhook, and structured authentication configuration replaced a dozen --oidc-* flags with a reloadable file. The ecosystem lineage (OPA Gatekeeper, Kyverno, Cilium, Calico) adds what the core does not: image signatures, background reports, mutation libraries, L7 and DNS-aware network rules. Kyverno itself is converging on the core model: its new policy types are written in CEL and shaped like ValidatingAdmissionPolicy.

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product does, and the fix.

Request flow: authentication, authorization, admission control Must-know ​

In plain words: kube-apiserver asks every request who you are and whether you are allowed to do this; for create, update, patch and delete it then asks whether the object you are sending is acceptable, and for CONNECT subresources (pods/exec, pods/attach, pods/portforward, proxy) whether the connection may be opened; a CONNECT that passes admission persists nothing. A "no" at any step ends the request; nothing reaches etcd. Reads are never seen by admission: admission controllers "do not (and cannot) block requests to read (get, watch or list) objects, because reads bypass the admission control layer", so only RBAC protects a Secret from get.

Common misunderstanding: "RBAC checks the object." RBAC sees only attributes (user, groups, verb, API group, resource, subresource, namespace, name). It never sees the Pod spec, so it cannot tell a privileged Pod from a harmless one. The authorization page says it directly: "Access controls and policies that depend on specific fields of specific kinds of objects are handled by admission controllers," and "admission control happens after authorization has completed (and, therefore, only when the authorization decision was to allow the request)."

Definition: Authentication plugins (client certificates, bearer tokens, an authenticating proxy) attach "Username", "UID", "Groups" and "Extra fields" to the request; a successful one adds the group system:authenticated. Authorization modules are checked in sequence: "If any authorizer approves or denies a request, that decision is immediately returned and no other authorizer is consulted. If all modules have no opinion on the request, then the request is denied," with HTTP 403. Admission control "proceeds in two phases. In the first phase, mutating admission controllers are run. In the second phase, validating admission controllers are run," and "If any of the controllers in either phase reject the request, the entire request is rejected immediately."

text
kubectl apply -f deployment.yaml as jane (OIDC), namespace shop
1  TLS; Authorization: Bearer <id_token>  -> JWT authenticator: user oidc:jane@acme.example,
   groups [oidc:shop-oncall, system:authenticated]
2  request attributes: verb=patch group=apps resource=deployments ns=shop name=orders-api
3  Node authorizer: no opinion (not a node) -> RBAC: RoleBinding shop-oncall-edit -> allow
4  mutating admission: ServiceAccount plugin, MutatingAdmissionPolicy, mutating webhooks (Kyverno)
5  schema validation of the merged object
6  validating admission: PodSecurity (warn/audit on the template), ValidatingAdmissionPolicy,
   validating webhooks (Kyverno, Gatekeeper), ResourceQuota
7  write to etcd -> audit event at ResponseComplete -> controllers see the change via watch

Real scenarios:

  • A pipeline gets 403 on patch deployments: authentication worked (the error names the user), RBAC has no binding.
  • A developer is allowed to create a Deployment but its Pods never appear: admission (PSA enforce) rejects the Pods the ReplicaSet creates, not the Deployment.
  • Every kubectl call hangs for 10 seconds after a policy-engine upgrade: a webhook with failurePolicy: Fail is unreachable and each call waits for the timeout.
  • An incident review needs "who exec'd into the payments Pod at 03:12": only the audit log has it.
ProductWhere the gates are configured
kubeadm, k3s, self-managedkube-apiserver flags and config files you own (--authentication-config, --authorization-mode, --admission-control-config-file, --audit-policy-file)
EKSIAM authentication via access entries (or the legacy aws-auth ConfigMap); audit to CloudWatch when control-plane logging is enabled
GKEGoogle identities and groups; Cloud Audit Logs; GKE-managed admission
AKSMicrosoft Entra ID integration, Azure RBAC for Kubernetes as an optional webhook authorizer
Docker Desktop, kindA single admin certificate in the kubeconfig: fine for a laptop, never a model for production

Fix: when a request fails, read the status code first (401 = authentication, 403 = authorization, a message naming a webhook or policy = admission), then debug that gate only.

Authentication: client certificates, OIDC, tokens, anonymous requests Must-know ​

In plain words: Kubernetes has no user database. A person is "authenticated" when they present something the API server trusts: a certificate signed by the cluster CA, or a token signed by a trusted issuer. The name inside that credential becomes the username RBAC sees.

Common misunderstanding: "I can delete a user from Kubernetes." The docs: "Kubernetes does not have objects which represent normal user accounts. Normal users cannot be added to a cluster through an API call." A client certificate stays valid until it expires; removing the person's RoleBindings is the only revocation you have, and the RBAC good-practices page warns that a new user with a deleted user's name "can automatically inherit all the rights of the deleted user".

Definition: With client certificates (--client-ca-file), "the common name of the subject is used as the user name for the request" and "Client certificates can also indicate a user's group memberships using the certificate's organization fields." OIDC uses the id_token ("not the access_token") as a bearer token; the docs warn that "The id_token can't be revoked, it's like a certificate so it should be short-lived (only a few minutes)." Since v1.34 the stable AuthenticationConfiguration file (--authentication-config) configures up to 64 JWT authenticators with CEL claimValidationRules, claimMappings and userValidationRules, and cannot be combined with the --oidc-* flags. Anonymous requests: "requests that are not rejected by other configured authentication methods are treated as anonymous requests, and given a username of system:anonymous and a group of system:unauthenticated"; anonymous access "is enabled by default if an authorization mode other than AlwaysAllow is used", and the configuration file can limit it to paths such as /livez, /readyz and /healthz. Static token files (--token-auth-file) exist but need an API server restart to change.

text
OIDC login for a developer (kubelogin-style credential plugin)
1  kubectl needs a token -> exec plugin opens the browser to https://sso.acme.example
2  IdP returns id_token: iss, aud=kubernetes-prod, email=jane@acme.example, groups=[shop-developers], exp=+15m
3  kubectl sends Authorization: Bearer <id_token>
4  API server: issuer + JWKS from discovery, aud matches, exp ok, claimValidationRules (CEL) ok
5  claimMappings: username "oidc:jane@acme.example", groups ["oidc:shop-developers"]
6  RBAC sees those strings; after 15 minutes the plugin refreshes the token silently
yaml
# kube-apiserver --authentication-config=/etc/kubernetes/authentication-config.yaml
# Structured authentication configuration (stable since v1.34). Replaces the
# --oidc-* flags; cannot be combined with them, nor with --anonymous-auth.
# Self-managed clusters only (kubeadm, k3s); EKS, GKE and AKS configure
# identity through their own APIs (access entries, Google groups, Entra ID).
apiVersion: apiserver.config.k8s.io/v1
kind: AuthenticationConfiguration
# Anonymous requests are allowed only on the health endpoints that load
# balancers probe. Everything else returns 401 to an unauthenticated caller.
anonymous:
  enabled: true
  conditions:
    - path: /livez
    - path: /readyz
    - path: /healthz
jwt:
  - issuer:
      url: https://sso.acme.example         # the company's OIDC provider
      audiences:
        - kubernetes-prod                    # the client ID registered for this cluster
    claimValidationRules:
      - expression: 'claims.exp - claims.nbf <= 3600'
        message: id_token lifetime must not exceed one hour
    claimMappings:
      username:
        claim: email
        prefix: "oidc:"                      # oidc:jane@acme.example can never collide with system:*
      groups:
        claim: groups
        prefix: "oidc:"                      # RBAC binds Group oidc:shop-developers
    userValidationRules:
      - expression: "!user.username.startsWith('system:')"
        message: 'username cannot use the reserved system: prefix'

Real scenarios:

  • A contractor leaves; their admin certificate has 364 days left. With certificates you must rotate the CA or keep a deny list in an authorizer webhook; with OIDC you disable them in the IdP and their token dies within minutes.
  • A username claim of system:admin from a misconfigured IdP: the oidc: prefix and a userValidationRules CEL rule stop it colliding with built-in identities.
  • A load balancer probing /readyz needs no credential; with the anonymous conditions list nothing else is reachable anonymously.
  • kubectl auth whoami (SelfSubjectReview) shows exactly which username and groups the API server derived from your kubeconfig.
MethodLifetimeRevocationFits
X.509 client certificateUntil notAfterNone short of CA rotationBreak-glass admin, node and component identities
OIDC id_token (Dex, Keycloak, Okta, Entra ID, Google)MinutesDisable in the IdPPeople
ServiceAccount token (TokenRequest)10 min to hoursDelete the bound object (Pod, Secret, Node)Workloads, CI
Cloud IAM (EKS access entries, GKE, AKS Entra ID)Short, cloud-issuedCloud IAMManaged clusters
Static token fileForeverEdit file, restart API serverNever in production

Fix: people log in through OIDC with prefixed usernames and groups; certificates only for components and a sealed break-glass identity; anonymous access restricted to health endpoints. Theory of OIDC flows: OAuth 2.0, OIDC & SSO.

ServiceAccounts and ServiceAccount tokens: bound, projected, TokenRequest, automountServiceAccountToken Must-know ​

In plain words: A ServiceAccount is the identity of a program inside the cluster. The kubelet puts a short-lived signed token for it into the Pod as a file; the program sends that token to the API server and is recognised as system:serviceaccount:<namespace>:<name>.

Common misunderstanding: "My app does not use the API, so the token does not matter." Unless you turn it off, every Pod gets the default ServiceAccount's token mounted at /var/run/secrets/kubernetes.io/serviceaccount/token. An attacker with code execution in your PHP app reads that file and gets whatever that ServiceAccount (or system:serviceaccounts, or system:authenticated) was ever granted.

Definition: Each namespace has a ServiceAccount named default, assigned to Pods that do not set spec.serviceAccountName. "In v1.22 and later, Kubernetes gets a short-lived, automatically rotating token using the TokenRequest API and mounts the token as a projected volume." The injected volume kube-api-access-* has three sources: a serviceAccountToken ("bound to the specific Pod and has the kube-apiserver as its audience", default lifespan 1 hour), the kube-root-ca.crt ConfigMap and the namespace via the downward API. The kubelet refreshes it when "older than 80% of its total time-to-live (TTL), or if the token is older than 24 hours"; expirationSeconds "must be at least 10 minutes (600 seconds)". Bound tokens are tied to an object (Pod, Secret or Node): the API server checks that the object still exists, so deleting the Pod invalidates the token. automountServiceAccountToken: false can be set on the ServiceAccount or the Pod; "the Pod spec takes precedence". Legacy Secrets of type kubernetes.io/service-account-token "don't expire and don't rotate"; since v1.24 they are no longer auto-created, and since v1.29 unused auto-generated ones are invalidated after a year.

Bound, projected ServiceAccount tokens: from TokenRequest to the cloudkubeletTokenRequest forsa orders-api, pod uid,aud, expirationSecondskube-apiserversigns JWT with--service-account-signing-key-fileJWT (iss, sub, aud, exp)projected volumetoken, ca.crt, namespace;refreshed at 80% of TTLapp containerrest.InClusterConfig()re-reads the fileBearer token, aud = API serverAPI server checks signature,aud, exp, and that the boundPod still exists, then RBACtoken with aud = sts.amazonaws.com / Google / Entracloud IAMIRSA: AssumeRole-WithWebIdentity; GKE WI;Azure WI federationOIDC discoveryissuer URL + JWKS soclouds can verifycluster tokens
text
Pod orders-api-7d9f starts with its own projected token (expirationSeconds: 600)
1  kubelet -> POST /api/v1/namespaces/shop/serviceaccounts/orders-api/token
   {audiences: [api server], expirationSeconds: 600, boundObjectRef: Pod orders-api-7d9f}
2  API server signs a JWT: sub=system:serviceaccount:shop:orders-api, kubernetes.io.pod.uid=...
3  kubelet writes it to the projected volume; app's rest.Config reads the file
4  t=480 s (80 % of 600): kubelet requests a new token, swaps the file atomically
5  Pod deleted -> any copy of the token is rejected: bound object no longer exists

Real scenarios:

  • A CI job needs a kube token for 15 minutes: kubectl create token shop-deployer --duration=15m instead of a long-lived Secret.
  • Vault's Kubernetes auth method wants a token whose audience is vault, not the API server: a second projected serviceAccountToken source with audience: vault.
  • An old cluster still has *-token-* Secrets from before 1.24; each is a credential that never expires.
  • An app caches the token read at start-up and starts failing after an hour; client-go re-reads BearerTokenFile ("If set, the contents are periodically read").
WorkloadServiceAccountToken
Laravel web, queue, schedulershop-web (no bindings)automountServiceAccountToken: false
Go orders-api (lists ConfigMaps)orders-api + one RoleProjected, 600 s, audience API server
Operator / controllerIts own SA, ClusterRole if it watches cluster-wideDefault projected token
CI deployershop-deployer + Rolekubectl create token --duration=15m, or cloud OIDC
Talks to Vault or a cloudIts own SAExtra projected token with that audience
bash
#!/bin/sh
# TokenRequest API from the command line (expected, not run: no cluster here).
# A short-lived, audience-bound token for a CI job, instead of a Secret of
# type kubernetes.io/service-account-token that never expires.
set -eu
NS=shop
SA=shop-deployer

# 1. Ask the API server for a 15-minute token for the deployer ServiceAccount.
#    Requires "create" on serviceaccounts/token in namespace shop.
#    Kept in a shell variable, never written to disk.
TOKEN="$(kubectl create token "$SA" -n "$NS" --duration=15m)"

# 2. Who does the API server think we are with that token?
kubectl --token="$TOKEN" auth whoami
# expected shape:
# ATTRIBUTE   VALUE
# Username    system:serviceaccount:shop:shop-deployer
# UID         <uid>
# Groups      [system:serviceaccounts system:serviceaccounts:shop system:authenticated]

# 3. A token for another audience and bound to a Pod: it dies with the Pod.
kubectl create token orders-api -n "$NS" --audience=vault \
  --bound-object-kind=Pod --bound-object-name="$(kubectl get pod -n "$NS" \
  -l app.kubernetes.io/name=orders-api -o jsonpath='{.items[0].metadata.name}')"

# 4. Find legacy, never-expiring token Secrets that should be deleted.
kubectl get secrets -A --field-selector type=kubernetes.io/service-account-token

Fix: one ServiceAccount per workload, automount off by default, tokens projected explicitly where the API is needed, legacy token Secrets deleted. Note the default --service-account-extend-token-expiration=true: admission-injected tokens are extended "up to 1 year" for old clients (see the token, byte for byte).

RBAC objects: Role, ClusterRole, RoleBinding, ClusterRoleBinding Must-know ​

In plain words: A Role is a list of permissions; a binding gives that list to someone. Roles and RoleBindings live in a namespace; ClusterRoles and ClusterRoleBindings are cluster-wide. A RoleBinding may point at a ClusterRole, which reuses the definition but grants it only inside that one namespace.

Common misunderstanding: "A ClusterRole grants cluster-wide access." Only a ClusterRoleBinding does. RoleBinding shop/oncall-edit → ClusterRole edit gives edit in shop and nowhere else. The opposite mistake is common too: a ClusterRoleBinding to view lets someone read every namespace, including the ones you forgot existed.

Definition: RBAC is enabled with --authorization-mode=...,RBAC. "Permissions are purely additive (there are no "deny" rules)." A binding has subjects (User, Group, ServiceAccount) and a roleRef; "If you try to change a binding's roleRef, you get a validation error", because "Making roleRef immutable allows granting someone update permission on an existing binding object, so that they can manage the list of subjects, without being able to change the role that is granted to those subjects." ServiceAccounts appear as users named system:serviceaccount:<ns>:<name> in groups system:serviceaccounts and system:serviceaccounts:<ns>.

RBAC: rules live in roles, bindings attach roles to subjectsSubjects (who)User oidc:jane@acme.exampleGroup oidc:shop-developersServiceAccount shop/orders-api= system:serviceaccount:shop:...Bindings (grant)RoleBinding (namespace shop)grants only inside shop, evenwhen roleRef is a ClusterRoleClusterRoleBindinggrants in every namespace andon cluster-scoped resourcesRoles (what)Role (namespace shop)orders-api-config-reader:configmaps get list watchClusterRoleview, edit, admin, cluster-admin,aggregated by labelsroleRefOne rule = apiGroups x resources x verbs (x resourceNames)apiGroups [""] (core), ["apps"] resources ["pods", "pods/log", "pods/exec"] (subresources by name)verbs get list watch create update patch delete deletecollection, plus bind escalate impersonate; or nonResourceURLs ["/healthz"]Purely additive: no deny rules. roleRef is immutable. system:masters bypasses RBAC entirely.list on secrets = read all Secrets; create pods = act as any ServiceAccount in the namespace.
text
May system:serviceaccount:shop:orders-api "list configmaps" in namespace payments?
1  ClusterRoleBindings: none name this subject or its groups          -> continue
2  RoleBindings in payments (only that namespace counts): none match   -> continue
3  RoleBinding shop/orders-api-config-reader matches the subject, but it is in shop -> ignored
4  no rule allowed -> RBAC has no opinion -> no other authorizer allows -> 403 Forbidden

Real scenarios:

  • Granting a team admin in their namespace with one RoleBinding to the built-in ClusterRole.
  • An operator that watches its CRD in every namespace: ClusterRole + ClusterRoleBinding, scoped to its own API group.
  • Changing which role a binding grants: delete and recreate the binding (kubectl auth reconcile does this for you).
  • Argo CD's application controller often runs with cluster-wide rights; a per-namespace deployer Role is the alternative for multi-tenant set-ups.
NeedObject pair
Permissions in one namespace, defined thereRole + RoleBinding
Same permission set in many namespacesClusterRole + one RoleBinding per namespace
Cluster-scoped resources (nodes, namespaces, CRDs, PVs) or all namespacesClusterRole + ClusterRoleBinding
/healthz, /metrics and other nonResourceURLsClusterRole + ClusterRoleBinding
Manage subjects without changing the roleupdate on the binding (roleRef is immutable)
yaml
# AFTER, workload side: the Go service orders-api reads its feature-flag
# ConfigMaps from its own namespace and nothing else.
#   - its own ServiceAccount (never "default")
#   - a namespaced Role (not a ClusterRole) with read verbs on one resource
#   - a RoleBinding in the same namespace
# Check it offline with go/rbaccheck, or online with:
#   kubectl auth can-i list configmaps -n shop --as=system:serviceaccount:shop:orders-api
apiVersion: v1
kind: ServiceAccount
metadata:
  name: orders-api
  namespace: shop
  labels:
    app.kubernetes.io/name: orders-api
# The token is mounted explicitly by the Pod spec (see
# serviceaccount/orders-api-deployment.yaml); the ServiceAccount default is off.
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: orders-api-config-reader
  namespace: shop
rules:
  - apiGroups: [""]               # "" is the core API group
    resources: ["configmaps"]
    verbs: ["get", "list", "watch"] # watch so an informer can follow changes
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: orders-api-config-reader
  namespace: shop
roleRef:                          # immutable: delete and recreate to change it
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: orders-api-config-reader
subjects:
  - kind: ServiceAccount
    name: orders-api
    namespace: shop

Fix: default to Role/ClusterRole + RoleBinding; treat every ClusterRoleBinding as a review item. The general model behind roles and permissions is in Authorization: RBAC, ABAC & Zero Trust.

Rules: verbs, resources, subresources, resourceNames, nonResourceURLs Must-know ​

In plain words: A rule is "these verbs, on these resources, in these API groups" (and optionally "only these names"). The verbs come from the HTTP method; subresources such as logs, exec and scale are separate resources you must name.

Common misunderstanding: "resources: [pods] includes logs and exec." It does not: a request for pods/log or pods/exec is checked against pods/log or pods/exec. The audit-policy example in the docs makes the same point: "Resource "pods" doesn't match requests to any subresource of pods, which is consistent with the RBAC policy."

Definition: The request verbs map from HTTP: POST → create; GET/HEAD → get, list (collections, "including full object content") or watch; PUT → update; PATCH → patch; DELETE → delete or deletecollection. The verbs get list watch create update patch delete (plus deletecollection) cover resources; special verbs are impersonate, bind, escalate, approve, and for non-resource requests the lowercased HTTP method. apiGroups: [""] is the core group. Subresources are written pods/log; */scale matches the scale subresource of every resource. resourceNames narrows to named objects, but "You cannot restrict deletecollection or top-level create requests by resource name." nonResourceURLs ("you can use the wildcard * as a suffix glob match") apply to paths like /healthz and only make sense in a ClusterRole.

text
kubectl logs orders-api-7d9f -n shop  ->  GET /api/v1/namespaces/shop/pods/orders-api-7d9f/log
attributes: verb=get group="" resource=pods subresource=log name=orders-api-7d9f ns=shop
rule {apiGroups:[""], resources:["pods"], verbs:["get"]}            -> no match ("pods" != "pods/log")
rule {apiGroups:[""], resources:["pods","pods/log"], verbs:["get"]} -> match -> allowed
kubectl exec ... -> POST .../pods/orders-api-7d9f/exec -> verb=create resource=pods/exec -> needs its own rule

Real scenarios:

  • A log-reader role for developers: pods and pods/log with get, list, watch, and no pods/exec.
  • A controller that may update only its own leader-election Lease: resourceNames: [orders-api-leader] on leases.
  • A HorizontalPodAutoscaler-like tool: update on deployments/scale, nothing on deployments.
  • A monitoring agent scraping /metrics on the API server: nonResourceURLs: ["/metrics"], verbs: ["get"].
Kubectl commandVerbResource / subresource
kubectl get podslistpods
kubectl get pod x -wwatchpods
kubectl logs xgetpods/log
kubectl exec x -- shcreatepods/exec
kubectl port-forward x 8080createpods/portforward
kubectl scale deploy x --replicas=3patchdeployments/scale
kubectl create token sacreateserviceaccounts/token
kubectl debug x (ephemeral container)patchpods/ephemeralcontainers

Fix: write rules from the commands people actually run; never * in verbs, resources or apiGroups ("providing wildcard access gives rights not just to all object types that currently exist in the cluster, but also to all object types which are created in the future").

Default ClusterRoles view, edit, admin, cluster-admin and aggregated ClusterRoles Important ​

In plain words: Every cluster ships four user-facing ClusterRoles meant to be granted per namespace: view, edit, admin, and the super-user cluster-admin. Aggregation lets a CRD's permissions join those roles automatically.

Common misunderstanding: "edit is a safe developer role." The reference says edit "allows accessing Secrets and running Pods as any ServiceAccount in the namespace, so it can be used to gain the API access levels of any ServiceAccount in the namespace." view deliberately excludes Secrets "since reading the contents of Secrets enables access to ServiceAccount credentials".

Definition: cluster-admin (bound to the system:masters group by default) "Allows super-user access to perform any action on any resource"; in a RoleBinding it gives "full control over every resource in the role binding's namespace, including the namespace itself". admin is "intended to be granted within a namespace using a RoleBinding" and includes creating Roles and RoleBindings there, but not "write access to resource quota or to the namespace itself". An aggregated ClusterRole has an aggregationRule with label selectors; the controller manager fills its rules with the rules of every ClusterRole carrying those labels. The built-ins aggregate rbac.authorization.k8s.io/aggregate-to-view, -edit and -admin. Default roles are auto-reconciled at API server start unless annotated rbac.authorization.kubernetes.io/autoupdate: "false".

text
A CRD refundrequests.shop.acme.io is installed
1  without aggregation: users with "view" in shop cannot list refundrequests
2  apply ClusterRole shop-orders-crd-view labelled aggregate-to-view/edit/admin = "true"
3  controller manager recomputes view, edit, admin: rules += refundrequests get list watch
4  every existing RoleBinding to view/edit/admin now covers the CRD; no binding changed

Real scenarios:

  • Operators installed by Helm charts usually ship aggregate-to-* ClusterRoles so namespace admins can manage their custom resources.
  • A custom acme-auditor role assembled from small labelled pieces owned by different teams.
  • Someone edits edit by hand and the change disappears after an API server restart (auto-reconciliation).
  • A vendor chart creates a ClusterRoleBinding to cluster-admin for its controller: review before install.
RoleSecretsRBAC objectsNamespace objectTypical binding
viewNoNoNoRoleBinding, developers
editRead/writeNoNoRoleBinding, on-call
adminRead/writeRoles, RoleBindings in the namespaceNo writeRoleBinding, team lead
cluster-adminAllAllAllClusterRoleBinding, break-glass only
yaml
# AFTER, people and pipelines. Groups come from the OIDC id_token
# (claimMappings.groups in apiserver/authentication-config.yaml, prefix "oidc:").
# Humans are bound to the built-in user-facing ClusterRoles inside one
# namespace with a RoleBinding; nobody but break-glass gets cluster-admin.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: shop-developers-view
  namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: view                     # no Secrets, no Roles/RoleBindings
subjects:
  - kind: Group
    name: oidc:shop-developers
    apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: shop-oncall-edit
  namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: edit                     # can read Secrets and run Pods as any SA here
subjects:
  - kind: Group
    name: oidc:shop-oncall
    apiGroup: rbac.authorization.k8s.io
---
# Read logs without exec: pods/log is a subresource and must be named.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: shop-log-reader
  namespace: shop
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: shop-developers-logs
  namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: shop-log-reader
subjects:
  - kind: Group
    name: oidc:shop-developers
    apiGroup: rbac.authorization.k8s.io
---
# The deployer used by CI (GitHub Actions / GitLab CI) or by Argo CD for this
# namespace: it applies the kinds the app ships and nothing else. It cannot
# touch RBAC, Secrets, the Namespace object (PSA labels) or webhooks.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: shop-deployer
  namespace: shop
rules:
  - apiGroups: ["apps"]
    resources: ["deployments", "statefulsets"]
    verbs: ["get", "list", "watch", "create", "update", "patch"]
  - apiGroups: ["batch"]
    resources: ["jobs", "cronjobs"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: [""]
    resources: ["services", "configmaps"]
    verbs: ["get", "list", "watch", "create", "update", "patch"]
  - apiGroups: ["networking.k8s.io"]
    resources: ["ingresses", "networkpolicies"]
    verbs: ["get", "list", "watch", "create", "update", "patch"]
  - apiGroups: ["policy"]
    resources: ["poddisruptionbudgets"]
    verbs: ["get", "list", "watch", "create", "update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: shop-deployer
  namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: shop-deployer
subjects:
  - kind: ServiceAccount
    name: shop-deployer
    namespace: shop
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: shop-deployer
  namespace: shop
automountServiceAccountToken: false   # CI gets a short TokenRequest token instead
---
# Aggregation: a CRD's permissions join the built-in roles by label.
# The controller manager unions these rules into view/edit/admin.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: shop-orders-crd-view
  labels:
    rbac.authorization.k8s.io/aggregate-to-view: "true"
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
  - apiGroups: ["shop.acme.io"]
    resources: ["refundrequests"]
    verbs: ["get", "list", "watch"]
---
# A custom aggregated ClusterRole of our own: anything labelled
# acme.io/aggregate-to-auditor joins it.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: acme-auditor
aggregationRule:
  clusterRoleSelectors:
    - matchLabels:
        acme.io/aggregate-to-auditor: "true"
# No rules field: the controller manager owns it and overwrites manual rules;
# even "rules: []" claims the field under server-side apply and causes conflicts.
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: acme-auditor-rbac-read
  labels:
    acme.io/aggregate-to-auditor: "true"
rules:
  - apiGroups: ["rbac.authorization.k8s.io"]
    resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
    verbs: ["get", "list", "watch"]
  - nonResourceURLs: ["/healthz", "/livez", "/readyz", "/version"]
    verbs: ["get"]

Fix: view for most people, edit only for on-call, admin for the namespace owner, cluster-admin behind break-glass; extend with aggregation labels instead of editing built-ins.

Checking access: kubectl auth can-i, impersonation --as, SelfSubjectAccessReview Must-know ​

In plain words: Ask the API server what it would decide without doing the thing. kubectl auth can-i asks for yourself; with --as an administrator asks on behalf of someone else.

Common misunderstanding: "can-i reads my RoleBindings." It asks the whole authorization chain: it "uses the SelfSubjectAccessReview API to determine if the current user can perform a given action, and works regardless of the authorization mode used". A yes can therefore come from a webhook authorizer or the Node authorizer, not only RBAC.

Definition: kubectl auth can-i <verb> <resource> [-n ns] prints yes or no; --list prints the rules for a namespace. Impersonation "is a method of allowing authenticated users to act as another user, group, or service account through HTTP headers": Impersonate-User, Impersonate-Group, Impersonate-Uid, Impersonate-Extra-*, set by kubectl's --as, --as-group, --as-uid (1.23) and --as-user-extra (1.35). "Impersonation requests first authenticate as the requesting user, then switch to the impersonated user info"; the caller needs the impersonate verb on users, groups, serviceaccounts or uids. SubjectAccessReview (any user) and LocalSubjectAccessReview (one namespace) are the API forms used by tools and webhooks.

text
$ kubectl auth can-i list configmaps -n shop --as=system:serviceaccount:shop:orders-api
1  kubectl authenticates as the admin, adds Impersonate-User: system:serviceaccount:shop:orders-api
2  API server checks: admin may "impersonate" serviceaccounts? yes
3  creates a SelfSubjectAccessReview as the impersonated SA: verb=list resource=configmaps ns=shop
4  authorizers evaluate -> status.allowed=true, reason "RBAC: allowed by RoleBinding ..."
5  kubectl prints: yes

Real scenarios:

  • Before merging a RoleBinding change: kubectl auth can-i --list -n shop --as=oidc:jane@acme.example --as-group=oidc:shop-developers.
  • A Go service checks its own permission at start-up with a SelfSubjectAccessReview and fails fast with a clear message (Go).
  • A break-glass flow: on-call engineers have only impersonate on a single privileged group, so every privileged action is visibly "as" something in the audit log.
  • kubectl drain mynode --as=superman --as-group=system:masters is the docs' own example of why impersonate is a dangerous verb.
ToolQuestion it answers
kubectl auth can-i / --listMay I (or --as X) do this?
kubectl auth whoamiWho does the server think I am?
kubectl auth reconcile -fApply RBAC objects, recreating bindings whose roleRef changed
rakkess (access matrix), kubectl-who-can (krew plugins)Who can do X; matrix views
rbaccheck in this chapter's snippetsThe same RBAC matching offline, against YAML files in Git

Fix: every RBAC change ships with can-i checks for the positive and the negative case, in CI against the YAML (offline) and after apply against the cluster.

Least privilege and privilege escalation: escalate, bind, impersonate, create pods, nodes/proxy Must-know ​

In plain words: Some permissions are worth more than they look, because they let you obtain other permissions. Least privilege means knowing these and granting them almost never.

Common misunderstanding: "Someone with permission to create Roles can give themselves anything." No: "The RBAC API prevents users from escalating privileges by editing roles or role bindings." You can create a role only if "You already have all the permissions contained in the role" or have the escalate verb; you can bind a role only if you hold its permissions or have the bind verb on it. Those two verbs, not "create roles", are the escalation keys.

Definition: The RBAC good-practices page lists the escalation risks. Workload creation: "Permission to create workloads (either Pods, or workload resources that manage Pods) in a namespace implicitly grants access to many other resources in that namespace, such as Secrets, ConfigMaps, and PersistentVolumes", and "since Pods can run as any ServiceAccount, granting permission to create workloads also implicitly grants the API access levels of any service account in that namespace" (privilege escalation via create pods); privileged Pods reach the node. nodes/proxy: "This access bypasses audit logging and admission control", and "get permission on nodes/proxy is not a read-only permission". escalate and bind bypass the built-in checks. impersonate turns you into anyone. CSRs with approval can mint client certificates with "arbitrary names including duplicates of Kubernetes system components". serviceaccounts/token create issues tokens for existing ServiceAccounts. Webhook configurations can read and mutate every admitted object. Namespace patch can relabel PSA. system:masters membership "bypasses all RBAC rights checks ... which cannot be revoked by removing RoleBindings".

text
"Developers only get create on deployments in shop" (no Secrets access) -> read the payment key anyway
1  kubectl create deploy peek --image=busybox -- sleep 3600, then patch it:
   serviceAccountName: payments-worker, volume secret: stripe-key
2  ReplicaSet creates the Pod; kubelet mounts stripe-key (kubelet reads it, not the developer)
3  kubectl logs is denied? the container can still POST the key anywhere egress allows
-> separate namespaces per trust level, PSA restricted, default-deny egress, audit on Pod creation

Real scenarios:

  • cluster-admin bound to the CI ServiceAccount, the most common finding in cluster reviews (before-overgrant.yaml).
  • A "support read-only" ClusterRole with * resources and list: it reads every Secret in the cluster.
  • A helper that "onboards teams" with bind on clusterroles without resourceNames: it can bind cluster-admin.
  • A metrics agent with get nodes/proxy exploited to exec into any Pod on every node.
GrantEffectively also grantsSafer alternative
create pods / deployments / jobsAny ServiceAccount, any Secret, any ConfigMap in the namespaceDeploy via GitOps with a namespace-scoped deployer; PSA restricted
list/watch secretsAll Secret valuesget with resourceNames, or no Secrets access
create pods/execWhatever the container can readpods/log, ephemeral debug in a separate namespace
escalate / bindAny permissionbind with resourceNames: [view, edit]
impersonateAny identityImpersonate one named group only
get nodes/proxyExec on every Pod of the node, no auditScrape via the metrics API
create serviceaccounts/tokenTokens for every SA in scopeOnly for CI's own SA
patch namespacesChanging PSA and NetworkPolicy labelsPlatform team only
system:masters groupUnrevokable super-userNever in issued certificates except break-glass
A Pod with hostPath to /run/containerd/containerd.sockStart any container on the node through containerd directly: no RBAC, no admission, no auditPSA baseline or restricted (no hostPath)

Fix: run a linter over RBAC in Git (this chapter's rbaccheck, or krew plugins such as kubectl-who-can), review every ClusterRoleBinding, and pair RBAC with PSA and NetworkPolicy because RBAC alone cannot close the create-pods path.

Workload identity: IRSA, EKS Pod Identity, GKE Workload Identity, Azure Workload Identity Important ​

In plain words: Instead of putting a cloud access key into a Secret, let the cloud trust the cluster's ServiceAccount tokens. The Pod presents its projected token to the cloud's identity service and gets temporary cloud credentials for one role.

Common misunderstanding: "The node's IAM role is good enough." Every Pod on the node can read the node's instance metadata credentials unless something blocks it, so the node role becomes the union of all workloads' needs. Workload identity makes the cloud permission per ServiceAccount; whether you may then deny egress to the metadata address depends on the platform (see the Fix below: GKE Workload Identity itself needs it).

Definition: AWS's own background section explains the mechanism: "Amazon EKS hosts a public OIDC discovery endpoint for each cluster that contains the signing keys for the ProjectedServiceAccountToken JSON web tokens so external systems, such as IAM, can validate and accept the OIDC tokens". IRSA annotates the ServiceAccount with eks.amazonaws.com/role-arn; the role's trust policy allows sts:AssumeRoleWithWebIdentity for that provider and subject. EKS Pod Identity "is a simpler method than IAM roles for service accounts, as this method doesn't use OIDC identity providers": associations are made in the EKS API and an agent DaemonSet serves the credentials. GKE Workload Identity Federation grants IAM roles to principals such as principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/NAMESPACE/sa/KSA_NAME, or links a Kubernetes SA to an IAM service account with iam.gke.io/gcp-service-account; metadata-server requests from Pods are "routed to the GKE metadata server". Azure Workload Identity uses a federated identity credential on a managed identity, the azure.workload.identity/client-id annotation and the Pod label azure.workload.identity/use: "true"; "Only pods with this label are mutated by the azure-workload-identity mutating admission webhook".

text
orders-api reads s3://acme-invoices on EKS with IRSA
1  Pod's SA orders-api is annotated eks.amazonaws.com/role-arn=arn:aws:iam::111122223333:role/orders-api-s3-read
2  EKS webhook adds a projected token (audience sts.amazonaws.com) and the AWS SDK environment for it
3  AWS SDK calls sts:AssumeRoleWithWebIdentity with the token
4  STS fetches the cluster's OIDC JWKS, checks iss, aud, sub=system:serviceaccount:shop:orders-api
5  returns credentials for one role; the SDK refreshes them before expiry
yaml
# Workload identity: the Pod's projected ServiceAccount token (an OIDC JWT
# issued by the cluster) is exchanged for short-lived cloud credentials.
# No cloud access keys in Secrets. One ServiceAccount per workload, so the
# cloud role is as narrow as the Kubernetes one.
#
# AWS EKS, IAM roles for service accounts (IRSA): the IAM role's trust policy
# allows sts:AssumeRoleWithWebIdentity for this cluster's OIDC provider and
# sub = system:serviceaccount:shop:orders-api. (EKS Pod Identity is the newer
# alternative: an association made through the EKS API, no annotation.)
apiVersion: v1
kind: ServiceAccount
metadata:
  name: orders-api
  namespace: shop
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::111122223333:role/orders-api-s3-read
automountServiceAccountToken: false
---
# GKE Workload Identity Federation: either grant IAM roles directly to the
# principal principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/
# global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/shop/sa/orders-api
# (no annotation needed), or link to an IAM service account as below.
apiVersion: v1
kind: ServiceAccount
metadata:
  name: orders-api-gke
  namespace: shop
  annotations:
    iam.gke.io/gcp-service-account: orders-api@acme-prod.iam.gserviceaccount.com
---
# Azure Workload Identity (AKS): the managed identity has a federated identity
# credential for this subject; the Pod must also carry the label
# azure.workload.identity/use: "true" so the webhook injects the token volume
# and AZURE_FEDERATED_TOKEN_FILE.
apiVersion: v1
kind: ServiceAccount
metadata:
  name: orders-api-aks
  namespace: shop
  annotations:
    azure.workload.identity/client-id: 00000000-0000-0000-0000-000000000000

Real scenarios:

  • Laravel queue workers writing to S3: a shop-queue ServiceAccount with IRSA, while the web Pods have no cloud access at all.
  • External Secrets Operator reading AWS Secrets Manager with its own IRSA role.
  • GitHub Actions deploying to the cluster uses the same idea in reverse: the workflow's OIDC token is trusted by the cloud (CI/CD Pipelines).
  • A multi-cluster GKE fleet shares one workload identity pool: identical namespace/SA names in two clusters get the same principal, so namespace naming becomes a security decision.
CloudMechanismKubernetes sideCloud side
AWS EKSIRSASA annotation eks.amazonaws.com/role-arnIAM OIDC provider + role trust policy
AWS EKSPod IdentityNone (association via EKS API), agent DaemonSetRole trusting pods.eks.amazonaws.com
Google GKEWorkload Identity FederationWorkload pool on the cluster; optional iam.gke.io/gcp-service-accountIAM binding to the principal
Azure AKSAzure Workload IdentitySA annotation azure.workload.identity/client-id, Pod label azure.workload.identity/useManaged identity + federated identity credential
Self-managedSame pattern--service-account-issuer reachable OIDC discoveryAny OIDC-federating IAM (Vault, cloud)

Fix: no cloud keys in Secrets; one ServiceAccount and one cloud role per workload; and decide the metadata-endpoint egress per platform. On EKS with IRSA, Pods that do not need the node role can be denied egress to 169.254.169.254. On GKE the metadata address is how Workload Identity delivers credentials, so blocking it breaks it: "If you have a strict cluster network policy in place, you must allow egress ... Allow egress to 169.254.169.252/32 on port 988. For clusters running GKE Dataplane V2, ensure that you allowed egress to 169.254.169.254/32 on port 80." Workloads with no cloud access at all (the Laravel web Pods here) get no metadata egress on any platform.

Pod Security Admission: namespace labels, enforce, audit and warn modes, versions, exemptions Must-know ​

In plain words: A built-in admission plugin checks every Pod against one of the three Pod Security Standards levels, privileged, baseline and restricted, chosen per namespace with labels. What each level forbids is taught in Container Security; this block is about how the labels work.

Common misunderstanding: "Labelling enforce rejects my Deployment." The docs: "audit and warning modes are applied to the workload resources. However, enforce mode is not applied to workload resources, only to the resulting pod objects." The Deployment is accepted, and its Pods are rejected later in the ReplicaSet's events.

Definition: Pod Security Standards privileged baseline restricted are cumulative levels; Pod Security Admission (stable since v1.25) reads pod-security.kubernetes.io/<MODE>: <LEVEL> and optional pod-security.kubernetes.io/<MODE>-version: <VERSION> ("VERSION must be a valid Kubernetes minor version, or latest"). Modes: "enforce: Policy violations will cause the pod to be rejected"; "audit: Policy violations will trigger the addition of an audit annotation to the event recorded in the audit log, but are otherwise allowed"; "warn: Policy violations will trigger a user-facing warning, but are otherwise allowed". Exemptions are static, in the PodSecurityConfiguration passed via --admission-control-config-file: usernames, runtime classes and namespaces; "Requests meeting exemption criteria are ignored by the Admission Controller (all enforce, audit and warn behaviors are skipped)." The same file sets defaults for unlabelled namespaces, which are privileged out of the box.

text
kubectl label ns payments pod-security.kubernetes.io/enforce=restricted --dry-run=server --overwrite
1  API server evaluates existing Pods in payments against restricted:latest
2  prints warnings per Pod that would be rejected; nothing changes (dry run)
3  set warn=restricted + audit=restricted, keep enforce=baseline; fix manifests until warnings stop
4  set enforce=restricted, enforce-version=v1.37 (pinned), commit the Namespace manifest via GitOps
5  only patch-namespaces holders can undo it: keep that verb with the platform team
yaml
# Pod Security Admission is configured per namespace with labels:
#   pod-security.kubernetes.io/<MODE>: <LEVEL>          MODE = enforce | audit | warn
#   pod-security.kubernetes.io/<MODE>-version: <VERSION> VERSION = v1.NN | latest
# What each LEVEL (privileged, baseline, restricted) forbids is in the
# Container Security chapter; this file is about where the labels go.
apiVersion: v1
kind: Namespace
metadata:
  name: shop
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: v1.37   # pinned: upgrades do not change it
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: latest     # see what the next version would reject
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/audit-version: latest
---
# A team namespace on its way to restricted: enforce the floor (baseline),
# warn and audit the target (restricted) until the warnings stop.
apiVersion: v1
kind: Namespace
metadata:
  name: payments
  labels:
    pod-security.kubernetes.io/enforce: baseline
    pod-security.kubernetes.io/enforce-version: v1.37
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/warn-version: latest
    pod-security.kubernetes.io/audit: restricted
    pod-security.kubernetes.io/audit-version: latest
---
# Node agents (CNI, CSI, log shippers) genuinely need host access. They get
# their own namespace with privileged, and nobody else can create Pods there
# (RBAC), so the exception does not leak to application teams.
apiVersion: v1
kind: Namespace
metadata:
  name: node-agents
  labels:
    pod-security.kubernetes.io/enforce: privileged
    pod-security.kubernetes.io/enforce-version: v1.37
    pod-security.kubernetes.io/warn: baseline
    pod-security.kubernetes.io/warn-version: latest
yaml
# kube-apiserver --admission-control-config-file=/etc/kubernetes/admission-configuration.yaml
# Cluster-wide PSA defaults for namespaces WITHOUT labels, and the exemptions.
# Managed clusters (EKS, GKE, AKS) do not let you pass this file; use labels.
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
  - name: PodSecurity
    configuration:
      apiVersion: pod-security.admission.config.k8s.io/v1
      kind: PodSecurityConfiguration
      # The built-in default is privileged everywhere. Raising it to baseline
      # means a forgotten namespace label fails safe instead of open.
      defaults:
        enforce: "baseline"
        enforce-version: "latest"
        audit: "restricted"
        audit-version: "latest"
        warn: "restricted"
        warn-version: "latest"
      exemptions:
        # Exempt requests skip enforce, audit and warn entirely. Keep these
        # lists short and review them: an exempt namespace is a hole.
        usernames: []
        runtimeClasses: []
        namespaces: ["kube-system"]

Real scenarios:

  • Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false on every kubectl apply in a namespace with warn=restricted: the migration signal working as designed.
  • A CNI DaemonSet in kube-system needs host networking: privileged namespace or an exemption, never a lower level for application namespaces.
  • A team with edit relabels its namespace to privileged: impossible, because edit cannot patch Namespace objects; admin cannot write "to the namespace itself" either.
  • After a cluster upgrade, enforce-version: latest starts rejecting Pods that the new version's restricted level forbids; pinned versions do not move.
ModeEffect on PodsEffect on Deployments etc.Where you see it
enforceRejectedNot evaluated (accepted)ReplicaSet events: FailedCreate ... violates PodSecurity
warnAllowedEvaluatedkubectl warning lines
auditAllowedEvaluatedAudit event annotation pod-security.kubernetes.io/audit-violations
ExemptionSkipped entirelySkippedpod_security_exemptions_total metric

Fix: every application namespace enforce: restricted pinned plus warn/audit at latest; a non-privileged cluster default in the admission configuration where you control the API server; exemptions reviewed like firewall rules.

Admission webhooks: ValidatingWebhookConfiguration, MutatingWebhookConfiguration, failurePolicy Important ​

In plain words: A webhook is an HTTPS service that the API server calls during admission with the object, and that answers "allow", "deny", or "allow with this JSON patch". Policy engines and sidecar injectors are webhooks.

Common misunderstanding: "failurePolicy: Ignore is the safe choice." It is the available choice: when the webhook is down, the request proceeds as if the policy did not exist. For a security policy that is fail-open. Fail is the safe choice for security and the dangerous one for availability; which one you need depends on what the webhook protects.

Definition: MutatingWebhookConfiguration and ValidatingWebhookConfiguration register webhooks with rules (operations, API groups, versions, resources, scope), namespaceSelector, objectSelector and up to 64 CEL matchConditions ("for failurePolicy: Fail, reject the request (without calling the webhook)" if a match condition errors). "The default failurePolicy for an admission webhooks is Fail"; "Ignore means that an error calling the webhook is ignored and the API request is allowed to continue." "The timeout for an admission webhook defaults to 10 seconds." sideEffects declares whether dry runs are safe. Mutating webhooks may set reinvocationPolicy: IfNeeded ("It defaults to Never"). An explicit rejection "always denies the API request, regardless of the failurePolicy setting." The good-practices page lists the self-lockout traps: webhooks that intercept their own namespace or kube-system.

text
The policy webhook's Pods are all evicted during a node upgrade (failurePolicy: Fail, no namespaceSelector)
1  kube-scheduler can still bind Pods, but every Pod CREATE calls the webhook -> connection refused
2  the webhook's own Deployment cannot recreate its Pods (they are Pods too) -> deadlock
3  fix during the incident: kubectl delete validatingwebhookconfiguration <name> (needs that RBAC)
4  fix for good: exclude kube-system and the webhook's namespace, run 3 replicas with a PDB,
   set timeoutSeconds 3-5, matchConditions to skip system ServiceAccounts
yaml
# The two webhook registration kinds, with the settings that decide whether a
# broken webhook takes the cluster down (failurePolicy, timeoutSeconds,
# namespaceSelector, matchConditions). Policy engines install objects like
# these for you; read theirs with:
#   kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations -o yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: acme-sidecar-injector
webhooks:
  - name: inject.sidecar.acme.io
    admissionReviewVersions: ["v1"]
    sideEffects: None
    reinvocationPolicy: IfNeeded     # run again if a later mutation changes the Pod
    failurePolicy: Ignore             # a missing sidecar is better than no Pods at all
    timeoutSeconds: 3                 # default 10; admission latency adds up
    clientConfig:
      service:
        name: sidecar-injector
        namespace: platform-system
        path: /mutate
      caBundle: Cg==                  # placeholder: the injector's serving CA
    rules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
        scope: Namespaced
    namespaceSelector:
      matchLabels:
        acme.io/sidecar-injection: enabled
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: acme-image-policy
webhooks:
  - name: images.policy.acme.io
    admissionReviewVersions: ["v1"]
    sideEffects: None
    failurePolicy: Fail               # the default: fail closed, a security check must not skip
    timeoutSeconds: 5
    clientConfig:
      service:
        name: image-policy
        namespace: platform-system
        path: /validate
      caBundle: Cg==
    rules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
    # Never call ourselves for the namespaces the webhook and the control
    # plane run in: otherwise a dead webhook blocks its own restart.
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: ["kube-system", "platform-system"]
    # Skip requests from node agents' ServiceAccounts without a network call.
    matchConditions:
      - name: not-node-agents
        expression: "!request.userInfo.username.startsWith('system:serviceaccount:node-agents:')"

Real scenarios:

  • Istio or Linkerd injecting sidecars (mutating, Ignore is acceptable because a Pod without a sidecar is still a Pod).
  • Kyverno and Gatekeeper validating (security: Fail, with the exclusions above).
  • Gatekeeper's docs: "Gatekeeper is defaulting to using failurePolicy: Ignore for admission request webhook errors. The impact of this is that when the webhook is down, or otherwise unreachable, constraints will not be enforced."
  • A slow webhook adding 2 seconds to every kubectl apply, multiplied by every controller write.
SettingDefaultSecurity webhookConvenience webhook
failurePolicyFailFailIgnore
timeoutSeconds103-51-3
namespaceSelectorallexclude kube-system and its ownopt-in label
matchConditionsnoneskip system usersnarrow to relevant objects
sideEffects(required)NoneNone or NoneOnDryRun
Replicas / PDB—≥ 2 replicas, PDB≥ 2

Fix: prefer in-process policies (PSA, ValidatingAdmissionPolicy) when they can express the rule; for webhooks, fail closed with exclusions and redundancy, and monitor admission latency through the API server's admission webhook metrics.

ValidatingAdmissionPolicy and CEL (and MutatingAdmissionPolicy) Must-know ​

In plain words: Write the rule as a short expression in CEL (Common Expression Language) and the API server evaluates it itself. No extra service to deploy, nothing to time out.

Common misunderstanding: "Creating the policy enforces it." A policy does nothing until bound: "At least a ValidatingAdmissionPolicy and a corresponding ValidatingAdmissionPolicyBinding must be defined for a policy to have an effect." The binding also decides the action.

Definition: ValidatingAdmissionPolicy (admissionregistration.k8s.io/v1, "Stable since Kubernetes v1.30") has matchConstraints, optional paramKind, matchConditions, variables (lazily evaluated, can refer to earlier variables) and validations with expression, message or messageExpression and reason. Expressions see object, oldObject, request, params, namespaceObject, authorizer and variables. The binding's validationActions are "Deny: Validation failure results in a denied request", "Warn: Validation failure is reported to the request client", "Audit: Validation failure is included in the audit event"; "Deny and Warn may not be used together". failurePolicy handles CEL errors and missing params. MutatingAdmissionPolicy ("Stable since Kubernetes v1.36") does the same for mutations "with an apply configuration that is merged using the server side apply merge strategy, or a JSON patch".

text
kubectl apply deployment orders-api (image ghcr.io/acme/orders-api:latest) in shop, binding [Warn, Audit]
1  matchConstraints: apps/v1 deployments CREATE -> policy acme-pod-rules applies
2  binding matchResources: namespace shop not excluded -> evaluate
3  variables.podSpec = object.spec.template.spec; variables.containers = containers + initContainers
4  validation 2 (disallow latest tag) -> false -> messageExpression builds the image list
5  Warn: kubectl prints "Warning: Validation failed for ValidatingAdmissionPolicy ..."; Audit: annotation in the audit event
6  request succeeds (no Deny yet); switch the binding to [Deny] once the warnings stop
yaml
# ValidatingAdmissionPolicy (admissionregistration.k8s.io/v1, stable since
# v1.30): CEL evaluated inside kube-apiserver, no webhook to run or to fail.
# Three rules most clusters want on top of Pod Security Admission:
# require non-root, disallow the latest tag, require resource limits.
# Matches Pods AND the workload kinds, so `kubectl apply` of a bad Deployment
# fails at once instead of a ReplicaSet failing silently later.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: acme-pod-rules.acme.io
spec:
  failurePolicy: Fail            # a CEL runtime error rejects; there is no network to fail
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments", "statefulsets", "daemonsets"]
      - apiGroups: ["batch"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["jobs"]
  variables:
    - name: podSpec
      expression: "object.kind == 'Pod' ? object.spec : object.spec.template.spec"
    - name: containers
      expression: "variables.podSpec.containers + variables.podSpec.?initContainers.orValue([])"
    - name: podNonRoot
      expression: "variables.podSpec.?securityContext.?runAsNonRoot.orValue(false)"
  validations:
    # require non-root: every container is non-root, by its own setting or the Pod's
    - expression: >-
        variables.containers.all(c,
          c.?securityContext.?runAsNonRoot.orValue(variables.podNonRoot) &&
          c.?securityContext.?runAsUser.orValue(variables.podSpec.?securityContext.?runAsUser.orValue(1)) != 0)
      message: "containers must set runAsNonRoot: true and must not run as UID 0"
      reason: Forbidden
    # disallow latest tag: an explicit tag that is not latest, or a digest
    - expression: >-
        variables.containers.all(c,
          c.image.contains('@sha256:') ||
          (c.image.substring(c.image.lastIndexOf('/') + 1).contains(':') &&
           !c.image.endsWith(':latest')))
      messageExpression: >-
        'image tag missing or latest: ' + variables.containers.filter(c,
          !c.image.contains('@sha256:') &&
          (!c.image.substring(c.image.lastIndexOf('/') + 1).contains(':') ||
           c.image.endsWith(':latest'))).map(c, c.image).join(', ')
    # require limits: memory limit and cpu/memory requests on app containers
    - expression: >-
        variables.podSpec.containers.all(c,
          has(c.resources) && has(c.resources.limits) && 'memory' in c.resources.limits &&
          has(c.resources.requests) && 'cpu' in c.resources.requests && 'memory' in c.resources.requests)
      message: "every container needs requests.cpu, requests.memory and limits.memory"
---
# The binding decides WHERE and HOW. Roll out as [Warn, Audit] first: users
# see warnings on kubectl apply and the audit log records each failure;
# then switch to [Deny]. (Deny and Warn together are not allowed.)
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: acme-pod-rules-app-namespaces.acme.io
spec:
  policyName: acme-pod-rules.acme.io
  validationActions: [Warn, Audit]
  matchResources:
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: ["kube-system", "node-agents"]

Real scenarios:

  • Replacing a small Gatekeeper template ("every Deployment has an owner label") with a VAP and removing a webhook from the critical path.
  • Per-namespace limits through paramKind (a ConfigMap or CRD per team) and one binding per team.
  • Protecting platform objects: deny deletion of Namespaces labelled acme.io/protected unless authorizer says the user is in the platform group.
  • Kyverno can generate VAPs from its own policies (spec.autogen) so the rule runs in-process.
ConcernValidatingAdmissionPolicyWebhook policy engine
AvailabilityIn process; no networkSeparate Deployment, timeouts
LanguageCELRego (Gatekeeper), CEL/YAML (Kyverno)
MutationMutatingAdmissionPolicy (v1.36)Yes
External data (registries, signatures)NoYes
Reports on existing objectsNo (admission time only)Background scans, PolicyReports, Gatekeeper audit
Rollout[Warn, Audit] → [Deny]Audit/dryrun → Enforce/deny

Fix: the require non-root, disallow latest tag and require limits rules above are VAP-sized; reach for an engine only for what CEL in the API server cannot do. Test expressions in the CEL playground and roll out with [Warn, Audit].

Policy engines: Kyverno (ClusterPolicy, ValidatingPolicy) and OPA Gatekeeper (ConstraintTemplate) Important ​

In plain words: A policy engine is a webhook plus a library of rules written as Kubernetes objects. Kyverno writes rules in YAML and CEL; Gatekeeper writes them in Rego. Both also scan what is already running and report violations.

Common misunderstanding: "Kyverno policies are kind: ClusterPolicy." That is the older API; the Kyverno 1.18 docs list "ClusterPolicy Deprecated" and present ValidatingPolicy, MutatingPolicy, GeneratingPolicy, DeletingPolicy and ImageValidatingPolicy (policies.kyverno.io/v1). Existing ClusterPolicies keep working and are what most blog posts and charts still show, so you will read both. (The Kyverno ClusterPolicy shape: rules with match, exclude and one of validate, mutate, generate, verifyImages.)

Definition: Kyverno: "A ValidatingPolicy is a superset of a ValidatingAdmissionPolicy", adding background scans, exceptions and autogen for Pod controllers. In ClusterPolicy terms, "mutation rules are applied before validation rules", validation failureAction is Enforce or Audit, and "namespaced policies cannot override or modify behaviors described in a cluster-wide policy". OPA Gatekeeper (v3.23): "Validation uses ConstraintTemplate and Constraint resources"; "Before you can define a constraint, you must first define a ConstraintTemplate, which describes both the Rego that enforces the constraint and the schema of the constraint." A Constraint's enforcementAction defaults to deny; dryrun and warn are the other values; the audit controller evaluates existing resources, and "By default, all constraints are opted-in audit". The gatekeeper-library ships ready templates (k8sdisallowedtags, k8scontainerlimits, the PSP-equivalent set).

text
Rolling out "disallow latest tag" with Gatekeeper on a live cluster
1  apply ConstraintTemplate k8sdisallowedtags (creates the CRD kind K8sDisallowedTags)
2  apply Constraint no-latest-in-app-namespaces with enforcementAction: dryrun
3  audit controller writes violations to the Constraint's status every audit interval
4  teams fix manifests; kubectl get k8sdisallowedtags -o yaml shows totalViolations: 0
5  switch to enforcementAction: deny; new :latest Pods are rejected at admission
yaml
# Kyverno ValidatingPolicy (policies.kyverno.io/v1): the same CEL model as the
# built-in ValidatingAdmissionPolicy, plus background scans, PolicyReports and
# exceptions. Adapted from the kyverno/policies library (best-practices-vpol/
# disallow-latest-tag, require-pod-requests-limits; pod-security-vpol/
# require-run-as-nonroot), with the library's exceptions.* terms removed.
# Kyverno autogenerates the Deployment/StatefulSet/Job variants from a Pod rule.
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: acme-pod-rules
spec:
  validationActions: [Audit]       # step 1: report only; step 2: [Deny]
  evaluation:
    background:
      enabled: true                # also scan what is already running
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [CREATE, UPDATE]
        resources: [pods]
    namespaceSelector:
      matchExpressions:
        - key: kubernetes.io/metadata.name
          operator: NotIn
          values: [kube-system, kyverno, node-agents]
  variables:
    - name: allContainers
      expression: >-
        object.spec.containers + object.spec.?initContainers.orValue([])
  validations:
    - expression: >-
        variables.allContainers.all(c,
          c.?securityContext.?runAsNonRoot.orValue(
            object.spec.?securityContext.?runAsNonRoot.orValue(false)) == true)
      message: "Running as root is not allowed: set securityContext.runAsNonRoot to true."
    - expression: >-
        variables.allContainers.all(c,
          c.image.substring(c.image.lastIndexOf('/') + 1).contains(':') ||
          c.image.contains('@'))
      message: "An image tag is required."
    - expression: >-
        variables.allContainers.all(c, !c.image.endsWith(':latest'))
      message: "Using a mutable image tag e.g. 'latest' is not allowed."
    - expression: >-
        object.spec.containers.all(c,
          has(c.resources) && has(c.resources.requests) &&
          has(c.resources.requests.memory) && has(c.resources.requests.cpu) &&
          has(c.resources.limits) && has(c.resources.limits.memory))
      message: "CPU and memory resource requests and memory limits are required for containers."
yaml
# OPA Gatekeeper: a ConstraintTemplate (Rego + the parameter schema) and a
# Constraint that applies it. The template is copied unchanged from the
# gatekeeper-library (library/general/disallowedtags/template.yaml, v1.0.2);
# The library publishes it in Rego v0 syntax (Gatekeeper v3.23 bundles OPA v1.17).
# Roll out with enforcementAction: dryrun (audit only), then deny.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: k8sdisallowedtags
  annotations:
    metadata.gatekeeper.sh/title: "Disallow tags"
    metadata.gatekeeper.sh/version: 1.0.2
    description: >-
      Requires container images to have an image tag different from the ones in
      the specified list.

      https://kubernetes.io/docs/concepts/containers/images/#image-names
spec:
  crd:
    spec:
      names:
        kind: K8sDisallowedTags
      validation:
        # Schema for the `parameters` field
        openAPIV3Schema:
          type: object
          properties:
            exemptImages:
              description: >-
                Any container that uses an image that matches an entry in this list will be excluded
                from enforcement. Prefix-matching can be signified with `*`. For example: `my-image-*`.
                It is recommended that users use the fully-qualified Docker image name (e.g. start with a domain name)
                in order to avoid unexpectedly exempting images from an untrusted repository.
              type: array
              items:
                type: string
            tags:
              type: array
              description: Disallowed container image tags.
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sdisallowedtags

        import data.lib.exempt_container.is_exempt

        violation[{"msg": msg}] {
            container := input_containers[_]
            not is_exempt(container)
            tags := [tag_with_prefix | tag := input.parameters.tags[_]; tag_with_prefix := concat(":", ["", tag])]
            strings.any_suffix_match(container.image, tags)
            msg := sprintf("container <%v> uses a disallowed tag <%v>; disallowed tags are %v", [container.name, container.image, input.parameters.tags])
        }

        violation[{"msg": msg}] {
            container := input_containers[_]
            not is_exempt(container)
            parts := split(container.image, "/")
            not contains(parts[count(parts) - 1], ":")
            msg := sprintf("container <%v> didn't specify an image tag <%v>", [container.name, container.image])
        }

        input_containers[c] {
            c := input.review.object.spec.containers[_]
        }
        input_containers[c] {
            c := input.review.object.spec.initContainers[_]
        }
        input_containers[c] {
            c := input.review.object.spec.ephemeralContainers[_]
        }
      libs:
        - |
          package lib.exempt_container

          is_exempt(container) {
              exempt_images := object.get(object.get(input, "parameters", {}), "exemptImages", [])
              img := container.image
              exemption := exempt_images[_]
              _matches_exemption(img, exemption)
          }

          _matches_exemption(img, exemption) {
              not endswith(exemption, "*")
              exemption == img
          }

          _matches_exemption(img, exemption) {
              endswith(exemption, "*")
              prefix := trim_suffix(exemption, "*")
              startswith(img, prefix)
          }

---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDisallowedTags
metadata:
  name: no-latest-in-app-namespaces
spec:
  enforcementAction: dryrun          # then: deny (the default)
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
    excludedNamespaces: ["kube-system", "gatekeeper-system", "node-agents"]
  parameters:
    tags: ["latest"]
    exemptImages: []

Real scenarios:

  • A platform team installs Kyverno with Helm, keeps policies in Git, and Argo CD syncs them; violations show up as Argo CD sync failures.
  • Gatekeeper chosen because the security team already writes Rego for Terraform plans (conftest) and CI.
  • Kyverno generate (now GeneratingPolicy) creating a default-deny NetworkPolicy in every new namespace.
  • Policy tests in CI: kyverno test and Gatekeeper's gator verify run policies against fixtures before merge.
KyvernoOPA GatekeeperValidatingAdmissionPolicy
LanguageCEL (current), JMESPath patterns (legacy ClusterPolicy)RegoCEL
Mutation / generationYes / yesMutation (Assign), no generationMutatingAdmissionPolicy
Image signaturesImageValidatingPolicy, verifyImagesVia external data providersNo
Existing-object reportsPolicyReportsAudit status on ConstraintsNo
Default failure modeConfigurable per policyIgnore per its docsIn process
CLI for CIkyverno testgatorkubectl --dry-run=server

Fix: pick one engine per cluster; PSA for the floor, VAP for simple rules, the engine for signatures, mutation and reports; every policy goes Audit → Enforce with a dated plan.

Supply-chain admission: image signature verification with cosign and Kyverno verifyImages Important ​

In plain words: CI signs every image it builds; the cluster refuses to run images that are not signed by your CI. A stolen registry password then is not enough to get code into production.

Common misunderstanding: "We verify signatures in CI, so the cluster is covered." CI is not the only path into the cluster: a human with edit can kubectl set image to anything. Verification must happen at admission, by digest, because a signature covers a digest and a tag can be moved after verification.

Definition: cosign keyless signing (Sigstore) binds a signature to an OIDC identity (for GitHub Actions, issuer https://token.actions.githubusercontent.com and the workflow path as subject) with a short-lived Fulcio certificate and a Rekor transparency-log entry. Kyverno's ImageValidatingPolicy declares matchImageReferences, attestors (cosign keyless identities, keys, notary certificates) and CEL validations calling verifyImageSignatures(image, [attestors.cosign]); validationConfigurations.mutateDigest "Mutates image tags to digests (recommended to avoid mutable tags)" and verifyDigest "Ensures that images are verified with a digest instead of tags". In legacy ClusterPolicy terms this is a Kyverno verifyImages rule with imageReferences and attestors.entries.keyless (subject, issuer, rekor.url); "The rule mutates matching images to add the image digest, when mutateDigest is set to true (which is the default)".

text
Pod with ghcr.io/acme/orders-api:1.4.2 created in shop
1  Kyverno ImageValidatingPolicy matches ghcr.io/acme/*
2  resolve tag -> digest sha256:D; fetch cosign signature for D from the registry
3  verify Fulcio cert chain, identity = https://github.com/acme/orders-api/.github/workflows/release.yml@refs/tags/v1.4.2
4  check Rekor inclusion; validation expression true
5  mutate image to ghcr.io/acme/orders-api:1.4.2@sha256:D -> Pod admitted with a pinned digest
yaml
# Image signature verification at admission: only images from ghcr.io/acme
# signed keyless (cosign + Sigstore Fulcio/Rekor) by this organisation's
# GitHub Actions release workflow may run. Shape taken from the Kyverno
# ImageValidatingPolicy docs (Cosign Keyless Verification sample).
apiVersion: policies.kyverno.io/v1
kind: ImageValidatingPolicy
metadata:
  name: verify-acme-images
spec:
  validationActions: [Deny]
  failurePolicy: Fail                # registry or Rekor unreachable -> reject (fail closed)
  webhookConfiguration:
    timeoutSeconds: 15               # signature lookups are network calls
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  matchImageReferences:
    - glob: "ghcr.io/acme/*"
    # lab only: lets unsigned-test-pod.yaml prove the rejection with a public,
    # existing, unsigned image; remove in production
    - glob: "ghcr.io/kyverno/test-verify-image:unsigned"
  validationConfigurations:
    mutateDigest: true               # rewrite :1.4.2 to @sha256:... after verifying
    verifyDigest: true
    required: true
  attestors:
    - name: cosign
      cosign:
        keyless:
          identities:
            - subject: "https://github.com/acme/*/.github/workflows/release.yml@refs/tags/*"
              issuer: "https://token.actions.githubusercontent.com"
        ctlog:
          url: "https://rekor.sigstore.dev"
  validations:
    - expression: >-
        images.containers.map(image, verifyImageSignatures(image, [attestors.cosign])).all(e, e > 0)
      message: "image is not signed by an acme release workflow"
yaml
# The older Kyverno policy kind, still found in most clusters: ClusterPolicy
# (kyverno.io/v1), marked Deprecated in the Kyverno 1.18 docs in favour of
# ValidatingPolicy / ImageValidatingPolicy. Same intent as the two files next
# to this one: verifyImages with cosign keyless, and a pattern-style validate rule.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: acme-legacy-images
spec:
  webhookConfiguration:
    timeoutSeconds: 30
  rules:
    - name: verify-acme-signature
      match:
        any:
          - resources:
              kinds: [Pod]
      verifyImages:
        - imageReferences:
            - "ghcr.io/acme/*"
          failureAction: Enforce
          mutateDigest: true
          attestors:
            - entries:
                - keyless:
                    subject: "https://github.com/acme/*/.github/workflows/release.yml@refs/tags/*"
                    issuer: "https://token.actions.githubusercontent.com"
                    rekor:
                      url: https://rekor.sigstore.dev
    - name: disallow-latest-tag
      match:
        any:
          - resources:
              kinds: [Pod]
      validate:
        failureAction: Audit
        message: "Using a mutable image tag e.g. 'latest' is not allowed."
        pattern:
          spec:
            containers:
              - image: "!*:latest"

Real scenarios:

  • A manual hotfix pushed from a laptop is rejected; the fix has to go through the release workflow.
  • Rekor or the registry is unreachable: failurePolicy: Fail blocks new Pods, so mirror signatures (OCI referrers) with the images and monitor the webhook.
  • A third-party image (ingress-nginx) verified with the vendor's published identity in a second attestor.
  • SBOM or vulnerability-scan attestations required in addition to the signature (verifyAttestationSignatures).
VerifierWhereNotes
Kyverno ImageValidatingPolicy / verifyImagesAdmission webhookcosign and Notary, digest mutation
Sigstore policy-controllerAdmission webhookClusterImagePolicy CRD
Gatekeeper + external data providerAdmission webhooke.g. Ratify
cosign verify in CI/CDPipelineNecessary, not sufficient
Signing (cosign sign in GitHub Actions or GitLab CI)BuildContainer Security owns it

Fix: sign by digest in CI, verify at admission with an identity-pinned policy, mutate to digests, and treat a verification outage as a deploy freeze rather than a reason to fail open.

Audit logging: policy levels, stages, backends, what to alert on Must-know ​

In plain words: The API server can write one record per request: who, what, when, from where, and the decision. An audit policy decides which requests are recorded and how much of each.

Common misunderstanding: "Audit is on by default." On a self-managed API server: "You can pass a file with the policy to kube-apiserver using the --audit-policy-file flag. If the flag is omitted, no events are logged." On managed clusters it is a setting (EKS control-plane logging, GKE Cloud Audit Logs, AKS diagnostic settings) that is often off or partial.

Definition: Each request generates events at stages RequestReceived, ResponseStarted ("only generated for long-running requests (e.g. watch)"), ResponseComplete and Panic. "The first matching rule sets the audit level of the event": None ("don't log events that match this rule"), Metadata ("log events with metadata (requesting user, timestamp, resource, verb, etc.) but not request or response body"), Request ("request metadata and body but not response body") and RequestResponse. The audit policy levels None Metadata Request RequestResponse therefore trade detail against volume and against leaking data: a Request level on Secrets writes Secret values into the log. Two audit backends: the log backend ("writes events into the filesystem", --audit-log-path, -maxage, -maxbackup, -maxsize; default mode blocking) and the webhook backend ("sends events to an external HTTP API", batching by default). The docs warn that audit "increases the memory consumption of the API server".

text
An attacker with a stolen token tries to read Secrets and exec into a Pod
1  GET /api/v1/namespaces/payments/secrets          -> 403; audit: Metadata, user=system:serviceaccount:shop:orders-api, code 403
2  POST .../pods/payments-worker-1/exec               -> 403; audit: Metadata, verb=create, resource=pods/exec
3  SIEM rule: >5 403s on secrets or pods/exec from one SA in 5 min -> page on-call
4  on-call: kubectl delete pod orders-api-7d9f (bound token dies), review RBAC, rotate what it touched
yaml
# kube-apiserver --audit-policy-file=/etc/kubernetes/audit-policy.yaml
#               --audit-log-path=/var/log/kubernetes/audit/audit.log
#               --audit-log-maxage=30 --audit-log-maxbackup=10 --audit-log-maxsize=100
# Rules are evaluated in order; the FIRST match sets the level.
# Levels: None < Metadata < Request < RequestResponse.
apiVersion: audit.k8s.io/v1
kind: Policy
omitStages:
  - "RequestReceived"            # one event per request at ResponseComplete is enough
rules:
  # 1. Noise that would dominate the log: health checks and the API discovery.
  - level: None
    nonResourceURLs: ["/healthz*", "/livez*", "/readyz*", "/version", "/openapi*"]
  - level: None
    users: ["system:kube-proxy"]
    verbs: ["watch"]
    resources:
      - group: ""
        resources: ["endpoints", "services"]
  # 2. Secrets, ConfigMaps and TokenRequests: who touched them, NEVER the body
  #    (a Request or RequestResponse level would copy secret values into the log).
  - level: Metadata
    resources:
      - group: ""
        resources: ["secrets", "configmaps", "serviceaccounts/token"]
  # 3. Interactive access to running containers: always worth an alert.
  - level: Metadata
    resources:
      - group: ""
        resources: ["pods/exec", "pods/attach", "pods/portforward", "pods/ephemeralcontainers"]
  # 4. Changes to who-can-do-what: keep the full request and response.
  - level: RequestResponse
    resources:
      - group: "rbac.authorization.k8s.io"
        resources: ["roles", "rolebindings", "clusterroles", "clusterrolebindings"]
      - group: "admissionregistration.k8s.io"
        resources: ["validatingwebhookconfigurations", "mutatingwebhookconfigurations",
                    "validatingadmissionpolicies", "validatingadmissionpolicybindings"]
  # 5. Writes to workloads and namespaces (PSA labels live on Namespace objects).
  - level: Request
    verbs: ["create", "update", "patch", "delete", "deletecollection"]
    resources:
      - group: ""
        resources: ["pods", "services", "namespaces", "serviceaccounts"]
      - group: "apps"
      - group: "batch"
      - group: "networking.k8s.io"
  # 6. Reads of everything else: metadata only, and skip the watch stream noise.
  - level: Metadata
    omitStages:
      - "RequestReceived"

Real scenarios:

  • Alert on exec and secret reads: pods/exec, pods/attach, pods/portforward, pods/ephemeralcontainers, and get/list on secrets by humans; also bindings to cluster-admin, changes to webhook configurations, and Forbidden bursts from one ServiceAccount.
  • Forensics after an incident: which identity created the cryptominer Deployment, and which userAgent and source IP it came from.
  • PSA audit mode and VAP Audit actions add annotations to these events; violations show up without blocking anyone.
  • Volume: Metadata for everything is a sane start; RequestResponse only for RBAC and admission configuration changes.
Backend / platformHow to enableWhere events go
Log backend (self-managed)--audit-policy-file + --audit-log-pathNode file; ship with Fluent Bit, Vector
Webhook backend--audit-webhook-config-fileFalco (k8saudit plugin), a SIEM collector
EKSControl-plane logging type auditCloudWatch Logs
GKECloud Audit Logs (Admin Activity on; Data Access configurable)Cloud Logging
AKSDiagnostic settings kube-audit / kube-audit-adminLog Analytics

Fix: a policy like the one above, Metadata for Secrets (never bodies), alerts on the list above, retention long enough for your incident process (Secure SDLC & Incident Response); querying the logs during debugging is in Kubernetes Observability & Troubleshooting.

NetworkPolicy: default deny, ingress and egress, selectors, ipBlock, DNS egress, CNI support Must-know ​

In plain words: Firewall rules between Pods, written with labels. By default every Pod can talk to every other Pod and to the internet; a NetworkPolicy that selects a Pod turns that Pod into "only what is allowed" for the directions it lists.

Common misunderstanding: "Policies are evaluated in order and the most specific wins." There is no order and no deny: "Network policies do not conflict; they are additive. If any policy or policies apply to a given pod for a given direction, the connections allowed in that direction from that pod is the union of what the applicable policies allow." And a connection needs both sides: "both the egress policy on the source pod and the ingress policy on the destination pod need to allow the connection."

Definition: "By default, a pod is non-isolated for egress; all outbound connections are allowed", and the same for ingress. A Pod becomes isolated for a direction when a policy selecting it has that direction in policyTypes. The ingress egress rules name peers with podSelector (Pods in the policy's namespace), namespaceSelector, both in one entry (Pods with those labels in those namespaces), or ipBlock ("These should be cluster-external IPs, since Pod IPs are ephemeral and unpredictable"), plus ports (with endPort for ranges). The podSelector namespaceSelector ipBlock trio is the whole vocabulary. Every namespace carries the immutable label kubernetes.io/metadata.name. "A default deny-all egress policy also blocks DNS traffic," so DNS egress to kube-dns must be allowed explicitly. Traffic "to and from the node where a Pod is running is always allowed". And CNI support decides everything: "Network policies are implemented by the network plugin."

Namespace shop: default deny both ways, then explicit allowsingress-nginxcontroller Podsnamespace shop default-deny-all: podSelector {} policyTypes [Ingress, Egress]shop-webLaravel, no SA tokenorders-apiGo, reads ConfigMapsshop-mysqlshop-rediskube-dnskube-systemAPI serveripBlock / entityTCP 808033066379all Pods: UDP/TCP 53TCP 443 / 6443Droppedshop-web to the API server, to 169.254.169.254 (cloud metadata), to the internet, to other namespaces;anything into shop-mysql except from web, queue, scheduler. Only if the CNI enforces NetworkPolicy.
text
The one-entry vs two-entry trap (from the docs)
from:
- namespaceSelector: {matchLabels: {user: alice}}
  podSelector: {matchLabels: {role: client}}      -> ONE peer: role=client Pods IN alice's namespaces
from:
- namespaceSelector: {matchLabels: {user: alice}}
- podSelector: {matchLabels: {role: client}}      -> TWO peers: ANY Pod in alice's namespaces, OR role=client here
-> one dash too many opens the namespace; check with kubectl describe networkpolicy
yaml
# Namespace-wide default deny, both directions, then DNS for everyone.
# Requires a network plugin that implements NetworkPolicy (Calico, Cilium,
# AWS VPC CNI with network policy enabled, Azure CNI with Cilium, GKE
# Dataplane V2...). Without one these objects are accepted and do nothing.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: shop
spec:
  podSelector: {}                 # every Pod in the namespace
  policyTypes: [Ingress, Egress]  # isolated in both directions, no rules = nothing allowed
---
# Default-deny egress also blocks DNS. Every Pod may query kube-dns/CoreDNS
# and nothing else on port 53.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns-egress
  namespace: shop
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: kube-system
          podSelector:            # same list item: kube-dns Pods IN kube-system
            matchLabels:
              k8s-app: kube-dns
      ports:
        - {protocol: UDP, port: 53}
        - {protocol: TCP, port: 53}

Real scenarios:

  • An RCE in the Laravel app tries curl http://169.254.169.254/ (cloud credentials) and curl https://kubernetes.default.svc: both dropped by default-deny egress.
  • After applying default deny, everything breaks with "could not resolve host": the DNS egress rule was missing.
  • The API server egress rule for a controller: the API server is not a Pod, and whether an ipBlock matches it after Service NAT is implementation-defined ("connections from pods to Service IPs that get rewritten to cluster-external IPs may or may not be subject to ipBlock-based policies").
  • A policy applied before the CNI has programmed it: "that pod may be started unprotected, and isolation rules will be applied when the NetworkPolicy handling is completed."
CNI / platformKubernetes NetworkPolicyExtras
CalicoYesNetworkPolicy/GlobalNetworkPolicy (projectcalico.org/v3): order, deny, tiers, host endpoints
CiliumYesCiliumNetworkPolicy: L7 HTTP, DNS toFQDNs, entities (kube-apiserver), deny
AWS VPC CNI (EKS)When its network policy agent is enabledSecurity groups for Pods
GKE Dataplane V2Yes (Cilium-based)FQDN policies (GKE feature)
Azure CNI powered by Cilium (AKS)YesCilium features per tier
Flannel alone, kindnet (older kind)No: objects accepted, ignored—

Fix: default deny both directions in every application namespace, DNS allowed once per namespace, one allow policy per workload for ingress and egress, and a smoke test after every CNI change. Node-level and cloud firewalls are Firewalls, iptables, nftables & Security Groups.

CNI policy extensions: Cilium and Calico, CiliumNetworkPolicy L7, DNS-aware egress Good to know ​

In plain words: The Kubernetes NetworkPolicy API stops at IPs and ports. Cilium and Calico add their own policy kinds for HTTP paths, DNS names, explicit deny rules and cluster-wide defaults.

Common misunderstanding: "L7 rules are free." Cilium's L7 rules "will proxy traffic through a node-local" Envoy instance, adding a hop, CPU, and a dependency on that proxy's availability ("Layer 7 traffic targeted by policies will therefore depend on the availability of the Cilium agent pod" when Envoy is embedded).

Definition: In a CiliumNetworkPolicy L7 rule, "Layer 7 policy rules are embedded into Layer 4 rules": toPorts[].rules.http with method and path ("an extended POSIX regex matched against the path of a request"), or rules.dns with matchName/matchPattern, which also feeds toFQDNs egress rules ("The separate L3 toFQDNs egress rule allows connections to any IPs returned"). Cilium entities include kube-apiserver ("represents both deployments of the kube-apiserver: within the cluster and outside of the cluster"). Calico network policy "provides a richer set of policy capabilities than Kubernetes including: policy ordering/priority, deny rules, and more flexible match rules", with namespaced and global policies. What the Kubernetes API itself cannot do (as of 1.37) includes "Anything TLS related" and "Targeting of services by name".

text
ingress-nginx forwards to orders-api: GET /orders/42 allowed, DELETE /orders/42 refused
1  CiliumNetworkPolicy orders-api-l7 selects orders-api, ingress from the ingress-nginx Pods on 8080 with http rules
2  Cilium redirects that port to the node-local Envoy
3  GET /orders/42 matches method GET, path /orders/.* -> forwarded
4  DELETE /orders/42 -> Envoy returns an HTTP 403 access denied; the app never sees it
yaml
# Cilium extensions over the plain NetworkPolicy API (cilium.io/v2):
#  1. L7 HTTP rules: the ingress controller may call orders-api only with GET /orders/...
#     (enforced by the node-local Envoy proxy Cilium inserts for L7 rules).
#  2. kube-apiserver as an entity instead of an IP for orders-api.
#  3. DNS-aware egress: DNS visibility plus toFQDNs for one external API.
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: orders-api-l7
  namespace: shop
spec:
  description: "ingress-nginx may only GET /orders/* on orders-api"
  endpointSelector:
    matchLabels:
      app.kubernetes.io/name: orders-api
  ingress:
    - fromEndpoints:
        - matchLabels:
            "k8s:io.kubernetes.pod.namespace": ingress-nginx
            app.kubernetes.io/name: ingress-nginx
      toPorts:
        - ports:
            - port: "8080"
              protocol: TCP
          rules:
            http:
              - method: "GET"
                path: "/orders/.*"
  egress:
    - toEntities:
        - kube-apiserver
      toPorts:
        - ports:
            - port: "443"
              protocol: TCP
            - port: "6443"
              protocol: TCP
---
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: shop-web-payments-fqdn
  namespace: shop
spec:
  endpointSelector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  egress:
    - toEndpoints:
        - matchLabels:
            "k8s:io.kubernetes.pod.namespace": kube-system
            "k8s:k8s-app": kube-dns
      toPorts:
        - ports:
            - port: "53"
              protocol: ANY
          rules:
            dns:
              - matchPattern: "*"
    - toFQDNs:
        - matchName: "api.stripe.com"
      toPorts:
        - ports:
            - port: "443"
              protocol: TCP

Real scenarios:

  • Laravel calls the Stripe API: toFQDNs: api.stripe.com instead of an ever-changing CIDR list.
  • A platform-wide metadata-endpoint rule as a Calico GlobalNetworkPolicy that application teams cannot override, written per platform: on EKS with IRSA, deny 169.254.169.254 to every Pod; on GKE with Workload Identity, allow it only to Workload Identity users (169.254.169.252:988, or 169.254.169.254:80 on Dataplane V2) and deny it to the rest.
  • Visibility first: a DNS rule with matchPattern: "*" logs every lookup a namespace makes before you write the allow list.
  • Service-mesh authorisation (Istio, Linkerd) as the alternative L7 layer based on workload identity and mTLS (mTLS & Service Security).
NeedKubernetes NetworkPolicyCiliumCalico
Explicit deny, orderingNoDeny policiesYes (order, tiers)
Cluster-wide policyNoCiliumClusterwideNetworkPolicyGlobalNetworkPolicy
HTTP method/pathNoYes (Envoy)Via Istio integration / application layer policy
DNS namesNotoFQDNsDomain-based rules (check your Calico edition)
API server as a peeripBlock onlytoEntities: [kube-apiserver]Service/host endpoint rules

Fix: write portable Kubernetes NetworkPolicy first; add CNI-specific kinds for FQDN egress and the few L7 rules that matter, knowing they tie you to that CNI.

Secrets access control: Secrets RBAC and encryption at rest Important ​

In plain words: The API server will give a Secret's value to anyone RBAC allows; etcd stores it unencrypted unless configured. Both are separate decisions.

Common misunderstanding: "Secrets are encrypted because they are base64." base64 is an encoding. Encryption at rest is an API server configuration (--encryption-provider-config, ideally a KMS provider); the details, the Secret types and the "list is read" trap are owned by Config, Secrets & Storage, which this block only summarises.

Definition: Secrets RBAC: the good-practices page warns that "list and watch access also effectively allow for users to reveal the Secret contents", and that workload creation grants Secret access by mounting. resourceNames restricts get to named Secrets (a list restricted by name needs a metadata.name field selector). Applications usually need no RBAC on Secrets at all: the kubelet fetches mounted Secrets with its own Node-authorizer identity. The Node authorizer lets a kubelet read only Secrets referenced by Pods bound to its node, and the NodeRestriction admission plugin limits what it may modify.

text
Who can read the Secret shop/orders-db?
1  RBAC: subjects with get on secrets (by name or all) or list/watch on secrets in shop, or cluster-wide
2  anyone who can create Pods in shop (mount it), or exec into a Pod that mounts it
3  the kubelet of a node running a Pod that references it (Node authorizer)
4  anyone with etcd or backup access, unless encryption at rest is on (then: KMS key holders)

Real scenarios:

  • External Secrets Operator needs create/update on Secrets in target namespaces; nothing else should.
  • kubectl get secrets -A in a support role leaks every password in the cluster.
  • An etcd snapshot copied to a laptop: without encryption at rest it contains every Secret in plaintext.
  • Vault agent or the Secrets Store CSI driver avoiding Secret objects entirely.
PrincipalSecrets access it should have
Application PodsNone via RBAC (mounted by kubelet)
Controllers (ESO, cert-manager)Write in their target namespaces
DevelopersNone in production
On-calledit in their namespace (includes Secrets), audited
Platform break-glassEverything, audited, alerted

Fix: no Secrets verbs in application or developer roles, audit Secret reads at Metadata level, encryption at rest with KMS (encryption at rest link: Config, Secrets & Storage).

API server and kubelet hardening; CIS Kubernetes Benchmark and kube-bench Important ​

In plain words: A few API server and kubelet flags decide whether the gates above exist at all. The CIS Kubernetes Benchmark lists them; kube-bench checks them on your nodes.

Common misunderstanding: "Defaults are secure." Some command-line defaults are not: kube-apiserver --authorization-mode "Defaults to AlwaysAllow if --authorization-config is not used", --anonymous-auth "Default: true", --profiling "Default: true"; the kubelet flag --authorization-mode defaults to "AlwaysAllow" and --read-only-port to 10255. kubeadm and the managed services set safe values, and the KubeletConfiguration file defaults are safe (anonymous.enabled: false, webhook.enabled: true, mode: Webhook, readOnlyPort "Default: 0 (disabled)"), which is exactly why a hand-built node started with flags is the dangerous case.

Definition: API server flags anonymous-auth and authorization-mode: --anonymous-auth enables anonymous requests; --authorization-mode=Node,RBAC is the standard order. "Enabling the AlwaysAllow mode bypasses authorization", and --authorization-mode=AlwaysAllow,RBAC "has the same effect as --authorization-mode=AlwaysAllow". Kubelet authentication: with token webhook mode "the kubelet calls the TokenReview API on the configured API server to determine user information from bearer tokens", x509 client certificates (--client-ca-file) cover the API server's own calls, anonymous off; kubelet authorization Webhook "uses the SubjectAccessReview API". Other flags: --kubelet-certificate-authority (verify kubelet serving certs), --encryption-provider-config, --audit-policy-file, --service-account-extend-token-expiration, --enable-admission-plugins=NodeRestriction. kube-bench "checks whether Kubernetes is deployed securely by running the checks documented in the CIS Kubernetes Benchmark", runs as a Job (kubectl apply -f job.yaml), and on EKS only node checks run because "it's not possible to schedule jobs onto the master node". CIS publishes Kubernetes Benchmark 2.1.0 and per-provider variants (EKS 2.1.0, AKS 2.1.0, GKE 2.0.0 at the time of writing).

text
Hardening review of a self-managed kubeadm cluster
1  kubectl apply -f job.yaml (kube-bench as a Job; control-plane checks need it scheduled on a control-plane node)
2  read the [FAIL] and [WARN] lines: e.g. profiling still on, audit-log flags missing, kubelet read-only port open
3  apply apiserver/kube-apiserver-flags.yaml values; static Pod restarts by itself
4  nodes: KubeletConfiguration with anonymous off, Webhook authz, readOnlyPort 0
5  re-run kube-bench; store the report as the evidence for the audit
yaml
# Excerpt of a kubeadm-style static Pod manifest for kube-apiserver
# (/etc/kubernetes/manifests/kube-apiserver.yaml), security flags only.
# Self-managed clusters only: on EKS, GKE and AKS the provider owns these.
apiVersion: v1
kind: Pod
metadata:
  name: kube-apiserver
  namespace: kube-system
spec:
  containers:
    - name: kube-apiserver
      image: registry.k8s.io/kube-apiserver:v1.37.0
      command:
        - kube-apiserver
        # Authorization: Node first (kubelets), then RBAC. Never AlwaysAllow,
        # which is the default when neither this flag nor --authorization-config is set.
        - --authorization-mode=Node,RBAC
        # Authentication: OIDC + anonymous-only-on-health live in this file;
        # it replaces --oidc-* and --anonymous-auth (default true).
        - --authentication-config=/etc/kubernetes/authentication-config.yaml
        - --client-ca-file=/etc/kubernetes/pki/ca.crt
        # ServiceAccount tokens: who issues them and with which keys.
        - --service-account-issuer=https://kubernetes.default.svc.cluster.local
        - --service-account-key-file=/etc/kubernetes/pki/sa.pub
        - --service-account-signing-key-file=/etc/kubernetes/pki/sa.key
        # Default true: admission-injected tokens are silently extended to one
        # year (with a warnafter claim) for old clients. Turn off once nothing
        # reads the token only at start-up.
        - --service-account-extend-token-expiration=false
        # Admission: PSA defaults and exemptions live in this file.
        - --admission-control-config-file=/etc/kubernetes/admission-configuration.yaml
        - --enable-admission-plugins=NodeRestriction
        # Talk to kubelets over verified TLS, as a client the kubelet can authorise.
        - --kubelet-certificate-authority=/etc/kubernetes/pki/ca.crt
        - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
        - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
        # Secrets encrypted in etcd (see the Config, Secrets & Storage chapter).
        - --encryption-provider-config=/etc/kubernetes/encryption-config.yaml
        # Audit: no policy file = no audit events at all.
        - --audit-policy-file=/etc/kubernetes/audit-policy.yaml
        - --audit-log-path=/var/log/kubernetes/audit/audit.log
        - --audit-log-maxage=30
        - --audit-log-maxbackup=10
        - --audit-log-maxsize=100
        # Default true; the CIS Kubernetes Benchmark asks for false.
        - --profiling=false
yaml
# /var/lib/kubelet/config.yaml (KubeletConfiguration). The config-file
# defaults are already safe; the deprecated command-line FLAGS are not
# (--anonymous-auth=true, --authorization-mode=AlwaysAllow,
# --read-only-port=10255), so state the values explicitly and let
# kube-bench check them.
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
authentication:
  anonymous:
    enabled: false               # 401 for unauthenticated calls to :10250
  webhook:
    enabled: true                # bearer tokens checked with TokenReview
    cacheTTL: 2m0s
  x509:
    clientCAFile: /etc/kubernetes/pki/ca.crt   # the API server's client cert
authorization:
  mode: Webhook                  # SubjectAccessReview against RBAC (nodes/proxy, nodes/log, ...)
  webhook:
    cacheAuthorizedTTL: 5m0s
    cacheUnauthorizedTTL: 30s
readOnlyPort: 0                  # no unauthenticated :10255
rotateCertificates: true
serverTLSBootstrap: true

Real scenarios:

  • A scan finds port 10255 open on a node built from an old guide: unauthenticated Pod listings.
  • An exposed API server with system:unauthenticated bound to a custom role: anyone on the internet can call it ("Review bindings for the system:unauthenticated group and remove them where possible").
  • An auditor asks for evidence of CIS compliance: kube-bench (or the Trivy Operator's CIS scan) output on a schedule.
  • On EKS/GKE/AKS the control-plane items are the provider's job; node and RBAC items remain yours.
CheckSelf-managedManaged (EKS / GKE / AKS)
API server flagsYouProvider
Kubelet configYouYou (node images mostly correct)
RBAC, PSA, NetworkPolicy, audit policyYouYou
etcd encryptionYouProvider option (KMS)
CIS scankube-bench job.yamljob-eks.yaml etc., node checks only

Fix: pin these flags in code (kubeadm config, Terraform for managed settings), run kube-bench in CI against new node images and on a schedule against the cluster.

Multi-tenancy: the namespace boundary, hierarchical namespaces, vCluster Good to know ​

In plain words: Several teams or customers on one cluster. The namespace is the unit everything above is scoped to (RBAC, PSA, NetworkPolicy, quotas), so it is the tenant boundary; when that is not enough, give each tenant its own control plane.

Common misunderstanding: "Namespaces isolate tenants." They isolate API objects, and only as far as the policies above are configured. The good-practices page is blunt: "boundaries within a namespace should be considered weak", and the multi-tenancy page reminds that "the kubelet and (unless using virtual control planes) the API service are still shared". CRDs, webhooks and cluster-scoped objects are shared by everyone.

Definition: Multi-tenancy with a namespace boundary means per-tenant namespaces with RoleBindings, PSA labels, default-deny NetworkPolicy, ResourceQuota and LimitRange, plus separate node pools for untrusted tenants. Hierarchical namespaces (the Hierarchical Namespace Controller) let a team create sub-namespaces and propagate RBAC and policies down the tree ("you can create additional namespaces under your team's namespace, even if you don't have cluster-level permission to create namespaces"); its repository is archived under kubernetes-retired, so treat it as a pattern, not a dependency. The virtual control plane per tenant model "extends namespace-based multi-tenancy" with a tenant API server, controller manager and datastore; vCluster implements it: "Each cluster is backed by a dedicated virtualized control plane", running "as a pod in a dedicated namespace" of the host cluster, with shared or private nodes.

text
Onboarding tenant "payments" on a shared cluster
1  platform GitOps repo: Namespace payments with PSA restricted labels, quota, limit range
2  RoleBinding admin -> group oidc:payments-leads; view -> oidc:payments-devs
3  NetworkPolicy default deny + DNS (generated by a Kyverno GeneratingPolicy for every new namespace)
4  payments wants its own CRDs and webhooks -> not on the shared API server: give it a vCluster
5  regulated card data -> separate node pool or separate cluster (vCluster private nodes or a real cluster)

Real scenarios:

  • Internal teams on one cluster: namespaces and the policies of this chapter are enough.
  • Preview environments per pull request: a namespace (or a vCluster) created and destroyed by CI.
  • A SaaS running customer code: separate clusters or virtual clusters on private nodes, never shared namespaces.
  • A team needs cluster-admin "for its operator": a virtual cluster gives it that without giving it the host cluster.
ModelIsolationCostFits
Namespace per teamAPI objects; network with NetworkPolicyLowestTrusted internal teams
Namespace tree (HNC pattern)Same, with delegated sub-namespacesLowLarge orgs (controller archived)
vCluster on shared nodesSeparate API server, CRDs, RBACMediumTeams needing cluster-admin-like control
vCluster on private nodesPlus compute and networkHigherCustomer or regulated tenants
Cluster per tenantEverythingHighestHard multi-tenancy, compliance

Fix: decide the tenancy model explicitly, write it down per tenant class, and automate the namespace bundle so no tenant is created without its RBAC, PSA and NetworkPolicy.

Mechanics ​

How an authorization decision is made ​

With --authorization-mode=Node,RBAC, the Node authorizer answers only for kubelets (users system:node:<name> in system:nodes) and limits them to objects related to their own Pods; for everyone else it has no opinion and RBAC decides. RBAC itself walks ClusterRoleBindings, then the RoleBindings of the request's namespace, and for every subject that matches, every rule of the referenced role, stopping at the first rule that allows. The rule test is four checks ANDed, ported from plugin/pkg/auth/authorizer/rbac/rbac.go and the evaluation helpers (Kubernetes v1.34.1) into the chapter's offline checker:

go
package rbaccheck

// The RBAC rule matching of kube-apiserver, ported from Kubernetes v1.34.1:
// plugin/pkg/auth/authorizer/rbac/rbac.go (RuleAllows) and
// pkg/apis/rbac/v1/evaluation_helpers.go (the *Matches helpers).
// A rule allows a request only if verb, API group, resource (with
// subresource) and name all match; there is no code path that denies.

import (
	"strings"

	rbacv1 "k8s.io/api/rbac/v1"
)

// RuleAllows is rbac.go's RuleAllows over the evaluation helpers.
func RuleAllows(r Request, rule rbacv1.PolicyRule) bool {
	if r.Path == "" {
		combined := r.Resource
		if r.Subresource != "" {
			combined += "/" + r.Subresource
		}
		return verbMatches(rule, r.Verb) && apiGroupMatches(rule, r.APIGroup) &&
			resourceMatches(rule, combined, r.Subresource) && resourceNameMatches(rule, r.Name)
	}
	return verbMatches(rule, r.Verb) && nonResourceURLMatches(rule, r.Path)
}

func verbMatches(rule rbacv1.PolicyRule, verb string) bool {
	for _, v := range rule.Verbs {
		if v == rbacv1.VerbAll || v == verb {
			return true
		}
	}
	return false
}

func apiGroupMatches(rule rbacv1.PolicyRule, group string) bool {
	for _, g := range rule.APIGroups {
		if g == rbacv1.APIGroupAll || g == group {
			return true
		}
	}
	return false
}

func resourceMatches(rule rbacv1.PolicyRule, combined, sub string) bool {
	for _, res := range rule.Resources {
		if res == rbacv1.ResourceAll || res == combined {
			return true
		}
		// "*/scale" matches the scale subresource of every resource
		if sub != "" && len(res) == len(sub)+2 && strings.HasPrefix(res, "*/") && strings.HasSuffix(res, sub) {
			return true
		}
	}
	return false
}

func resourceNameMatches(rule rbacv1.PolicyRule, name string) bool {
	if len(rule.ResourceNames) == 0 {
		return true // an empty list means every name
	}
	for _, n := range rule.ResourceNames {
		if n == name {
			return true
		}
	}
	return false
}

func nonResourceURLMatches(rule rbacv1.PolicyRule, path string) bool {
	for _, u := range rule.NonResourceURLs {
		if u == rbacv1.NonResourceAll || u == path ||
			(strings.HasSuffix(u, "*") && strings.HasPrefix(path, strings.TrimRight(u, "*"))) {
			return true
		}
	}
	return false
}

Three consequences fall out of it: * matches everything in its field (ResourceAll, VerbAll, APIGroupAll); an empty resourceNames list matches every name ("For resourceNames, an empty set means that everything is allowed"); and */scale matches the scale subresource of any resource but not the resource itself. There is no code path that returns "deny", which is the "purely additive" rule in code.

text
Authorizer chain for: user system:node:worker-3 GET secret shop/orders-db
1  Node authorizer: is a Pod bound to worker-3 referencing secret orders-db? yes -> ALLOW (stop)
Authorizer chain for: user oidc:jane GET secret shop/orders-db
1  Node authorizer: not a node -> no opinion
2  RBAC: bindings for oidc:jane / oidc:shop-developers in shop -> view has no secrets -> no opinion
3  no more authorizers -> 403: User "oidc:jane@acme.example" cannot get resource "secrets" ... in the namespace "shop"

The ServiceAccount token, byte for byte ​

The documented payload of a Pod-bound token (from the "Configure Service Accounts for Pods" task page):

json
{
  "aud": ["https://kubernetes.default.svc"],
  "exp": 1731613413,
  "iat": 1700077413,
  "iss": "https://kubernetes.default.svc",
  "jti": "ea28ed49-2e11-4280-9ec5-bc3d1d84661a",
  "kubernetes.io": {
    "namespace": "kube-system",
    "node": {"name": "127.0.0.1", "uid": "58456cb0-dd00-45ed-b797-5578fdceaced"},
    "pod": {"name": "coredns-69cbfb9798-jv9gn", "uid": "778a530c-b3f4-47c0-9cd5-ab018fb64f33"},
    "serviceaccount": {"name": "coredns", "uid": "a087d5a0-e1dd-43ec-93ac-f13d89cd13af"},
    "warnafter": 1700081020
  },
  "nbf": 1700077413,
  "sub": "system:serviceaccount:kube-system:coredns"
}

Do the arithmetic: exp − iat = 31,536,000 s (365 days), while warnafter − iat = 3,607 s. The admin reference shows the injected volume requesting expirationSeconds: 3607, and the kube-apiserver flag explains the year: --service-account-extend-token-expiration (default true) means "admission injected tokens would be extended up to 1 year to prevent unexpected failure during transition". The token is valid for a year, but a client still presenting it after warnafter is one that never re-reads its token file: exactly the client the extension exists to protect, and the one to fix before turning the flag off. A projected volume you declare yourself (like orders-api-deployment.yaml) is not "admission injected", so its 600 seconds are real; setting the flag to false makes the default ones real too. jti identifies the token in audit logs, kubernetes.io.pod.uid is what "bound" means (the API server rejects the token once that Pod is gone), and aud is why a token for vault is useless against the API server.

Admission, in the order it runs ​

The plugins enabled by default in v1.37 (from --enable-admission-plugins help): NamespaceLifecycle, LimitRanger, ServiceAccount, TaintNodesByCondition, PodSecurity, Priority, DefaultTolerationSeconds, DefaultStorageClass, StorageObjectInUseProtection, PodGroupProtection, PersistentVolumeClaimResize, RuntimeClass, CertificateApproval, CertificateSigning, ClusterTrustBundleAttest, CertificateSubjectRestriction, DefaultIngressClass, PodTopologyLabels, NodeDeclaredFeatureValidator, PodResizeValidator, MutatingAdmissionPolicy, MutatingAdmissionWebhook, ValidatingAdmissionPolicy, ValidatingAdmissionWebhook, ResourceQuota. NodeRestriction is not in that list and must be added (kubeadm does).

text
1  mutating phase: built-in mutators (ServiceAccount injects kube-api-access-*, DefaultTolerationSeconds,
   LimitRanger defaults), then MutatingAdmissionPolicy, then MutatingAdmissionWebhook (reinvoked if IfNeeded)
2  object schema validation (types, required fields, immutable fields)
3  validating phase: PodSecurity, ValidatingAdmissionPolicy, ValidatingAdmissionWebhook,
   ResourceQuota last in the plugin list (it increments usage)
4  any rejection anywhere -> whole request rejected; quota usage is reconciled later

Policies and configuration files in this chapter ​

FileKindApplied by
k8s/rbac/before-overgrant.yamlThe anti-patterns, for the linterNobody (teaching)
k8s/rbac/orders-api-rbac.yamlServiceAccount, Role, RoleBindingApp's GitOps repo
k8s/rbac/people-and-ci.yamlRoleBindings for groups, deployer Role, aggregated ClusterRolesPlatform repo
k8s/serviceaccount/orders-api-deployment.yamlDeployment with projected tokensApp repo
k8s/psa/namespaces.yamlNamespaces with PSA labelsPlatform repo
k8s/admission/*.yamlVAP + binding, webhook configurationsPlatform repo
k8s/kyverno/*.yaml, k8s/gatekeeper/*.yamlPolicy-engine policiesPlatform repo (one engine)
k8s/netpol/*.yamlNetworkPolicy, CiliumNetworkPolicyApp repo (allows), platform repo (default deny)
apiserver/*.yamlAuthentication, admission, audit, kubelet configs, API server flagsNode provisioning (kubeadm, Ansible, Terraform)

Knobs ​

KnobWhereDefaultNotes
--authorization-modekube-apiserverAlwaysAllow if no --authorization-configUse Node,RBAC
--anonymous-authkube-apiserver / kubelet flagtrueOr anonymous.conditions in AuthenticationConfiguration
--authentication-configkube-apiserverunsetStable v1.34; excludes --oidc-*
jwt authenticatorsAuthenticationConfiguration—Max 64
--service-account-extend-token-expirationkube-apiservertrueInjected tokens valid 1 year
--service-account-max-token-expirationkube-apiserverunsetCaps TokenRequest durations
expirationSecondsprojected token3600Minimum 600
Kubelet token refreshkubelet80 % of TTL or 24 hNot configurable
Legacy token invalidationkube-controller-manager1 year unusedSince v1.29
Webhook timeoutSecondswebhook configuration10Max 30
Webhook failurePolicywebhook configurationFailGatekeeper installs Ignore
matchConditionswebhook / VAPnoneMax 64 per webhook
validationActionsVAP binding(required)Deny, Warn, Audit; not Deny+Warn
PSA defaultsPodSecurityConfigurationprivileged / latestPer mode
--audit-log-modekube-apiserverblockingbatch is the webhook default
--audit-webhook-batch-max-size / -max-waitkube-apiserver400 / 30 sBatch mode only
Kubelet authentication.anonymous.enabledKubeletConfigurationfalseFlag default is true
Kubelet authorization.modeKubeletConfigurationWebhookFlag default AlwaysAllow
Kubelet readOnlyPortKubeletConfiguration0Flag default 10255
Kubelet webhook cacheKubeletConfigurationauthn 2 m, authz 5 m / 30 sA revoked grant can live that long

Error messages you will actually see ​

MessageGateMeaningFix
error: You must be logged in to the server (Unauthorized)AuthenticationExpired or untrusted credential (401)Refresh the OIDC token; check the issuer/audience
pods is forbidden: User "system:serviceaccount:shop:orders-api" cannot list resource "pods" in API group "" in the namespace "shop"AuthorizationNo binding grants it (403)Add the narrowest rule; check with auth can-i
User "system:anonymous" cannot get path "/"AuthorizationRequest arrived without credentialsFix the client's kubeconfig or token mount
unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be definedclient-goNot in a Pod (rest.ErrNotInCluster)Use kubeconfig locally; in a Pod check the env
open /var/run/secrets/kubernetes.io/serviceaccount/token: no such file or directoryclient-goAutomount off and nothing projectedProject a token or keep the app API-free
Error from server (Forbidden): pods "x" is forbidden: violates PodSecurity "restricted:v1.37": ...Admission (PSA)Pod breaks the levelFix securityContext (see Container Security)
Warning: would violate PodSecurity "restricted:latest": ...Admission (PSA warn)Would be rejected under enforceFix before raising enforce
... is forbidden: ValidatingAdmissionPolicy '...' with binding '...' denied request: ...Admission (VAP)CEL rule false with DenyFix the object or the policy
Internal error occurred: failed calling webhook "...": ... context deadline exceededAdmission (webhook)Webhook slow or down, failurePolicy: FailRestore the webhook; check exclusions
admission webhook "..." denied the request: ...Admission (webhook)Explicit rejection (Kyverno, Gatekeeper)Read the message: it is the policy's
validation error on roleRef when updating a bindingAPI validationroleRef is immutableDelete and recreate, or kubectl auth reconcile
Forbidden on creating a Role or binding, listing the permissions you do not holdRBAC escalation checkCreating a role/binding with more than you haveGet the permission, or escalate/bind (rarely)
dial tcp 10.96.0.10:53: i/o timeout after default denyNetworkPolicyDNS egress not allowedAdd the DNS egress policy

Go ​

orders-api is the Go service of the KB's shop. Besides serving HTTP it reads its feature-flag ConfigMaps (label acme.io/flags=true) from the Kubernetes API at start-up. That single need is the whole RBAC story of the service: list (and watch) ConfigMaps, in its own namespace, nothing else.

Before ​

The common first version: the default ServiceAccount, a ClusterRoleBinding because "it was forbidden", a cluster-wide list, and the namespace hard-coded:

go
// Package before is the first version of orders-api's flag loader that many
// services start with. It compiles and works on day one; each comment says
// what is wrong. The fixed version is the lister package.
package before

import (
	"context"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

// LoadFlags returns the names of the shop ConfigMaps.
func LoadFlags(ctx context.Context) ([]string, error) {
	cfg, err := rest.InClusterConfig() // token of the "default" SA, bound to cluster-admin "to make it work"
	if err != nil {
		return nil, err
	}
	cs := kubernetes.NewForConfigOrDie(cfg) // panics instead of returning an error
	// metav1.NamespaceAll: needs a ClusterRoleBinding, reads every team's ConfigMaps
	list, err := cs.CoreV1().ConfigMaps(metav1.NamespaceAll).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, err // a 403 looks like any other error
	}
	var names []string
	for _, cm := range list.Items {
		if cm.Namespace == "shop" { // hard-coded: breaks in shop-staging
			names = append(names, cm.Name)
		}
	}
	return names, nil
}

and the RBAC objects that usually come with it (each annotated with why it is wrong; rbaccheck flags all nine findings, see the Lab):

yaml
# BEFORE: what many clusters look like after a year. Every object below is
# accepted by the API server; each comment says why it is still wrong.
# (rbaccheck in go/ flags every one of these; see the chapter's Lab.)
apiVersion: v1
kind: ServiceAccount
metadata:
  name: ci-deployer
  namespace: ci
---
# 1. The CI pipeline is cluster-admin: one leaked runner token = the whole
#    cluster, every namespace, every Secret, every node via privileged Pods.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ci-deployer-cluster-admin
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
  - kind: ServiceAccount
    name: ci-deployer
    namespace: ci
---
# 2. A "read-only" role that is not read-only: list/watch on secrets returns
#    the data of every Secret; wildcards also cover resources added later.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: support-readonly
rules:
  - apiGroups: ["*"]
    resources: ["*"]
    verbs: ["get", "list", "watch"]
---
# 3. "Developers need to debug": exec into any Pod in shop, plus create pods,
#    which lets them run as any ServiceAccount and mount any Secret there.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: shop-debug
  namespace: shop
rules:
  - apiGroups: [""]
    resources: ["pods", "pods/exec", "pods/log"]
    verbs: ["get", "list", "create"]
---
# 4. A helper that manages RBAC for teams: escalate and bind defeat the
#    API server's built-in escalation check; impersonate turns this
#    identity into anyone, including members of system:masters.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: team-onboarding
rules:
  - apiGroups: ["rbac.authorization.k8s.io"]
    resources: ["clusterroles", "clusterrolebindings"]
    verbs: ["create", "update", "escalate", "bind"]
  - apiGroups: [""]
    resources: ["users", "groups", "serviceaccounts"]
    verbs: ["impersonate"]
---
# 5. The default ServiceAccount of shop gets edit: every Pod that does not
#    name a ServiceAccount (and automounts its token) inherits it.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: default-sa-edit
  namespace: shop
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: edit
subjects:
  - kind: ServiceAccount
    name: default
    namespace: shop

After ​

The lister package: rest.InClusterConfig and kubernetes.NewForConfig with a user agent and a small QPS, the namespace read from the projected file, a SelfSubjectAccessReview that answers "may I?" before trying, and ErrForbidden wrapping so callers can tell RBAC from network problems:

go
// Package lister is the Kubernetes-facing part of orders-api: it reads the
// ConfigMaps of its OWN namespace with the Pod's ServiceAccount token, and
// nothing else. The RBAC that makes this work (and nothing more) is
// k8s/rbac/orders-api-rbac.yaml.
package lister

import (
	"context"
	"errors"
	"fmt"
	"os"
	"sort"
	"strings"

	authorizationv1 "k8s.io/api/authorization/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
)

// NamespaceFile is where the projected volume puts the Pod's namespace
// (the downwardAPI source of kube-api-access-*, or our own projection).
const NamespaceFile = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"

// ErrForbidden is returned when RBAC denies the call. It wraps the API
// error, so apierrors.IsForbidden still works on it.
var ErrForbidden = errors.New("forbidden by RBAC")

// NamespaceFromFile reads the namespace the Pod runs in. Using it instead
// of a hard-coded "shop" keeps the code correct when the same image is
// deployed to shop-staging.
func NamespaceFromFile(path string) (string, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return "", fmt.Errorf("read namespace: %w", err)
	}
	ns := strings.TrimSpace(string(b))
	if ns == "" {
		return "", fmt.Errorf("read namespace: %s is empty", path)
	}
	return ns, nil
}

// InClusterClient builds a clientset from the Pod's environment:
// KUBERNETES_SERVICE_HOST/PORT, the token file and ca.crt. rest.Config
// re-reads BearerTokenFile periodically, so the kubelet's token rotation
// needs no code here. Outside a Pod it returns rest.ErrNotInCluster.
func InClusterClient(userAgent string) (kubernetes.Interface, error) {
	cfg, err := rest.InClusterConfig()
	if err != nil {
		return nil, err
	}
	cfg.UserAgent = userAgent  // shows up in audit events as userAgent
	cfg.QPS, cfg.Burst = 5, 10 // a config reader needs little; protect the API server
	return kubernetes.NewForConfig(cfg)
}

// Lister lists ConfigMaps in exactly one namespace.
type Lister struct {
	client    kubernetes.Interface
	namespace string
}

// New returns a Lister for namespace ns.
func New(client kubernetes.Interface, ns string) *Lister {
	return &Lister{client: client, namespace: ns}
}

// CanList asks the API server "may I list configmaps here?" with a
// SelfSubjectAccessReview (what kubectl auth can-i does). Every
// authenticated identity may create one about itself. It returns the
// decision and the authorizer's reason.
func (l *Lister) CanList(ctx context.Context) (bool, string, error) {
	review := &authorizationv1.SelfSubjectAccessReview{
		Spec: authorizationv1.SelfSubjectAccessReviewSpec{
			ResourceAttributes: &authorizationv1.ResourceAttributes{
				Namespace: l.namespace,
				Verb:      "list",
				Resource:  "configmaps",
			},
		},
	}
	res, err := l.client.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, review, metav1.CreateOptions{})
	if err != nil {
		return false, "", fmt.Errorf("self subject access review: %w", err)
	}
	return res.Status.Allowed, res.Status.Reason, nil
}

// ConfigMapNames returns the sorted names of the ConfigMaps in the namespace,
// optionally filtered by a label selector such as "acme.io/flags=true".
func (l *Lister) ConfigMapNames(ctx context.Context, labelSelector string) ([]string, error) {
	list, err := l.client.CoreV1().ConfigMaps(l.namespace).List(ctx, metav1.ListOptions{LabelSelector: labelSelector})
	if apierrors.IsForbidden(err) {
		return nil, fmt.Errorf("%w: list configmaps in %q: %w", ErrForbidden, l.namespace, err)
	}
	if err != nil {
		return nil, fmt.Errorf("list configmaps in %q: %w", l.namespace, err)
	}
	names := make([]string, 0, len(list.Items))
	for _, cm := range list.Items {
		names = append(names, cm.Name)
	}
	sort.Strings(names)
	return names, nil
}

The tests use client-go's fake clientset. It does not run RBAC, so they assert what the code asks for (only its own namespace, the right SelfSubjectAccessReview attributes), how it treats a 403 (PrependReactor returning apierrors.NewForbidden), and that outside a Pod it fails with rest.ErrNotInCluster:

go
package lister

import (
	"context"
	"errors"
	"os"
	"path/filepath"
	"reflect"
	"testing"

	authorizationv1 "k8s.io/api/authorization/v1"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/kubernetes/fake"
	"k8s.io/client-go/rest"
	k8stesting "k8s.io/client-go/testing"
)

func cm(ns, name string, labels map[string]string) *corev1.ConfigMap {
	return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: ns, Name: name, Labels: labels}}
}

// The fake clientset does NOT run RBAC; this test only shows that the code
// asks for its own namespace and never for another one.
func TestConfigMapNamesOnlyOwnNamespace(t *testing.T) {
	client := fake.NewClientset(
		cm("shop", "orders-flags", map[string]string{"acme.io/flags": "true"}),
		cm("shop", "kube-root-ca.crt", nil),
		cm("payments", "payments-flags", map[string]string{"acme.io/flags": "true"}),
	)
	l := New(client, "shop")

	got, err := l.ConfigMapNames(context.Background(), "")
	if err != nil {
		t.Fatal(err)
	}
	if want := []string{"kube-root-ca.crt", "orders-flags"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("names = %v, want %v", got, want)
	}

	got, err = l.ConfigMapNames(context.Background(), "acme.io/flags=true")
	if err != nil {
		t.Fatal(err)
	}
	if want := []string{"orders-flags"}; !reflect.DeepEqual(got, want) {
		t.Fatalf("filtered names = %v, want %v", got, want)
	}

	for _, a := range client.Actions() {
		if a.GetNamespace() != "shop" {
			t.Fatalf("request outside own namespace: %s %s in %q", a.GetVerb(), a.GetResource().Resource, a.GetNamespace())
		}
	}
}

// A 403 from the API server (what RBAC returns) becomes ErrForbidden and
// still satisfies apierrors.IsForbidden.
func TestConfigMapNamesForbidden(t *testing.T) {
	client := fake.NewClientset()
	client.PrependReactor("list", "configmaps", func(k8stesting.Action) (bool, runtime.Object, error) {
		return true, nil, apierrors.NewForbidden(schema.GroupResource{Resource: "configmaps"}, "",
			errors.New(`User "system:serviceaccount:shop:orders-api" cannot list resource "configmaps" in API group "" in the namespace "payments"`))
	})
	_, err := New(client, "payments").ConfigMapNames(context.Background(), "")
	if !errors.Is(err, ErrForbidden) {
		t.Fatalf("err = %v, want ErrForbidden", err)
	}
	if !apierrors.IsForbidden(err) {
		t.Fatalf("apierrors.IsForbidden(%v) = false", err)
	}
}

func TestCanList(t *testing.T) {
	for _, tc := range []struct {
		name    string
		allowed bool
		reason  string
	}{
		{"allowed", true, `RBAC: allowed by RoleBinding "orders-api-config-reader/shop"`},
		{"denied", false, ""},
	} {
		t.Run(tc.name, func(t *testing.T) {
			client := fake.NewClientset()
			var seen *authorizationv1.SelfSubjectAccessReview
			client.PrependReactor("create", "selfsubjectaccessreviews", func(a k8stesting.Action) (bool, runtime.Object, error) {
				seen = a.(k8stesting.CreateAction).GetObject().(*authorizationv1.SelfSubjectAccessReview).DeepCopy()
				seen.Status = authorizationv1.SubjectAccessReviewStatus{Allowed: tc.allowed, Reason: tc.reason}
				return true, seen, nil
			})
			ok, reason, err := New(client, "shop").CanList(context.Background())
			if err != nil {
				t.Fatal(err)
			}
			if ok != tc.allowed || reason != tc.reason {
				t.Fatalf("CanList = %v %q, want %v %q", ok, reason, tc.allowed, tc.reason)
			}
			ra := seen.Spec.ResourceAttributes
			if ra.Namespace != "shop" || ra.Verb != "list" || ra.Resource != "configmaps" {
				t.Fatalf("review asked for %+v", *ra)
			}
		})
	}
}

func TestNamespaceFromFile(t *testing.T) {
	dir := t.TempDir()
	p := filepath.Join(dir, "namespace")
	if err := os.WriteFile(p, []byte("shop\n"), 0o600); err != nil {
		t.Fatal(err)
	}
	ns, err := NamespaceFromFile(p)
	if err != nil || ns != "shop" {
		t.Fatalf("NamespaceFromFile = %q, %v", ns, err)
	}
	empty := filepath.Join(dir, "empty")
	if err := os.WriteFile(empty, nil, 0o600); err != nil {
		t.Fatal(err)
	}
	if _, err := NamespaceFromFile(empty); err == nil {
		t.Fatal("empty file: want error")
	}
	if _, err := NamespaceFromFile(filepath.Join(dir, "missing")); err == nil {
		t.Fatal("missing file: want error")
	}
}

// Outside a Pod (no KUBERNETES_SERVICE_HOST/PORT) rest.InClusterConfig fails
// with rest.ErrNotInCluster before it touches the token file.
func TestInClusterClientOutsideCluster(t *testing.T) {
	t.Setenv("KUBERNETES_SERVICE_HOST", "")
	t.Setenv("KUBERNETES_SERVICE_PORT", "")
	_, err := InClusterClient("orders-api/test")
	if !errors.Is(err, rest.ErrNotInCluster) {
		t.Fatalf("err = %v, want rest.ErrNotInCluster", err)
	}
}

The command that runs in the Pod:

go
// config-lister is the in-cluster entry point of orders-api's config
// reader: check the permission once, list the flag ConfigMaps, exit
// non-zero with a clear message if RBAC or the environment is wrong.
// Run it in a Pod whose ServiceAccount is bound by k8s/rbac/orders-api-rbac.yaml.
package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"os"
	"time"

	"academy/kubernetes-security-rbac/lister"

	"k8s.io/client-go/rest"
)

func main() {
	if err := run(); err != nil {
		slog.Error("config-lister failed", "err", err)
		os.Exit(1)
	}
}

func run() error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	client, err := lister.InClusterClient("orders-api/config-lister")
	if errors.Is(err, rest.ErrNotInCluster) {
		return fmt.Errorf("not running in a Pod (or automountServiceAccountToken is false and no token is projected): %w", err)
	}
	if err != nil {
		return err
	}
	ns, err := lister.NamespaceFromFile(lister.NamespaceFile)
	if err != nil {
		return err
	}
	l := lister.New(client, ns)

	ok, reason, err := l.CanList(ctx)
	if err != nil {
		return err
	}
	slog.Info("access review", "namespace", ns, "verb", "list", "resource", "configmaps", "allowed", ok, "reason", reason)
	if !ok {
		return fmt.Errorf("ServiceAccount may not list configmaps in %q: check the RoleBinding", ns)
	}

	names, err := l.ConfigMapNames(ctx, "acme.io/flags=true")
	if err != nil {
		return err
	}
	for _, n := range names {
		fmt.Println(n)
	}
	return nil
}
text
module academy/kubernetes-security-rbac

go 1.24.0

require (
	k8s.io/api v0.34.1
	k8s.io/apimachinery v0.34.1
	k8s.io/client-go v0.34.1
	sigs.k8s.io/yaml v1.6.0
)

require (
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/emicklei/go-restful/v3 v3.12.2 // indirect
	github.com/fxamacker/cbor/v2 v2.9.0 // indirect
	github.com/go-logr/logr v1.4.2 // indirect
	github.com/go-openapi/jsonpointer v0.21.0 // indirect
	github.com/go-openapi/jsonreference v0.20.2 // indirect
	github.com/go-openapi/swag v0.23.0 // indirect
	github.com/gogo/protobuf v1.3.2 // indirect
	github.com/google/gnostic-models v0.7.0 // indirect
	github.com/google/uuid v1.6.0 // indirect
	github.com/josharian/intern v1.0.0 // indirect
	github.com/json-iterator/go v1.1.12 // indirect
	github.com/mailru/easyjson v0.7.7 // indirect
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
	github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/pkg/errors v0.9.1 // indirect
	github.com/x448/float16 v0.8.4 // indirect
	go.yaml.in/yaml/v2 v2.4.2 // indirect
	go.yaml.in/yaml/v3 v3.0.4 // indirect
	golang.org/x/net v0.38.0 // indirect
	golang.org/x/oauth2 v0.27.0 // indirect
	golang.org/x/sys v0.31.0 // indirect
	golang.org/x/term v0.30.0 // indirect
	golang.org/x/text v0.23.0 // indirect
	golang.org/x/time v0.9.0 // indirect
	google.golang.org/protobuf v1.36.5 // indirect
	gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
	gopkg.in/inf.v0 v0.9.1 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
	k8s.io/klog/v2 v2.130.1 // indirect
	k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b // indirect
	k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 // indirect
	sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect
	sigs.k8s.io/randfill v1.0.0 // indirect
	sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect
)

The same logic as a one-shot Job, used in the Lab:

yaml
# The one-shot form of the same logic (go/cmd/config-lister): check the
# permission, list the flag ConfigMaps, exit 0, or exit 1 with a message that
# names the missing RoleBinding. Same ServiceAccount, token projection and
# label as the orders-api Deployment, so orders-api-netpol.yaml applies to it.
apiVersion: batch/v1
kind: Job
metadata:
  name: orders-api-config-check
  namespace: shop
spec:
  backoffLimit: 0                      # a 403 will not fix itself by retrying
  ttlSecondsAfterFinished: 3600
  template:
    metadata:
      labels:
        app.kubernetes.io/name: orders-api
    spec:
      restartPolicy: Never
      serviceAccountName: orders-api
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: config-lister
          # built from go/Dockerfile (ENTRYPOINT /config-lister); the lab replaces the
          # placeholder digest with the one the push printed
          image: ghcr.io/acme/config-lister:1.4.2@sha256:0000000000000000000000000000000000000000000000000000000000000000
          resources:
            requests: {cpu: 10m, memory: 16Mi}
            limits: {memory: 32Mi}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: kube-api-token
              mountPath: /var/run/secrets/kubernetes.io/serviceaccount
              readOnly: true
      volumes:
        - name: kube-api-token
          projected:
            sources:
              - serviceAccountToken:
                  path: token
                  expirationSeconds: 600
              - configMap:
                  name: kube-root-ca.crt
                  items:
                    - key: ca.crt
                      path: ca.crt
              - downwardAPI:
                  items:
                    - path: namespace
                      fieldRef:
                        fieldPath: metadata.namespace

The Deployment of the server itself, with a 600-second projected token at the path rest.InClusterConfig reads and a second token for Vault:

yaml
# orders-api with an explicit, short-lived, audience-bound token.
# The ServiceAccount has automountServiceAccountToken: false; instead of the
# default kube-api-access-* volume we project the same three files ourselves
# at the path rest.InClusterConfig() reads, with a 10-minute lifetime, plus a
# second token whose audience is Vault (useless against the API server).
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  namespace: shop
  labels:
    app.kubernetes.io/name: orders-api
spec:
  replicas: 2
  selector:
    matchLabels:
      app.kubernetes.io/name: orders-api
  template:
    metadata:
      labels:
        app.kubernetes.io/name: orders-api
    spec:
      serviceAccountName: orders-api
      automountServiceAccountToken: false   # we mount our own projected volume below
      securityContext:                      # restricted PSS level (see container-security)
        runAsNonRoot: true
        runAsUser: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: orders-api
          image: ghcr.io/acme/orders-api:1.4.2@sha256:0000000000000000000000000000000000000000000000000000000000000000
          # the HTTP server; it reads its flag ConfigMaps at start-up with the
          # lister package (cmd/config-lister is the same logic as a one-shot Job)
          ports:
            - name: http
              containerPort: 8080
          resources:
            requests: {cpu: 100m, memory: 64Mi}
            limits: {memory: 128Mi}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: kube-api-token
              mountPath: /var/run/secrets/kubernetes.io/serviceaccount
              readOnly: true
            - name: vault-token
              mountPath: /var/run/secrets/tokens
              readOnly: true
      volumes:
        - name: kube-api-token
          projected:
            sources:
              - serviceAccountToken:
                  path: token
                  expirationSeconds: 600      # minimum allowed; kubelet refreshes at 80% of TTL
              - configMap:
                  name: kube-root-ca.crt
                  items:
                    - key: ca.crt
                      path: ca.crt
              - downwardAPI:
                  items:
                    - path: namespace
                      fieldRef:
                        fieldPath: metadata.namespace
        - name: vault-token
          projected:
            sources:
              - serviceAccountToken:
                  path: vault-token
                  audience: vault             # Vault's Kubernetes auth checks this "aud"
                  expirationSeconds: 3600

Its network policy, including the egress the API calls need. On GKE with Workload Identity, workloads with cloud access also need the metadata-server variant; on EKS with IRSA they must not have it:

yaml
# The Go service orders-api: ingress only from the ingress-nginx controller,
# egress to the Kubernetes API server (it lists ConfigMaps) on 443/6443.
# The API server is not a Pod you can select. NetworkPolicy can only name it
# by IP (ipBlock); what IP the plugin sees after the Service VIP is rewritten
# is implementation-defined, so check with your CNI. Cilium has a dedicated
# kube-apiserver entity (see cilium-l7.yaml).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: orders-api
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: orders-api
  policyTypes: [Ingress, Egress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ingress-nginx
          podSelector:
            matchLabels:
              app.kubernetes.io/name: ingress-nginx
      ports:
        - {protocol: TCP, port: 8080}
  egress:
    - to:
        - ipBlock:
            cidr: 10.0.0.1/32       # control-plane endpoint (kubectl get endpointslices -n default kubernetes)
      ports:
        - {protocol: TCP, port: 443}
        - {protocol: TCP, port: 6443}
yaml
# VARIANT for GKE only, for the workloads that use GKE Workload Identity
# (orders-api, the queue worker if it writes to Cloud Storage). Under
# default deny these Pods must still reach the GKE metadata server, which is
# where Workload Identity hands out credentials. From the GKE docs: "Allow
# egress to 169.254.169.252/32 on port 988. For clusters running GKE Dataplane
# V2, ensure that you allowed egress to 169.254.169.254/32 on port 80."
# Keep only the rule for your dataplane. Workloads without cloud access
# (shop-web) never get this policy. On EKS with IRSA do not apply it: there the
# metadata address serves the NODE's role and stays denied.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: gke-metadata-egress
  namespace: shop
spec:
  podSelector:
    matchExpressions:
      - key: app.kubernetes.io/name
        operator: In
        values: [orders-api, shop-queue]
  policyTypes: [Egress]
  egress:
    - to:
        - ipBlock:
            cidr: 169.254.169.252/32      # GKE metadata server (legacy dataplane)
      ports:
        - {protocol: TCP, port: 988}
    - to:
        - ipBlock:
            cidr: 169.254.169.254/32      # GKE Dataplane V2
      ports:
        - {protocol: TCP, port: 80}

The image for the config-lister Job is built from this chapter's own Dockerfile:

dockerfile
# syntax=docker/dockerfile:1
# Image for the config-lister Job (k8s/serviceaccount/config-lister-job.yaml).
# Build context: this go/ directory. Same pattern as the Images & Dockerfiles
# chapter: cached module download, static binary, distroless, numeric non-root.
FROM --platform=$BUILDPLATFORM golang:1.27-trixie AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG TARGETOS TARGETARCH
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -trimpath -ldflags "-s -w" -o /out/config-lister ./cmd/config-lister

FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/config-lister /config-lister
USER 65532:65532
ENTRYPOINT ["/config-lister"]

The offline RBAC checker used in the lab and in CI: the same rule matching as the API server, over the YAML in Git, plus a linter for the escalation paths in Escalation:

go
// Package rbaccheck answers "can this subject do this?" for RBAC objects
// read from YAML files, offline, the way the API server's RBAC authorizer
// would. The matching rules are ported from Kubernetes v1.34
// (plugin/pkg/auth/authorizer/rbac/rbac.go RuleAllows and
// pkg/apis/rbac/v1/evaluation_helpers.go). It also lints the objects for the
// over-grants the RBAC good-practices page lists.
//
// It only knows the objects in the files: built-in ClusterRoles such as
// view, edit or cluster-admin have no rules here, so a binding to them
// grants nothing in Allowed (Lint still flags the risky ones by name).
package rbaccheck

import (
	"bytes"
	"fmt"
	"os"

	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"sigs.k8s.io/yaml"
)

// Request is the subset of authorizer attributes RBAC looks at.
type Request struct {
	User        string
	Groups      []string
	Verb        string // get, list, watch, create, update, patch, delete, deletecollection, ...
	APIGroup    string // "" for the core group
	Resource    string // configmaps, pods, ...
	Subresource string // exec, log, token, ...
	Name        string // object name, "" for collections
	Namespace   string // "" for cluster-scoped requests
	Path        string // set instead of Resource for non-resource URLs (/healthz)
}

// ServiceAccount returns the username and groups the API server gives a
// ServiceAccount token: system:serviceaccount:<ns>:<name> and the groups
// system:serviceaccounts, system:serviceaccounts:<ns>, system:authenticated.
func ServiceAccount(ns, name string) (string, []string) {
	return "system:serviceaccount:" + ns + ":" + name,
		[]string{"system:serviceaccounts", "system:serviceaccounts:" + ns, "system:authenticated"}
}

// Store holds the RBAC objects found in some YAML files.
type Store struct {
	Roles               map[string]rbacv1.Role // key "namespace/name"
	ClusterRoles        map[string]rbacv1.ClusterRole
	RoleBindings        []rbacv1.RoleBinding
	ClusterRoleBindings []rbacv1.ClusterRoleBinding
}

// SplitDocuments splits a multi-document YAML stream on "---" lines.
func SplitDocuments(data []byte) [][]byte {
	var docs [][]byte
	for _, d := range bytes.Split(append([]byte("\n"), data...), []byte("\n---")) {
		if len(bytes.TrimSpace(stripComments(d))) > 0 {
			docs = append(docs, d)
		}
	}
	return docs
}

func stripComments(d []byte) []byte {
	var out [][]byte
	for _, l := range bytes.Split(d, []byte("\n")) {
		if t := bytes.TrimSpace(l); len(t) > 0 && t[0] != '#' {
			out = append(out, l)
		}
	}
	return bytes.Join(out, []byte("\n"))
}

// Load reads the files and keeps the four RBAC kinds, decoded strictly
// (an unknown or misspelled field is an error). Other kinds are skipped.
func Load(paths ...string) (*Store, error) {
	s := &Store{Roles: map[string]rbacv1.Role{}, ClusterRoles: map[string]rbacv1.ClusterRole{}}
	for _, p := range paths {
		data, err := os.ReadFile(p)
		if err != nil {
			return nil, err
		}
		for i, doc := range SplitDocuments(data) {
			var meta struct {
				Kind string `json:"kind"`
			}
			if err := yaml.Unmarshal(doc, &meta); err != nil {
				return nil, fmt.Errorf("%s doc %d: %w", p, i, err)
			}
			var derr error
			switch meta.Kind {
			case "Role":
				var r rbacv1.Role
				if derr = yaml.UnmarshalStrict(doc, &r); derr == nil {
					s.Roles[r.Namespace+"/"+r.Name] = r
				}
			case "ClusterRole":
				var r rbacv1.ClusterRole
				if derr = yaml.UnmarshalStrict(doc, &r); derr == nil {
					s.ClusterRoles[r.Name] = r
				}
			case "RoleBinding":
				var b rbacv1.RoleBinding
				if derr = yaml.UnmarshalStrict(doc, &b); derr == nil {
					s.RoleBindings = append(s.RoleBindings, b)
				}
			case "ClusterRoleBinding":
				var b rbacv1.ClusterRoleBinding
				if derr = yaml.UnmarshalStrict(doc, &b); derr == nil {
					s.ClusterRoleBindings = append(s.ClusterRoleBindings, b)
				}
			}
			if derr != nil {
				return nil, fmt.Errorf("%s doc %d (%s): %w", p, i, meta.Kind, derr)
			}
		}
	}
	return s, nil
}

// clusterRoleRules returns a ClusterRole's effective rules. For an aggregated
// ClusterRole the controller manager OVERWRITES the rules field with the
// union of the rules of every ClusterRole its aggregationRule selects
// ("The control plane overwrites any values that you manually specify in the
// rules field of an aggregate ClusterRole"), so manual rules are ignored here
// too. Selectors use the apimachinery label-selector semantics
// (matchLabels and matchExpressions).
func (s *Store) clusterRoleRules(name string) []rbacv1.PolicyRule {
	cr, ok := s.ClusterRoles[name]
	if !ok {
		return nil
	}
	if cr.AggregationRule == nil {
		return append([]rbacv1.PolicyRule(nil), cr.Rules...)
	}
	var rules []rbacv1.PolicyRule
	for i := range cr.AggregationRule.ClusterRoleSelectors {
		sel, err := metav1.LabelSelectorAsSelector(&cr.AggregationRule.ClusterRoleSelectors[i])
		if err != nil {
			continue // an invalid selector selects nothing
		}
		for _, other := range s.ClusterRoles {
			if other.Name != name && sel.Matches(labels.Set(other.Labels)) {
				rules = append(rules, other.Rules...)
			}
		}
	}
	return rules
}

func subjectMatches(sub rbacv1.Subject, bindingNS, user string, groups []string) bool {
	switch sub.Kind {
	case rbacv1.UserKind:
		return sub.Name == user
	case rbacv1.GroupKind:
		for _, g := range groups {
			if g == sub.Name {
				return true
			}
		}
	case rbacv1.ServiceAccountKind:
		ns := sub.Namespace
		if ns == "" {
			ns = bindingNS
		}
		return user == "system:serviceaccount:"+ns+":"+sub.Name
	}
	return false
}

// Allowed reports whether any binding grants the request, and which one.
// RBAC is purely additive: there is no deny rule, so the first allow wins
// and "no rule matched" means denied.
func (s *Store) Allowed(r Request) (bool, string) {
	for _, b := range s.ClusterRoleBindings {
		for _, sub := range b.Subjects {
			if subjectMatches(sub, "", r.User, r.Groups) {
				for _, rule := range s.clusterRoleRules(b.RoleRef.Name) {
					if RuleAllows(r, rule) {
						return true, "ClusterRoleBinding " + b.Name
					}
				}
			}
		}
	}
	if r.Namespace == "" {
		return false, "no rule matched"
	}
	for _, b := range s.RoleBindings {
		if b.Namespace != r.Namespace {
			continue // a RoleBinding only ever grants inside its own namespace
		}
		for _, sub := range b.Subjects {
			if !subjectMatches(sub, b.Namespace, r.User, r.Groups) {
				continue
			}
			var rules []rbacv1.PolicyRule
			if b.RoleRef.Kind == "Role" {
				rules = s.Roles[b.Namespace+"/"+b.RoleRef.Name].Rules
			} else {
				rules = s.clusterRoleRules(b.RoleRef.Name)
			}
			for _, rule := range rules {
				if RuleAllows(r, rule) {
					return true, "RoleBinding " + b.Namespace + "/" + b.Name
				}
			}
		}
	}
	return false, "no rule matched"
}
go
package rbaccheck

import (
	"fmt"
	"sort"

	rbacv1 "k8s.io/api/rbac/v1"
)

// Severity of a lint finding.
type Severity string

const (
	High Severity = "HIGH" // grants that amount to cluster or namespace takeover
	Note Severity = "NOTE" // intended but worth knowing (workload creation)
)

// Finding is one lint result.
type Finding struct {
	Severity Severity
	Object   string
	Message  string
}

func (f Finding) String() string { return fmt.Sprintf("%-4s %s: %s", f.Severity, f.Object, f.Message) }

func has(list []string, v string) bool {
	for _, x := range list {
		if x == v {
			return true
		}
	}
	return false
}

func lintRules(obj string, rules []rbacv1.PolicyRule) []Finding {
	var out []Finding
	add := func(s Severity, format string, a ...any) {
		out = append(out, Finding{s, obj, fmt.Sprintf(format, a...)})
	}
	for _, r := range rules {
		if has(r.Verbs, "*") || has(r.Resources, "*") || has(r.APIGroups, "*") {
			add(High, "wildcard in verbs/resources/apiGroups also covers resources added later")
		}
		for _, v := range []string{"escalate", "bind", "impersonate"} {
			if has(r.Verbs, v) {
				add(High, "verb %q bypasses RBAC's privilege-escalation checks", v)
			}
		}
		readsAll := has(r.Resources, "*") || has(r.Resources, "secrets")
		if readsAll && (has(r.Verbs, "list") || has(r.Verbs, "watch") || has(r.Verbs, "*")) {
			add(High, "list/watch on secrets returns the data of every Secret")
		}
		if has(r.Resources, "secrets") && has(r.Verbs, "get") && len(r.ResourceNames) == 0 {
			add(High, "get on secrets without resourceNames reads any Secret by name")
		}
		for _, sub := range []string{"pods/exec", "pods/attach", "nodes/proxy", "serviceaccounts/token"} {
			if has(r.Resources, sub) {
				add(High, "%s gives code execution or credentials beyond this role", sub)
			}
		}
		if has(r.Resources, "pods") && has(r.Verbs, "create") {
			add(High, "create pods = run as any ServiceAccount and mount any Secret in the namespace")
		}
		for _, w := range []string{"deployments", "statefulsets", "daemonsets", "jobs", "cronjobs"} {
			if has(r.Resources, w) && has(r.Verbs, "create") {
				add(Note, "create %s implies running Pods as any ServiceAccount in the namespace", w)
			}
		}
	}
	return out
}

func lintSubjects(obj, roleName string, subjects []rbacv1.Subject) []Finding {
	var out []Finding
	if roleName == "cluster-admin" {
		out = append(out, Finding{High, obj, "binds cluster-admin"})
	}
	for _, s := range subjects {
		if s.Kind == rbacv1.ServiceAccountKind && s.Name == "default" {
			out = append(out, Finding{High, obj, "grants to the default ServiceAccount, inherited by every Pod that names none"})
		}
		if s.Kind == rbacv1.GroupKind && (s.Name == "system:unauthenticated" || s.Name == "system:authenticated" || s.Name == "system:serviceaccounts") {
			out = append(out, Finding{High, obj, "grants to the broad group " + s.Name})
		}
		if s.Kind == rbacv1.UserKind && s.Name == "system:anonymous" {
			out = append(out, Finding{High, obj, "grants to system:anonymous"})
		}
	}
	return out
}

// Lint returns findings sorted by object name.
func Lint(s *Store) []Finding {
	var out []Finding
	for k, r := range s.Roles {
		out = append(out, lintRules("Role "+k, r.Rules)...)
	}
	for k, r := range s.ClusterRoles {
		out = append(out, lintRules("ClusterRole "+k, r.Rules)...)
	}
	for _, b := range s.RoleBindings {
		out = append(out, lintSubjects("RoleBinding "+b.Namespace+"/"+b.Name, b.RoleRef.Name, b.Subjects)...)
	}
	for _, b := range s.ClusterRoleBindings {
		out = append(out, lintSubjects("ClusterRoleBinding "+b.Name, b.RoleRef.Name, b.Subjects)...)
	}
	sort.SliceStable(out, func(i, j int) bool {
		if out[i].Object != out[j].Object {
			return out[i].Object < out[j].Object
		}
		return out[i].Message < out[j].Message
	})
	return out
}

// HighCount counts HIGH findings.
func HighCount(fs []Finding) int {
	n := 0
	for _, f := range fs {
		if f.Severity == High {
			n++
		}
	}
	return n
}
go
package rbaccheck

import (
	"path/filepath"
	"strings"
	"testing"

	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

const rbacDir = "../../k8s/rbac"

func load(t *testing.T, files ...string) *Store {
	t.Helper()
	var paths []string
	for _, f := range files {
		paths = append(paths, filepath.Join(rbacDir, f))
	}
	s, err := Load(paths...)
	if err != nil {
		t.Fatal(err)
	}
	return s
}

// The offline equivalent of
//
//	kubectl auth can-i <verb> <resource> -n <ns> --as=system:serviceaccount:shop:orders-api
func TestOrdersAPIServiceAccount(t *testing.T) {
	s := load(t, "orders-api-rbac.yaml", "people-and-ci.yaml")
	user, groups := ServiceAccount("shop", "orders-api")
	for _, tc := range []struct {
		req  Request
		want bool
	}{
		{Request{Verb: "list", Resource: "configmaps", Namespace: "shop"}, true},
		{Request{Verb: "watch", Resource: "configmaps", Namespace: "shop"}, true},
		{Request{Verb: "get", Resource: "configmaps", Name: "orders-flags", Namespace: "shop"}, true},
		{Request{Verb: "update", Resource: "configmaps", Name: "orders-flags", Namespace: "shop"}, false},
		{Request{Verb: "list", Resource: "configmaps", Namespace: "payments"}, false}, // RoleBinding is namespaced
		{Request{Verb: "list", Resource: "configmaps"}, false},                        // nor cluster-wide
		{Request{Verb: "get", Resource: "secrets", Name: "orders-db", Namespace: "shop"}, false},
		{Request{Verb: "create", Resource: "pods", Subresource: "exec", Name: "x", Namespace: "shop"}, false},
		{Request{Verb: "list", APIGroup: "apps", Resource: "configmaps", Namespace: "shop"}, false}, // wrong API group
	} {
		tc.req.User, tc.req.Groups = user, groups
		got, why := s.Allowed(tc.req)
		if got != tc.want {
			t.Errorf("%+v: allowed=%v (%s), want %v", tc.req, got, why, tc.want)
		}
	}
}

func TestPeopleAndCI(t *testing.T) {
	s := load(t, "people-and-ci.yaml")
	dev := Request{User: "oidc:jane@acme.example", Groups: []string{"oidc:shop-developers", "system:authenticated"}, Namespace: "shop"}

	logs := dev
	logs.Verb, logs.Resource, logs.Subresource, logs.Name = "get", "pods", "log", "shop-web-1"
	if ok, why := s.Allowed(logs); !ok {
		t.Errorf("developer cannot read pods/log: %s", why)
	}
	exec := logs
	exec.Verb, exec.Subresource = "create", "exec"
	if ok, _ := s.Allowed(exec); ok {
		t.Error("developer can exec: pods/log must not imply pods/exec")
	}

	deployer, groups := ServiceAccount("shop", "shop-deployer")
	for _, tc := range []struct {
		verb, group, res string
		want             bool
	}{
		{"patch", "apps", "deployments", true},
		{"create", "batch", "jobs", true},
		{"create", "rbac.authorization.k8s.io", "rolebindings", false},
		{"get", "", "secrets", false},
		{"patch", "", "namespaces", false}, // would let it relabel PSA
		{"delete", "apps", "deployments", false},
	} {
		r := Request{User: deployer, Groups: groups, Verb: tc.verb, APIGroup: tc.group, Resource: tc.res, Namespace: "shop"}
		if ok, why := s.Allowed(r); ok != tc.want {
			t.Errorf("deployer %s %s/%s: allowed=%v (%s), want %v", tc.verb, tc.group, tc.res, ok, why, tc.want)
		}
	}

	// Aggregation: acme-auditor has no rules of its own, but inherits the
	// rules of every ClusterRole labelled acme.io/aggregate-to-auditor.
	s.ClusterRoleBindings = append(s.ClusterRoleBindings, auditorBinding())
	audit := Request{User: "oidc:auditor@acme.example", Verb: "list", APIGroup: "rbac.authorization.k8s.io", Resource: "clusterrolebindings"}
	if ok, why := s.Allowed(audit); !ok {
		t.Errorf("aggregated ClusterRole did not grant: %s", why)
	}
	health := Request{User: "oidc:auditor@acme.example", Verb: "get", Path: "/healthz"}
	if ok, _ := s.Allowed(health); !ok {
		t.Error("nonResourceURLs /healthz not granted")
	}
	if ok, _ := s.Allowed(Request{User: "oidc:auditor@acme.example", Verb: "get", Path: "/metrics"}); ok {
		t.Error("/metrics granted but not listed")
	}
}

// Manual rules in an aggregated ClusterRole are overwritten by the control
// plane, so they must grant nothing here either.
func TestAggregatedClusterRoleIgnoresManualRules(t *testing.T) {
	s := load(t, "people-and-ci.yaml")
	agg := s.ClusterRoles["acme-auditor"]
	agg.Rules = []rbacv1.PolicyRule{ruleOf([]string{"get", "list"}, []string{""}, []string{"secrets"})}
	s.ClusterRoles["acme-auditor"] = agg
	s.ClusterRoleBindings = append(s.ClusterRoleBindings, auditorBinding())
	user := "oidc:auditor@acme.example"
	if ok, why := s.Allowed(Request{User: user, Verb: "list", Resource: "secrets", Namespace: "shop"}); ok {
		t.Errorf("manual rule in aggregated ClusterRole granted secrets: %s", why)
	}
	if ok, why := s.Allowed(Request{User: user, Verb: "list", APIGroup: "rbac.authorization.k8s.io", Resource: "roles", Namespace: "shop"}); !ok {
		t.Errorf("selected contributor rules not granted: %s", why)
	}
}

// An aggregationRule that selects no ClusterRole yields no rules at all,
// even if the manifest (wrongly) carries rules of its own; and a selector
// key that is absent from a role's labels must not match.
func TestAggregatedClusterRoleWithNoMatches(t *testing.T) {
	s := load(t, "people-and-ci.yaml")
	empty := rbacv1.ClusterRole{
		AggregationRule: &rbacv1.AggregationRule{ClusterRoleSelectors: []metav1.LabelSelector{
			{MatchLabels: map[string]string{"acme.io/aggregate-to-nobody": "true"}},
			{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "acme.io/missing", Operator: metav1.LabelSelectorOpIn, Values: []string{""}}}},
		}},
		Rules: []rbacv1.PolicyRule{ruleOf([]string{"*"}, []string{"*"}, []string{"*"})},
	}
	empty.Name = "acme-empty"
	s.ClusterRoles[empty.Name] = empty
	if got := s.clusterRoleRules("acme-empty"); len(got) != 0 {
		t.Fatalf("aggregated role with no matching contributors has %d rules, want 0", len(got))
	}
}

func TestLintBefore(t *testing.T) {
	fs := Lint(load(t, "before-overgrant.yaml"))
	text := make([]string, len(fs))
	for i, f := range fs {
		text[i] = f.String()
	}
	all := strings.Join(text, "\n")
	for _, want := range []string{
		"ClusterRoleBinding ci-deployer-cluster-admin: binds cluster-admin",
		"ClusterRole support-readonly: wildcard",
		"ClusterRole support-readonly: list/watch on secrets",
		"Role shop/shop-debug: pods/exec",
		"Role shop/shop-debug: create pods",
		`ClusterRole team-onboarding: verb "escalate"`,
		`ClusterRole team-onboarding: verb "bind"`,
		`ClusterRole team-onboarding: verb "impersonate"`,
		"RoleBinding shop/default-sa-edit: grants to the default ServiceAccount",
	} {
		if !strings.Contains(all, want) {
			t.Errorf("missing finding %q in:\n%s", want, all)
		}
	}
	if HighCount(fs) < 9 {
		t.Errorf("HIGH findings = %d, want >= 9", HighCount(fs))
	}
}

func TestLintAfterHasNoHigh(t *testing.T) {
	fs := Lint(load(t, "orders-api-rbac.yaml", "people-and-ci.yaml"))
	for _, f := range fs {
		if f.Severity == High {
			t.Errorf("unexpected %s", f)
		}
	}
	notes := 0
	for _, f := range fs {
		if f.Severity == Note {
			notes++
		}
	}
	if notes == 0 {
		t.Error("expected NOTE findings for the deployer's workload creation")
	}
}

func TestRuleAllowsSubresourceWildcard(t *testing.T) {
	r := Request{Verb: "update", APIGroup: "apps", Resource: "deployments", Subresource: "scale"}
	rule := ruleOf([]string{"update"}, []string{"apps"}, []string{"*/scale"})
	if !RuleAllows(r, rule) {
		t.Error("*/scale should match deployments/scale")
	}
	r.Subresource = ""
	if RuleAllows(r, rule) {
		t.Error("*/scale must not match deployments itself")
	}
}

func ruleOf(verbs, groups, resources []string) rbacv1.PolicyRule {
	return rbacv1.PolicyRule{Verbs: verbs, APIGroups: groups, Resources: resources}
}

func auditorBinding() rbacv1.ClusterRoleBinding {
	b := rbacv1.ClusterRoleBinding{
		RoleRef:  rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "ClusterRole", Name: "acme-auditor"},
		Subjects: []rbacv1.Subject{{Kind: rbacv1.UserKind, Name: "oidc:auditor@acme.example"}},
	}
	b.Name = "acme-auditor"
	return b
}

And the test that decodes every manifest of the chapter strictly into the k8s.io/api types, which caught a real YAML bug while this chapter was written (an unquoted system: prefix in a CEL message):

go
// Package manifests checks the chapter's YAML offline: every document of a
// built-in kind is decoded STRICTLY into the k8s.io/api Go types (v0.34),
// so a misspelled or misplaced field fails here the way
// `kubectl apply --dry-run=server` would fail on a cluster. CRDs (Kyverno,
// Gatekeeper, Cilium) and the API server's own config files have no types
// in k8s.io/api and are only parsed as YAML.
package manifests

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
	appsv1 "k8s.io/api/apps/v1"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	networkingv1 "k8s.io/api/networking/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/yaml"

	"academy/kubernetes-security-rbac/rbaccheck"
)

func typed(kind string) any {
	switch kind {
	case "Namespace":
		return &corev1.Namespace{}
	case "ServiceAccount":
		return &corev1.ServiceAccount{}
	case "Pod":
		return &corev1.Pod{}
	case "Deployment":
		return &appsv1.Deployment{}
	case "Job":
		return &batchv1.Job{}
	case "Role":
		return &rbacv1.Role{}
	case "ClusterRole":
		return &rbacv1.ClusterRole{}
	case "RoleBinding":
		return &rbacv1.RoleBinding{}
	case "ClusterRoleBinding":
		return &rbacv1.ClusterRoleBinding{}
	case "NetworkPolicy":
		return &networkingv1.NetworkPolicy{}
	case "ValidatingAdmissionPolicy":
		return &admissionregistrationv1.ValidatingAdmissionPolicy{}
	case "ValidatingAdmissionPolicyBinding":
		return &admissionregistrationv1.ValidatingAdmissionPolicyBinding{}
	case "ValidatingWebhookConfiguration":
		return &admissionregistrationv1.ValidatingWebhookConfiguration{}
	case "MutatingWebhookConfiguration":
		return &admissionregistrationv1.MutatingWebhookConfiguration{}
	}
	return nil
}

type doc struct {
	file string
	kind string
	raw  []byte
	obj  any
}

func loadAll(t *testing.T) []doc {
	t.Helper()
	var files []string
	for _, dir := range []string{"../../k8s", "../../apiserver"} {
		err := filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
			if err == nil && !d.IsDir() && strings.HasSuffix(p, ".yaml") {
				files = append(files, p)
			}
			return err
		})
		if err != nil {
			t.Fatal(err)
		}
	}
	var out []doc
	for _, f := range files {
		data, err := os.ReadFile(f)
		if err != nil {
			t.Fatal(err)
		}
		for i, raw := range rbaccheck.SplitDocuments(data) {
			var meta struct {
				APIVersion string `json:"apiVersion"`
				Kind       string `json:"kind"`
			}
			if err := yaml.Unmarshal(raw, &meta); err != nil {
				t.Fatalf("%s doc %d: not YAML: %v", f, i, err)
			}
			if meta.APIVersion == "" || meta.Kind == "" {
				t.Fatalf("%s doc %d: missing apiVersion/kind", f, i)
			}
			d := doc{file: f, kind: meta.Kind, raw: raw}
			if obj := typed(meta.Kind); obj != nil {
				if err := yaml.UnmarshalStrict(raw, obj); err != nil {
					t.Errorf("%s doc %d (%s): %v", f, i, meta.Kind, err)
				}
				d.obj = obj
			} else {
				var anyDoc map[string]any
				if err := yaml.UnmarshalStrict(raw, &anyDoc); err != nil {
					t.Errorf("%s doc %d (%s): %v", f, i, meta.Kind, err)
				}
			}
			out = append(out, d)
		}
	}
	return out
}

func TestStrictDecode(t *testing.T) {
	docs := loadAll(t)
	n := 0
	for _, d := range docs {
		if d.obj != nil {
			n++
		}
	}
	t.Logf("%d documents, %d decoded into k8s.io/api types", len(docs), n)
	if n < 30 {
		t.Fatalf("only %d typed documents; did a file move?", n)
	}
}

// Rules the API server or the docs state, checked by hand.
func TestSecurityInvariants(t *testing.T) {
	for _, d := range loadAll(t) {
		switch o := d.obj.(type) {
		case *corev1.Namespace:
			for k, v := range o.Labels {
				if !strings.HasPrefix(k, "pod-security.kubernetes.io/") {
					continue
				}
				mode := strings.TrimSuffix(strings.TrimPrefix(k, "pod-security.kubernetes.io/"), "-version")
				if mode != "enforce" && mode != "audit" && mode != "warn" {
					t.Errorf("%s: unknown PSA mode label %s", d.file, k)
				}
				if strings.HasSuffix(k, "-version") {
					if v != "latest" && !strings.HasPrefix(v, "v1.") {
						t.Errorf("%s: %s=%s is not latest or v1.NN", d.file, k, v)
					}
				} else if v != "privileged" && v != "baseline" && v != "restricted" {
					t.Errorf("%s: %s=%s is not a PSS level", d.file, k, v)
				}
			}
		case *admissionregistrationv1.ValidatingAdmissionPolicyBinding:
			deny, warn := false, false
			for _, a := range o.Spec.ValidationActions {
				deny = deny || a == admissionregistrationv1.Deny
				warn = warn || a == admissionregistrationv1.Warn
			}
			if deny && warn {
				t.Errorf("%s: Deny and Warn may not be used together", d.file)
			}
		case *admissionregistrationv1.ValidatingWebhookConfiguration:
			for _, w := range o.Webhooks {
				if w.TimeoutSeconds == nil || *w.TimeoutSeconds > 10 {
					t.Errorf("%s: webhook %s needs timeoutSeconds <= 10", d.file, w.Name)
				}
				if w.NamespaceSelector == nil {
					t.Errorf("%s: webhook %s should exclude its own namespace", d.file, w.Name)
				}
			}
		case *rbacv1.RoleBinding:
			if o.Namespace == "" {
				t.Errorf("%s: RoleBinding %s has no namespace", d.file, o.Name)
			}
		case *appsv1.Deployment:
			checkPodSpec(t, d.file, o.Name, o.Spec.Template.Spec)
		case *batchv1.Job:
			checkPodSpec(t, d.file, o.Name, o.Spec.Template.Spec)
		}
	}
}

func checkPodSpec(t *testing.T, file, name string, ps corev1.PodSpec) {
	t.Helper()
	if ps.AutomountServiceAccountToken == nil || *ps.AutomountServiceAccountToken {
		t.Errorf("%s: %s must set automountServiceAccountToken: false", file, name)
	}
	if ps.ServiceAccountName == "" || ps.ServiceAccountName == "default" {
		t.Errorf("%s: %s must use its own ServiceAccount", file, name)
	}
	for _, v := range ps.Volumes {
		if v.Projected == nil {
			continue
		}
		for _, src := range v.Projected.Sources {
			if st := src.ServiceAccountToken; st != nil && st.ExpirationSeconds != nil && *st.ExpirationSeconds < 600 {
				t.Errorf("%s: projected token shorter than the 600 s minimum", file)
			}
		}
	}
}

// Every NetworkPolicy podSelector in shop must select a label some
// Deployment or policy target in this chapter (or the Workloads chapter)
// really carries; a typo here silently selects nothing.
func TestNetworkPolicySelectorsUseKnownApps(t *testing.T) {
	known := map[string]bool{
		"shop-web": true, "orders-api": true, "shop-mysql": true, "shop-redis": true,
		"shop-queue": true, "shop-scheduler": true, "ingress-nginx": true,
	}
	for _, d := range loadAll(t) {
		np, ok := d.obj.(*networkingv1.NetworkPolicy)
		if !ok {
			continue
		}
		check := func(where string, ml map[string]string) {
			if v, ok := ml["app.kubernetes.io/name"]; ok && !known[v] {
				t.Errorf("%s %s: %s selects unknown app %q", d.file, np.Name, where, v)
			}
		}
		check("spec.podSelector", np.Spec.PodSelector.MatchLabels)
		for _, r := range np.Spec.Ingress {
			for _, p := range r.From {
				if p.PodSelector != nil {
					check("ingress.from", p.PodSelector.MatchLabels)
				}
			}
		}
		for _, r := range np.Spec.Egress {
			for _, p := range r.To {
				if p.PodSelector != nil {
					check("egress.to", p.PodSelector.MatchLabels)
				}
			}
		}
	}
}

// The strict decoder is what makes TestStrictDecode meaningful: a field in
// the wrong place (here automountServiceAccountToken under metadata) fails.
func TestStrictDecodeCatchesMisplacedField(t *testing.T) {
	bad := []byte("apiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: x\n  automountServiceAccountToken: false\n")
	if err := yaml.UnmarshalStrict(bad, &corev1.ServiceAccount{}); err == nil {
		t.Fatal("misplaced field accepted")
	}
	good := []byte("apiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: x\nautomountServiceAccountToken: false\n")
	if err := yaml.UnmarshalStrict(good, &corev1.ServiceAccount{}); err != nil {
		t.Fatal(err)
	}
}

// NetworkPolicy needs BOTH sides: for every in-namespace egress rule
// "app A -> app B on port P", some policy selecting B must allow ingress
// from A on P, otherwise the connection is dropped under default deny.
func TestNetworkPolicyBothSidesAllow(t *testing.T) {
	type edge struct {
		from, to string
		port     int32
	}
	appsOf := func(sel *metav1.LabelSelector) []string {
		if sel == nil {
			return nil
		}
		if v, ok := sel.MatchLabels["app.kubernetes.io/name"]; ok {
			return []string{v}
		}
		for _, e := range sel.MatchExpressions {
			if e.Key == "app.kubernetes.io/name" && e.Operator == metav1.LabelSelectorOpIn {
				return e.Values
			}
		}
		return nil
	}
	var egress, ingress []edge
	for _, d := range loadAll(t) {
		np, ok := d.obj.(*networkingv1.NetworkPolicy)
		if !ok || np.Namespace != "shop" {
			continue
		}
		selected := appsOf(&np.Spec.PodSelector)
		for _, r := range np.Spec.Egress {
			for _, peer := range r.To {
				if peer.NamespaceSelector != nil || peer.IPBlock != nil {
					continue // other namespaces and external IPs are checked elsewhere
				}
				for _, src := range selected {
					for _, dst := range appsOf(peer.PodSelector) {
						for _, p := range r.Ports {
							egress = append(egress, edge{src, dst, p.Port.IntVal})
						}
					}
				}
			}
		}
		for _, r := range np.Spec.Ingress {
			for _, peer := range r.From {
				if peer.NamespaceSelector != nil || peer.IPBlock != nil {
					continue
				}
				for _, src := range appsOf(peer.PodSelector) {
					for _, dst := range selected {
						for _, p := range r.Ports {
							ingress = append(ingress, edge{src, dst, p.Port.IntVal})
						}
					}
				}
			}
		}
	}
	if len(egress) == 0 {
		t.Fatal("no in-namespace egress edges found")
	}
	for _, e := range egress {
		found := false
		for _, i := range ingress {
			if i == e {
				found = true
			}
		}
		if !found {
			t.Errorf("egress %s -> %s:%d has no matching ingress allow on %s", e.from, e.to, e.port, e.to)
		}
	}
}

The Go angle ​

  • In-cluster config is three files and two variables. rest.InClusterConfig() reads KUBERNETES_SERVICE_HOST/KUBERNETES_SERVICE_PORT and /var/run/secrets/kubernetes.io/serviceaccount/{token,ca.crt}; without the variables it returns rest.ErrNotInCluster ("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined"). It sets BearerTokenFile, and "If set, the contents are periodically read", so kubelet rotation of a 10-minute token needs no code. Do not copy the token into a string at start-up.
  • Namespace from the file, not a constant. The namespace file comes from the downward API source of the projected volume; the same image then works in shop, shop-staging and a PR preview namespace without new RBAC.
  • Namespaced clients by construction. CoreV1().ConfigMaps(ns) with a concrete namespace needs only a Role; metav1.NamespaceAll needs a ClusterRole and a ClusterRoleBinding. Informers follow the same rule: informers.NewSharedInformerFactoryWithOptions(cs, resync, informers.WithNamespace(ns)) needs list and watch in one namespace only.
  • Fail fast and loudly on RBAC. A SelfSubjectAccessReview at start-up turns "random 403s later" into one log line naming namespace, verb and resource. Every authenticated identity may create a SelfSubjectAccessReview about itself, so the check needs no extra permission.
  • Tell 403 from everything else. apierrors.IsForbidden(err) (and IsUnauthorized for 401) let the service return "misconfigured" instead of retrying forever; wrapping with %w keeps both errors.Is(err, ErrForbidden) and IsForbidden working.
  • Be a polite API client. Set UserAgent (it appears in audit events as userAgent) and keep QPS/Burst low; API Priority and Fairness will throttle noisy clients anyway.
  • Versions. client-go v0.34.1 with k8s.io/api and k8s.io/apimachinery v0.34.1 declare go 1.24.0, which is why this module's go line reads 1.24.0; v0.35 needs Go 1.25. client-go supports API servers within the usual skew; the Kubernetes 1.37 API surface used here (ConfigMaps, SelfSubjectAccessReview v1) is stable.
  • Outside the cluster the same code takes a kubeconfig (clientcmd.BuildConfigFromFlags) and the developer's OIDC identity; never ship a kubeconfig with a ServiceAccount token inside an image. Verifying JWTs in your own Go service (for example a Kubernetes token with audience orders-api sent by another workload, checked with TokenReview or the cluster's JWKS) is covered in Authentication in Go.

Laravel ​

The Laravel shop (Nginx + php-fpm in shop-web, plus shop-queue and shop-scheduler from Kubernetes Workloads) never calls the Kubernetes API. The correct RBAC for it is none at all, and the correct token is no token. A Laravel pod without API access is the goal of this section.

Before ​

yaml
# Before: what Helm charts and quick starts produce.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
spec:
  template:
    spec:
      # no serviceAccountName -> "default"; no automount setting -> token mounted
      containers:
        - name: php-fpm
          image: ghcr.io/acme/shop-app:latest        # mutable tag, runs as root by default
---
# "The queue worker needed to list pods once" -> edit for the default SA
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: default-edit
roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: edit}
subjects: [{kind: ServiceAccount, name: default, namespace: shop}]
# ...and no NetworkPolicy: the web Pod can reach the API server, the metadata
# endpoint, every other namespace and the internet.

An RCE in any Composer dependency now reads /var/run/secrets/kubernetes.io/serviceaccount/token, and with edit it can read every Secret in shop and start Pods as any ServiceAccount there.

After ​

A dedicated ServiceAccount with no bindings and no token, and the Pod template that uses it. Nginx listens on 8080 here because it runs as non-root under PSA restricted and cannot bind port 80 without NET_BIND_SERVICE; the Kubernetes Workloads chapter uses 80 for simplicity:

yaml
# The Laravel app never talks to the Kubernetes API, so its Pods get:
#   - a dedicated ServiceAccount with no RoleBindings at all
#   - no token in the filesystem (automountServiceAccountToken: false on both
#     the ServiceAccount and the Pod template; the Pod setting wins if they differ)
# A remote-code-execution bug in a Composer package then finds no
# /var/run/secrets/kubernetes.io/serviceaccount/token to steal, and
# shop-web-netpol.yaml gives it no route to the API server either.
apiVersion: v1
kind: ServiceAccount
metadata:
  name: shop-web
  namespace: shop
automountServiceAccountToken: false
---
# Excerpt of the shop-web Deployment from the Kubernetes Workloads chapter:
# only the fields this chapter adds are shown with their surroundings.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
  namespace: shop
  labels:
    app.kubernetes.io/name: shop-web
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  template:
    metadata:
      labels:
        app.kubernetes.io/name: shop-web
    spec:
      serviceAccountName: shop-web
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 33                      # www-data in the Debian-based php:8.4-fpm images
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: php-fpm
          image: ghcr.io/acme/shop-app:1.8.0
          resources:
            requests: {cpu: 250m, memory: 256Mi}
            limits: {memory: 512Mi}
          securityContext:
            allowPrivilegeEscalation: false
            capabilities:
              drop: ["ALL"]
        - name: nginx
          image: ghcr.io/acme/shop-web:1.8.0
          ports:
            - name: http
              containerPort: 8080
          resources:
            requests: {cpu: 50m, memory: 32Mi}
            limits: {memory: 64Mi}
          securityContext:
            allowPrivilegeEscalation: false
            capabilities:
              drop: ["ALL"]

Ingress only from the ingress-nginx controller, egress only to MySQL and Redis (plus the namespace-wide DNS rule), the matching ingress rules on MySQL and Redis (both sides must allow), and the queue and scheduler Pods' egress. The manifests test checks that every in-namespace egress rule here has its ingress counterpart:

yaml
# The Laravel web Pods (Nginx + php-fpm, label app.kubernetes.io/name: shop-web):
#   ingress only from the ingress-nginx controller, on the Nginx port (8080: the
#   non-root Nginx of this chapter cannot bind 80 without NET_BIND_SERVICE)
#   egress only to MySQL and Redis in this namespace (DNS comes from
#   shop-default-deny.yaml). No route to the Kubernetes API, the cloud
#   metadata endpoint or the internet.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: shop-web
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  policyTypes: [Ingress, Egress]
  ingress:
    - from:
        # ONE list item with both selectors = controller Pods in ingress-nginx.
        # Two separate items ("- namespaceSelector" and "- podSelector") would
        # mean "anything in ingress-nginx OR those labels in shop".
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: ingress-nginx
          podSelector:
            matchLabels:
              app.kubernetes.io/name: ingress-nginx
      ports:
        - {protocol: TCP, port: 8080}
  egress:
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: shop-mysql
      ports:
        - {protocol: TCP, port: 3306}
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: shop-redis
      ports:
        - {protocol: TCP, port: 6379}
---
# The other side: MySQL accepts connections from the web, queue and scheduler
# Pods only. Both the egress rule above AND this ingress rule must allow it.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: shop-mysql
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: shop-mysql
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchExpressions:
              - key: app.kubernetes.io/name
                operator: In
                values: [shop-web, shop-queue, shop-scheduler]
      ports:
        - {protocol: TCP, port: 3306}
---
# Redis accepts the same three Laravel roles.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: shop-redis
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: shop-redis
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchExpressions:
              - key: app.kubernetes.io/name
                operator: In
                values: [shop-web, shop-queue, shop-scheduler]
      ports:
        - {protocol: TCP, port: 6379}
---
# The queue worker and the scheduler: no ingress at all, egress to MySQL and
# Redis only (same image as shop-web, different command).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: shop-workers
  namespace: shop
spec:
  podSelector:
    matchExpressions:
      - key: app.kubernetes.io/name
        operator: In
        values: [shop-queue, shop-scheduler]
  policyTypes: [Ingress, Egress]
  egress:
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: shop-mysql
      ports:
        - {protocol: TCP, port: 3306}
    - to:
        - podSelector:
            matchLabels:
              app.kubernetes.io/name: shop-redis
      ports:
        - {protocol: TCP, port: 6379}

If MySQL is a managed database outside the cluster, apply this file instead of the shop-mysql rules (an alternative, not an addition: policies are additive, so applying both allows both paths):

yaml
# ALTERNATIVE to the in-cluster shop-mysql rules in shop-web-netpol.yaml, applied
# INSTEAD of them (policies are additive, so applying both allows both paths).
# Managed MySQL (RDS, Cloud SQL, Azure Database) lives outside the cluster:
# use ipBlock with the database subnet instead of a podSelector. Whether
# ipBlock sees the real destination depends on the plugin and on NAT.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: shop-web-managed-db
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  policyTypes: [Egress]
  egress:
    - to:
        - ipBlock:
            cidr: 10.20.0.0/24      # the private database subnet
            except: [10.20.0.1/32]
      ports:
        - {protocol: TCP, port: 3306}

The Laravel angle ​

  • No token, no API. With automountServiceAccountToken: false on both the ServiceAccount and the Pod, nothing is mounted under /var/run/secrets/kubernetes.io/serviceaccount; the Pod is still associated with the shop-web ServiceAccount (spec.serviceAccountName), but has no credential to present.
  • A test that keeps it that way. Run it as part of the container smoke test in the cluster (for example in the post-deploy job), so a chart change that re-enables automount fails the pipeline:
php
<?php
// tests/Feature/NoKubernetesApiAccessTest.php — runs inside the deployed image (post-deploy smoke test)
namespace Tests\Feature;

use Tests\TestCase;

final class NoKubernetesApiAccessTest extends TestCase
{
    public function test_no_service_account_token_is_mounted(): void
    {
        $this->assertFileDoesNotExist('/var/run/secrets/kubernetes.io/serviceaccount/token');
    }

    public function test_api_server_is_not_reachable(): void
    {
        // KUBERNETES_SERVICE_HOST is still injected; NetworkPolicy must drop the connection.
        $host = getenv('KUBERNETES_SERVICE_HOST') ?: 'kubernetes.default.svc';
        $socket = @fsockopen($host, 443, $errno, $errstr, 2.0);
        $this->assertFalse($socket, 'shop-web can open a TCP connection to the Kubernetes API');
    }
}
  • Cloud access only where it is needed. If queue jobs upload invoices to S3, give shop-queue its own ServiceAccount with IRSA (or GKE/Azure workload identity) and leave shop-web without cloud access; the AWS SDK for PHP and Laravel's s3 filesystem driver pick up web-identity credentials from the environment without any keys in .env.
  • Trusted proxies. With ingress-nginx as the only allowed ingress peer, enable Laravel's TrustProxies middleware with $middleware->trustProxies(at: [...]) in bootstrap/app.php for the controller's Pod CIDR, so $request->ip() returns the client address; the NetworkPolicy is the guarantee that nobody else can send those forwarded headers.
  • Secrets as files or env from Secrets, not via the API. DB_PASSWORD comes from a Secret mounted by the kubelet (Config, Secrets & Storage); the app never needs get secrets.
  • Health route. Kubernetes probes hit /up over the Pod IP from the kubelet; node-to-Pod traffic is always allowed by NetworkPolicy, so probes keep working under default deny.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
CI pipeline is cluster-adminNamespace deployer Role + short tokensshop-deployer Role, kubectl create token --duration=15m or cloud OIDC; Argo CD per-project rightsLeak = one namespace, minutesA Role per namespace
Developers need to debug productionLogs, not execpods/log Role; kubectl debug only in break-glassNo shell into prod PodsSome bugs need a reproducer
Rolling out PSA restricted without an outagewarn/audit first--dry-run=server label, warn+audit restricted, enforce baseline, then enforce restricted pinnedTeams see failures before they happenWeeks of follow-up
Policy webhook outage blocks the clusterExclusions, redundancy, in-process rulesnamespaceSelector excludes kube-system and itself, ≥ 2 replicas + PDB, VAP for simple rulesControl plane survives a dead webhookDuplicated logic in two places
Long-lived ServiceAccount tokensDelete legacy token Secretskubectl get secrets -A --field-selector type=kubernetes.io/service-account-token; projected tokensNo credentials that never expireOld clients must re-read tokens
Cloud keys in SecretsWorkload identityIRSA / Pod Identity / GKE / Azure WI per ServiceAccountNo static cloud credentialsOIDC set-up per cluster
Default deny breaks the namespaceDNS rule + allow per workloadallow-dns-egress, then one policy per app, tested in stagingMinimal reachabilityEvery new dependency is a PR
"Who deleted the payments Deployment?"Audit policy + retentionMetadata for everything, RequestResponse for RBAC, ship to SIEMAnswerable in minutesStorage, API server memory

CI pipeline is cluster-admin ​

Replace the ClusterRoleBinding with a Role in each target namespace that lists exactly the kinds the app ships (Deployments, Services, ConfigMaps, Ingresses, NetworkPolicies, Jobs), and nothing for RBAC, Secrets or the Namespace object. GitHub Actions and GitLab CI authenticate with the cloud through OIDC and fetch a short cluster credential; for self-managed clusters kubectl create token shop-deployer --duration=15m from a trusted runner. With GitOps, the pipeline does not talk to the cluster at all: it writes the image digest to Git and Argo CD (with an AppProject limited to shop) applies it (GitOps). Remember the residual risk the linter's NOTE lines show: creating Deployments still means running Pods as any ServiceAccount in shop, which is why shop contains only shop's ServiceAccounts and enforces PSA restricted.

Developers need to debug production ​

Bind view plus the shop-log-reader Role (pods and pods/log) for everyone; give pods/exec and pods/ephemeralcontainers only through a break-glass group that on-call impersonates (impersonate on that one group), so every exec is visible in the audit log "as" that group and alerts fire. Metrics and traces should answer most questions without a shell (Kubernetes Observability & Troubleshooting).

Rolling out PSA restricted without an outage ​

Start with kubectl label --dry-run=server --overwrite ns <ns> pod-security.kubernetes.io/enforce=restricted to list violators, then label warn and audit at restricted while enforce stays baseline. Fix manifests (the usual four: allowPrivilegeEscalation: false, drop ALL capabilities, runAsNonRoot: true, seccompProfile: RuntimeDefault) and raise enforce with a pinned enforce-version. Container Security has the same roll-out from the container's point of view.

Policy webhook outage blocks the cluster ​

Keep the emergency procedure written down: who can kubectl delete validatingwebhookconfiguration, and that it must be re-applied by GitOps afterwards. Prevention: exclude kube-system and the engine's namespace, matchConditions for system users, two or more replicas spread over nodes with a PodDisruptionBudget, timeoutSeconds of a few seconds, and move every rule that CEL can express into ValidatingAdmissionPolicy, which cannot be unreachable.

Default deny breaks the namespace ​

Apply default deny in staging first with a DNS rule from day one; use the CNI's flow logs (Cilium Hubble, Calico flow logs) to list the connections each workload really makes, turn them into allow policies, then apply in production. Probes are not affected (node-to-Pod traffic is always allowed); the API server and external databases are the usual surprises, because they need ipBlock or CNI-specific peers.

Choosing ​

Which policy layer ​

RuleLayerWhy
Privileged, hostPath, capabilities, rootPod Security AdmissionBuilt in, cannot fail open
Labels required, replicas limit, no :latest, limits requiredValidatingAdmissionPolicyCEL in process, no component
Image signatures and digest pinningKyverno ImageValidatingPolicy (or Sigstore policy-controller)Needs registry and transparency-log access
Defaults (inject labels, sidecars, default-deny generation)MutatingAdmissionPolicy or KyvernoMutation and generation
Reports on what already runsKyverno background scans or Gatekeeper auditAdmission sees only new writes
Organisation already writes RegoOPA GatekeeperOne policy language across Terraform, CI and Kubernetes

Which authentication for humans ​

ClusterHuman loginBreak-glass
kubeadm / k3s on-premisesOIDC via AuthenticationConfiguration (Dex, Keycloak, corporate IdP)One client certificate in a vault, alerting on use
EKSIAM Identity Center + access entriesA separate IAM role with cluster-admin access policy
GKEGoogle identities and Google Groups for RBACOrg-level admin, audited
AKSMicrosoft Entra ID integration (local accounts disabled)Entra group with emergency access
Laptop (kind, Docker Desktop)The generated admin certificate—

Which workload identity ​

PlatformChoiceNote
EKS, new set-upEKS Pod IdentityNo OIDC provider per cluster; agent DaemonSet
EKS, existing or cross-account federation patternsIRSAWorks everywhere, including self-managed with an OIDC issuer
GKEWorkload Identity Federation (principal bindings)Pool shared across a fleet: name namespaces carefully
AKSMicrosoft Entra Workload IDLabel azure.workload.identity/use: "true" required
Vault-backed secrets anywhereVault Kubernetes or JWT auth with an audience-specific projected tokenAudience vault, short expiry

Which CNI for policy ​

NeedChoice
Standard NetworkPolicy, wide supportCalico or Cilium (or the managed default with policy enabled)
FQDN egress, L7 HTTP rules, Hubble visibilityCilium
Ordered policies with deny, global policies, host protectionCalico
EKS with VPC-native Pod IPsAWS VPC CNI with network policy enabled, or Cilium in chaining mode
Encrypted Pod traffic plus identity-based L7A service mesh or Cilium mutual authentication, see mTLS & Service Security

Which tenancy model ​

TenantsModel
Teams of one company, shared on-callNamespace per team + this chapter's bundle
Teams needing their own CRDs, webhooks or cluster-adminvCluster on shared nodes
External customers running their own codevCluster on private nodes or a cluster per customer
Regulated workloads (cards, health data)Separate cluster, separate cloud account

In architecture: from a single process to a distributed system ​

Kubernetes security grows with the number of identities more than with the number of Pods: each new team, pipeline and service is a new subject that needs a binding, a namespace label, a network rule and an audit trail.

Monolith: one app, one namespace ​

The Laravel monolith in shop: three Deployments (web, queue, scheduler) and a database. The minimum correct set-up is already everything in this chapter at small scale: shop-web, shop-queue and shop-scheduler ServiceAccounts with no bindings and no tokens, PSA restricted, default-deny NetworkPolicy with DNS, web ingress from ingress-nginx and egress to MySQL and Redis, a deployer Role for the one pipeline, OIDC login for the two developers with view and edit, and audit at Metadata. None of it needs a policy engine.

Modular monolith: namespaces and ownership ​

The same codebase now ships a Go orders-api and an admin back-office owned by different people. Split by trust, not by code: shop (customer-facing), shop-admin (internal back-office, different ingress, stricter egress), shop-jobs (batch). Each namespace has its owner group bound to admin, its own deployer, and its own NetworkPolicy set; cross-namespace calls are explicit namespaceSelector allows. orders-api's single Role (ConfigMaps in shop) stays the only API permission any workload holds.

Microservices: many teams, a platform team ​

Twenty services, ten teams. The platform team owns cluster-scoped things (PSA defaults, ValidatingAdmissionPolicies, the policy engine, audit, CNI, aggregated ClusterRoles for its CRDs) and a namespace template that every new service gets through GitOps. Teams own namespaced things. A typical onboarding flow, all as pull requests:

text
1  team opens a PR to the platform repo: tenants/orders.yaml (owners, cost centre, tier)
2  CI renders the bundle with Helm or Kustomize: Namespace + PSA labels, RoleBindings for OIDC groups,
   deployer ServiceAccount + Role, ResourceQuota, default-deny NetworkPolicy, Argo CD AppProject
3  CI runs rbaccheck (no HIGH findings), kyverno test / gator verify, kubectl --dry-run=server
4  Argo CD syncs; Terraform has already created the cloud role for the team's workload identity
5  the team's own repo deploys only into its namespace; any ClusterRoleBinding in it fails the policy

The general authorization model (who owns which permission, how reviews happen) is Authorization: RBAC, ABAC & Zero Trust; the architectural reasons for running Kubernetes at all are Containers & Kubernetes.

Distributed data: many clusters, regions and identities ​

With clusters per region and environment, the hard problems become consistency and identity federation. RBAC, PSA labels and policies are replicated by GitOps (Argo CD ApplicationSets, Flux) so every cluster has the same bindings; drift is a security finding. Human identity is federated once (the same OIDC issuer and group names on every API server), and audit events from all clusters go to one SIEM with the cluster name attached. Workload identity is per cluster (each has its own issuer and keys); on GKE the shared workload identity pool means ns/shop/sa/orders-api is the same principal in every fleet cluster, which is convenient and must be intentional. Network policy now spans clusters (Cilium Cluster Mesh, service meshes), and signature verification must work in every region, so signatures and attestations are replicated with the images.

Scaling path: 1x, 10x, 100x ​

ScaleIdentityAuthorizationAdmissionNetwork and audit
1x (one team, one cluster)OIDC for people, one SA per workloadBuilt-in view/edit per namespace, deployer RolePSA restricted, one or two VAPsDefault deny + allows; Metadata audit to a file
10x (several teams)Groups from the IdP, workload identityNamespace template via GitOps, rbaccheck in CI, aggregated roles for CRDsKyverno or Gatekeeper with signature verification, Audit → EnforceCNI with flow logs, alerts on exec and Secret reads
100x (many clusters, regions)One federation, break-glass proceduresPolicy-as-code repo, periodic access reviews, automated removal of stale bindingsSame policies everywhere, policy reports aggregatedCentral SIEM, multi-cluster network policy, CIS scans on schedule

Lab ​

Label: every kubectl, kube-bench and cosign command below is expected, not run: this build host has no Kubernetes cluster and no cluster may be started here (AUTHORING cost rule). Their output is shown either as the sample the Kubernetes docs print or as a described shape, never as invented values. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) with bash scripts/lab-offline.sh from the snippet root and show real output (saved in pipeline/sources/kubernetes-security-rbac/lab-host-output.txt).

1. Build and test the Go module (ran on the host) ​

bash
cd docs/snippets/platform/kubernetes-security-rbac/go
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ?   	academy/kubernetes-security-rbac/before	[no test files]
# ?   	academy/kubernetes-security-rbac/cmd/config-lister	[no test files]
# ?   	academy/kubernetes-security-rbac/cmd/rbaccheck	[no test files]
# ok  	academy/kubernetes-security-rbac/lister	2.037s
# ok  	academy/kubernetes-security-rbac/manifests	1.588s
# ok  	academy/kubernetes-security-rbac/rbaccheck	1.412s
go test -count=1 -run 'TestStrictDecode$' -v ./manifests/
#     manifests_test.go:125: 55 documents, 44 decoded into k8s.io/api types
# --- PASS: TestStrictDecode (0.01s)

2. Lint the "before" RBAC and the "after" RBAC offline (ran on the host) ​

bash
go run ./cmd/rbaccheck ../k8s/rbac/before-overgrant.yaml
# HIGH ClusterRole support-readonly: list/watch on secrets returns the data of every Secret
# HIGH ClusterRole support-readonly: wildcard in verbs/resources/apiGroups also covers resources added later
# HIGH ClusterRole team-onboarding: verb "bind" bypasses RBAC's privilege-escalation checks
# HIGH ClusterRole team-onboarding: verb "escalate" bypasses RBAC's privilege-escalation checks
# HIGH ClusterRole team-onboarding: verb "impersonate" bypasses RBAC's privilege-escalation checks
# HIGH ClusterRoleBinding ci-deployer-cluster-admin: binds cluster-admin
# HIGH Role shop/shop-debug: create pods = run as any ServiceAccount and mount any Secret in the namespace
# HIGH Role shop/shop-debug: pods/exec gives code execution or credentials beyond this role
# HIGH RoleBinding shop/default-sa-edit: grants to the default ServiceAccount, inherited by every Pod that names none
# 9 findings, 9 HIGH            (exit 1)
go run ./cmd/rbaccheck ../k8s/rbac/orders-api-rbac.yaml ../k8s/rbac/people-and-ci.yaml
# NOTE Role shop/shop-deployer: create cronjobs implies running Pods as any ServiceAccount in the namespace
# NOTE Role shop/shop-deployer: create deployments implies running Pods as any ServiceAccount in the namespace
# NOTE Role shop/shop-deployer: create jobs implies running Pods as any ServiceAccount in the namespace
# NOTE Role shop/shop-deployer: create statefulsets implies running Pods as any ServiceAccount in the namespace
# 4 findings, 0 HIGH            (exit 0)

3. Offline can-i against the YAML (ran on the host) ​

bash
R=../k8s/rbac; SA=system:serviceaccount:shop:orders-api
go run ./cmd/rbaccheck -as $SA -verb list -resource configmaps -n shop     $R/orders-api-rbac.yaml $R/people-and-ci.yaml
# yes - RoleBinding shop/orders-api-config-reader
go run ./cmd/rbaccheck -as $SA -verb list -resource configmaps -n payments $R/orders-api-rbac.yaml $R/people-and-ci.yaml
# no
go run ./cmd/rbaccheck -as $SA -verb get  -resource secrets    -n shop     $R/orders-api-rbac.yaml $R/people-and-ci.yaml
# no
go run ./cmd/rbaccheck -as oidc:jane@acme.example -as-group oidc:shop-developers -verb get -resource pods/log -n shop $R/people-and-ci.yaml
# yes - RoleBinding shop/shop-developers-logs
go run ./cmd/rbaccheck -as oidc:jane@acme.example -as-group oidc:shop-developers -verb create -resource pods/exec -n shop $R/people-and-ci.yaml
# no
go run ./cmd/config-lister
# ERROR config-lister failed err="not running in a Pod (or automountServiceAccountToken is false and no token is projected):
#   unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined"
ruby ../scripts/check-yaml.rb
# 55 YAML documents parsed

4. Apply and check RBAC on a cluster (expected, not run) ​

bash
cd ..   # back from go/ to the snippet root: the paths below are relative to it
kubectl apply -f k8s/psa/namespaces.yaml -f k8s/rbac/orders-api-rbac.yaml -f k8s/rbac/people-and-ci.yaml
kubectl auth can-i list configmaps -n shop --as=system:serviceaccount:shop:orders-api
# yes
kubectl auth can-i get secrets -n shop --as=system:serviceaccount:shop:orders-api
# no
kubectl auth can-i --list -n shop --as=oidc:jane@acme.example --as-group=oidc:shop-developers
# a table of Resources / Non-Resource URLs / Resource Names / Verbs (shape as in the kubectl docs)
kubectl auth whoami
# ATTRIBUTE   VALUE
# Username    oidc:jane@acme.example
# Groups      [oidc:shop-developers system:authenticated]

5. Run config-lister in the cluster and break it on purpose (expected, not run) ​

bash
# 0. The Job carries a placeholder digest (sha256:000...). Build go/Dockerfile (ENTRYPOINT
#    /config-lister), push it to a registry you control, then pin the digest the push produced:
docker buildx build --platform linux/amd64,linux/arm64 -t ghcr.io/acme/config-lister:1.4.2 --push go/
DIGEST=$(docker buildx imagetools inspect ghcr.io/acme/config-lister:1.4.2 --format '{{json .Manifest.Digest}}' | tr -d '"')
sed -i.bak "s|sha256:0\{64\}|$DIGEST|" k8s/serviceaccount/config-lister-job.yaml
# 1. The API server is not a Pod, so orders-api-netpol.yaml names it by IP. 10.0.0.1/32 is a
#    placeholder: put the address(es) of the "kubernetes" EndpointSlice in its ipBlock
#    (whether ipBlock matches after Service NAT depends on the CNI; Cilium: use toEntities instead)
kubectl get endpointslices -n default -l kubernetes.io/service-name=kubernetes -o jsonpath='{.items[*].endpoints[*].addresses[*]}'
kubectl apply -f k8s/netpol/shop-default-deny.yaml -f k8s/netpol/orders-api-netpol.yaml
kubectl apply -f k8s/serviceaccount/config-lister-job.yaml
kubectl wait -n shop --for=condition=complete job/orders-api-config-check --timeout=60s
kubectl logs -n shop job/orders-api-config-check
# expected: a log line "INFO access review namespace=shop verb=list resource=configmaps allowed=true reason=..."
#           then the names of the ConfigMaps labelled acme.io/flags=true; the Job completes
kubectl delete job -n shop orders-api-config-check
kubectl delete rolebinding -n shop orders-api-config-reader
kubectl apply -f k8s/serviceaccount/config-lister-job.yaml && kubectl logs -n shop job/orders-api-config-check -f
# expected: allowed=false, then: ServiceAccount may not list configmaps in "shop": check the RoleBinding;
#           exit 1, the Job fails at once (backoffLimit: 0)
kubectl apply -f k8s/rbac/orders-api-rbac.yaml; kubectl delete job -n shop orders-api-config-check
kubectl delete networkpolicy -n shop orders-api   # default deny stays, so egress to the API server is gone
kubectl apply -f k8s/serviceaccount/config-lister-job.yaml && kubectl logs -n shop job/orders-api-config-check -f
# expected: the new Pod's access review fails when the 10 s context deadline expires (no route to the API server)

6. Pod Security Admission and ValidatingAdmissionPolicy (expected, not run) ​

bash
kubectl label --dry-run=server --overwrite ns payments pod-security.kubernetes.io/enforce=restricted
# expected: "Warning: ..." lines naming the existing Pods that would violate restricted:latest;
#           nothing is changed because of --dry-run=server
kubectl apply -f k8s/admission/vap-pod-rules.yaml
# a Pod that passes PSA restricted but uses the latest tag: only the VAP objects to it
sed 's|orders-api:1.4.2@sha256:[0-9a-f]*|orders-api:latest|' k8s/serviceaccount/orders-api-deployment.yaml \
  | kubectl apply --dry-run=server -f -
# expected: accepted (binding is [Warn, Audit]) with a "Warning: Validation failed for ValidatingAdmissionPolicy
#           'acme-pod-rules.acme.io' ..." line naming the latest-tag image; after switching the binding to [Deny]: rejected

7. Audit, signature verification and the CIS scan (expected, not run) ​

bash
# self-managed control plane: watch for exec and Secret reads
sudo tail -f /var/log/kubernetes/audit/audit.log | jq -c 'select(.objectRef.subresource=="exec" or .objectRef.resource=="secrets")
  | {user: .user.username, verb, ns: .objectRef.namespace, name: .objectRef.name, code: .responseStatus.code}'
# Kyverno: install it, apply the signature policy, then try a Pod that passes PSA restricted
# and the VAP, so the signature is the only thing that can reject it
helm repo add kyverno https://kyverno.github.io/kyverno/
helm install kyverno kyverno/kyverno --version 3.10.0 -n kyverno --create-namespace
# wait until the admission controller serves and its webhooks are registered, or the next
# applies fail with "failed calling webhook" instead of the policy decision
kubectl -n kyverno wait --for=condition=Available deploy/kyverno-admission-controller --timeout=120s
until kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations -o name | grep -q kyverno; do sleep 2; done
kubectl apply -f k8s/kyverno/imagevalidatingpolicy.yaml
sleep 5   # give Kyverno a moment to register the new policy in its webhook
kubectl apply -f k8s/kyverno/unsigned-test-pod.yaml
# expected: rejected by the Kyverno admission webhook with the policy's message
#           "image is not signed by an acme release workflow"
cosign verify ghcr.io/acme/orders-api@sha256:<digest> \
  --certificate-identity-regexp 'https://github.com/acme/.*/.github/workflows/release.yml@refs/tags/.*' \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com
# CIS Kubernetes Benchmark with kube-bench
kubectl apply -f https://raw.githubusercontent.com/aquasecurity/kube-bench/main/job.yaml
kubectl logs job/kube-bench
# expected: [PASS]/[FAIL]/[WARN] lines per CIS check and a summary per section

Common misconceptions ​

BeliefReality
RBAC can deny"Permissions are purely additive (there are no "deny" rules)"; deny-style rules belong in admission
A ClusterRole grants cluster-wide accessOnly a ClusterRoleBinding does; a RoleBinding to a ClusterRole grants in one namespace
get/list on Secrets is read-only and harmless"list on secrets will reveal the data attributes of any returned resources"
Without Secrets permissions you cannot read Secretscreate on Pods mounts any Secret in the namespace and runs as any ServiceAccount
edit is a safe developer roleIt reads Secrets and runs Pods as any ServiceAccount; view is the safe one
system:masters can be revoked by removing bindingsIt "bypasses all RBAC rights checks" and cannot be revoked that way
Users can be deleted from KubernetesThere are no User objects; certificates stay valid until expiry
The ServiceAccount token expires after an hourAdmission-injected ones are extended to a year by default (warnafter at 3,607 s)
An app that does not call the API needs no ServiceAccount careThe default token is mounted unless automountServiceAccountToken: false
PSA enforce rejects the DeploymentEnforce applies to Pods; Deployments get warnings and audit annotations only
failurePolicy: Ignore is the safe defaultThe default is Fail; Ignore makes a security webhook fail open
A ValidatingAdmissionPolicy works once createdIt needs a ValidatingAdmissionPolicyBinding
A NetworkPolicy always blocks trafficOnly with a CNI that implements it; otherwise "no effect"
NetworkPolicies are evaluated in orderThey are additive unions; both egress and ingress sides must allow
Default deny keeps working DNS"A default deny-all egress policy also blocks DNS traffic"
Audit logging is on by defaultNo --audit-policy-file, no events; managed clusters need it enabled
Namespaces are a hard tenant boundaryKubelet, API server, CRDs and webhooks are shared; use virtual or separate clusters for hard isolation

Cheat sheet ​

TopicRemember
Request flowauthentication (401) → authorization (403) → mutating → schema → validating admission → etcd; audit beside all
AuthenticationClient certs (CN = user, O = groups), OIDC id_token (short-lived, prefix usernames), SA tokens; anonymous only for health
ServiceAccountsOne per workload, automountServiceAccountToken: false, projected tokens 600 s+, refreshed at 80 %
TokensTokenRequest API, bound to Pod/Secret/Node, audience-checked; delete legacy kubernetes.io/service-account-token Secrets
RBAC objectsRole/ClusterRole hold rules; RoleBinding grants in one namespace; ClusterRoleBinding everywhere; roleRef immutable
RulesapiGroups × resources (+ pods/log, pods/exec) × verbs; resourceNames; nonResourceURLs only in ClusterRoles; no *
Built-in rolesview (no Secrets) < edit (Secrets, any SA) < admin (RBAC in ns) < cluster-admin (break-glass)
Escalationescalate, bind, impersonate, create pods, nodes/proxy, serviceaccounts/token, CSR approval, webhook configs, patch namespaces, system:masters
Checkingkubectl auth can-i ... --as=... --as-group=..., --list, auth whoami, SelfSubjectAccessReview in code
Workload identityIRSA / EKS Pod Identity / GKE WIF / Azure WI: projected token exchanged for cloud creds; metadata egress per platform (GKE WI needs 169.254.169.252:988, or 169.254.169.254:80 on Dataplane V2)
PSApod-security.kubernetes.io/{enforce,audit,warn}[-version]; enforce on Pods only; pin enforce-version; exemptions static
WebhooksDefault failurePolicy: Fail, timeout 10 s (1-30), exclude kube-system and own namespace, matchConditions
VAPCEL in the API server, needs a binding; [Warn, Audit] → [Deny]; never Deny+Warn
EnginesKyverno ValidatingPolicy/ImageValidatingPolicy (ClusterPolicy legacy), Gatekeeper ConstraintTemplate + Constraint, dryrun → deny
Signaturescosign keyless in CI, verify at admission by digest, mutateDigest
AuditFirst match wins; None/Metadata/Request/RequestResponse; Metadata for Secrets; alert on exec and Secret reads
NetworkPolicyDefault deny both ways + DNS; one-entry vs two-entry from; ipBlock for external; CNI must enforce
Hardening--authorization-mode=Node,RBAC, anonymous limited, kubelet Webhook authn/authz, readOnlyPort 0, kube-bench
TenancyNamespace bundle (RBAC, PSA, NetworkPolicy, quota); vCluster or separate clusters for hard isolation

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A pipeline gets deployments.apps "orders-api" is forbidden: User "system:serviceaccount:ci:deployer" cannot patch resource "deployments". Which gate failed, and what do you change? Must-know ​

Answer

Answer: Authentication succeeded (the API server named the user); authorization failed with 403 because no binding grants patch on deployments in API group apps in that namespace. Add a Role in the target namespace with patch (and get, list, watch, create, update) on deployments in apps, bind it to that ServiceAccount with a RoleBinding in the same namespace, and confirm with kubectl auth can-i patch deployments.apps -n shop --as=system:serviceaccount:ci:deployer. Not a ClusterRoleBinding, and not cluster-admin. See Request flow and RBAC objects.

2 — Why is create on Pods in a namespace effectively access to all its Secrets and ServiceAccounts, and what limits the damage? Must-know ​

Answer

Answer: A Pod spec chooses its serviceAccountName and its volumes, so the creator can mount any Secret in the namespace (the kubelet reads it with its own identity) and run code with any ServiceAccount's token there; with privileged settings it can reach the node. RBAC cannot see the spec, so the limits are elsewhere: namespaces per trust level (boundaries inside a namespace "should be considered weak"), Pod Security Admission restricted, admission policies, default-deny egress, and auditing Pod creation. See Escalation paths.

3 — What is the difference between a Role bound with a RoleBinding, a ClusterRole bound with a RoleBinding, and a ClusterRole bound with a ClusterRoleBinding? Must-know ​

Answer

Answer: Role + RoleBinding: rules defined and granted in one namespace. ClusterRole + RoleBinding: a reusable rule set (such as view or edit) granted only in the RoleBinding's namespace. ClusterRole + ClusterRoleBinding: granted in every namespace and on cluster-scoped resources and nonResourceURLs. The binding decides the scope, not the role kind. See RBAC objects.

4 — Your Laravel app never calls the Kubernetes API. Which three settings make sure a code-execution bug in it cannot use the API either? Must-know ​

Answer

Answer: A dedicated ServiceAccount (shop-web) with no RoleBindings; automountServiceAccountToken: false on the ServiceAccount and on the Pod template, so no token file exists; and a default-deny egress NetworkPolicy that allows only DNS, MySQL and Redis, so the API server (and the cloud metadata endpoint) is unreachable. A post-deploy test can assert that the token file is absent and the API port does not answer. See Laravel.

5 — How do bound, projected ServiceAccount tokens differ from the old token Secrets, and what does --service-account-extend-token-expiration change? Must-know ​

Answer

Answer: Legacy kubernetes.io/service-account-token Secrets "don't expire and don't rotate". Projected tokens come from the TokenRequest API, are bound to the Pod (invalid once it is deleted), carry an audience and an expiry (default 1 hour, minimum 600 s), and the kubelet refreshes them at 80 % of TTL. With the default --service-account-extend-token-expiration=true, admission-injected tokens are extended "up to 1 year" for clients that never re-read the file; the documented payload shows exp − iat = 365 days and warnafter at 3,607 s. Tokens you project yourself are not extended. See ServiceAccounts and the token, byte for byte.

6 — You label a namespace pod-security.kubernetes.io/enforce: restricted and a team's Deployment applies cleanly, but no Pods appear. Why, and how should the label have been rolled out? Important ​

Answer

Answer: Enforce mode is applied only to Pods, not to workload resources, so the Deployment is accepted and the ReplicaSet's Pod creations are rejected (visible as FailedCreate events). Roll out with kubectl label --dry-run=server to list violators, then warn and audit at restricted while enforce stays at baseline, fix the manifests, and only then set enforce: restricted with a pinned enforce-version. See Pod Security Admission.

7 — A Kyverno upgrade goes wrong and every kubectl apply in the cluster now hangs for ten seconds and fails. Explain the mechanism and the two-level fix. Important ​

Answer

Answer: If Kyverno's webhooks are registered with failurePolicy: Fail (the API default, and what a fail-closed security set-up uses), the API server waits for the webhook up to timeoutSeconds (default 10) and, when the call fails, rejects the request. If the webhook also matches its own namespace, its Pods cannot be recreated. Immediate fix: restore the webhook Deployment or temporarily delete the webhook configuration (and re-apply via GitOps afterwards). Durable fix: exclude kube-system and the engine's namespace, matchConditions for system users, several replicas with a PDB, short timeouts, and move simple rules to ValidatingAdmissionPolicy, which runs in-process. See Admission webhooks.

8 — When would you write a ValidatingAdmissionPolicy instead of a Kyverno or Gatekeeper policy, and when not? Important ​

Answer

Answer: Use a VAP when the rule is an expression over the object, its namespace, the request and optional parameters (required labels, no :latest, limits present, non-root): it is evaluated inside kube-apiserver, so there is no webhook to fail or slow down; roll out with [Warn, Audit] then [Deny]. Use an engine when you need external data (image signatures, registry lookups), mutation or generation beyond MutatingAdmissionPolicy, background reports on existing objects, or exceptions workflows. See ValidatingAdmissionPolicy and Policy engines.

9 — Write down an audit policy strategy that lets you alert on exec and Secret reads without leaking Secret values into the log. Important ​

Answer

Answer: Rules are first-match: start with None for health endpoints and noisy system watches; then Metadata for secrets, configmaps and serviceaccounts/token (who, verb, name, response code, but never the body); Metadata for pods/exec, pods/attach, pods/portforward, pods/ephemeralcontainers; RequestResponse for RBAC and admission configuration changes; Request for workload writes; Metadata as the catch-all; omit RequestReceived. Ship to a SIEM and alert on those resources and on 403 bursts. See Audit logging.

10 — After applying default-deny-all in shop, every Pod logs "could not resolve host". What is missing, and what is the one-dash YAML trap to avoid when you fix the ingress rules? Important ​

Answer

Answer: Default-deny egress also blocks DNS; add an egress policy for all Pods to kube-dns in kube-system on UDP and TCP 53. When allowing traffic from the ingress controller, put namespaceSelector and podSelector in the same from entry (controller Pods in the ingress namespace); as two entries they mean "any Pod in that namespace OR those labelled Pods here". And confirm the CNI enforces NetworkPolicy at all. See NetworkPolicy.

11 — How does IRSA let a Pod call S3 without access keys, and what still needs blocking? Good to know ​

Answer

Answer: The ServiceAccount is annotated with an IAM role ARN; the Pod gets a projected token with audience sts.amazonaws.com; the AWS SDK calls sts:AssumeRoleWithWebIdentity, and STS verifies the token against the cluster's public OIDC discovery keys and the role's trust policy (issuer, audience, sub = system:serviceaccount:<ns>:<sa>), then returns short-lived credentials. On EKS the node's instance-metadata credentials stay reachable from Pods unless egress to 169.254.169.254 is denied (EKS Pod Identity instead uses its agent on the link-local 169.254.170.23, which must stay reachable); on GKE the metadata address must stay open because Workload Identity serves credentials through it. GKE Workload Identity and Azure Workload Identity follow the same token-exchange idea. See Workload identity.

12 — Which kube-apiserver and kubelet settings would you check first on a self-managed cluster, and what tool reports them against the CIS Kubernetes Benchmark? Good to know ​

Answer

Answer: API server: --authorization-mode=Node,RBAC (the flag defaults to AlwaysAllow when no authorization config is set), anonymous access limited to health endpoints, --audit-policy-file set, --encryption-provider-config, --kubelet-certificate-authority, --profiling=false, NodeRestriction enabled. Kubelet: anonymous authentication off, webhook token authentication, Webhook authorization, read-only port 0 (all flag defaults are the unsafe values). kube-bench runs the CIS checks as a Job; on managed clusters only the node checks apply. See Hardening.

13 — A developer says "I have no Secrets access, but kubectl auth can-i create pods/exec -n payments says yes." Why does that matter, and what would you grant instead? Must-know ​

Answer

Answer: pods/exec runs commands inside a running container, which can read whatever that container can: its mounted Secrets, its environment variables, its ServiceAccount token. It is a separate subresource, so it is granted explicitly somewhere (check bindings with --list). Grant pods/log for routine debugging, and put exec behind a break-glass group used through impersonation, with audit alerts on pods/exec. See Rules.

Glossary ​

TermMeaning
AuthenticationEstablishing who sent a request: client certificate, bearer token (OIDC, ServiceAccount), authenticating proxy; failure is 401
AuthorizationDeciding whether the authenticated user may perform the verb on the resource; authorizers in order, default deny, failure is 403
Admission controlPlugins and webhooks that mutate and validate objects after authorization, before storage
Request flowAuthentication → authorization → mutating admission → schema validation → validating admission → etcd, with audit events
Client certificatesX.509 certs signed by the cluster CA; CN is the username, O fields are groups
OIDCOpenID Connect; the API server accepts the IdP's id_token as a bearer token
AuthenticationConfigurationapiserver.config.k8s.io/v1 file (--authentication-config) with JWT authenticators and anonymous settings; stable in v1.34
system:anonymous / system:unauthenticatedUser and group of requests without credentials
system:mastersGroup that bypasses all authorization; bound to cluster-admin by default
ServiceAccountNamespaced identity for workloads; username system:serviceaccount:<ns>:<name>
ServiceAccount tokenJWT signed by the API server identifying a ServiceAccount
Bound service account tokenToken tied to a Pod, Secret or Node; invalid once that object is gone
Projected tokenserviceAccountToken source of a projected volume, written and refreshed by the kubelet
TokenRequest APIserviceaccounts/token subresource that issues time-limited, audience-bound tokens
automountServiceAccountTokenServiceAccount or Pod field; false stops the default token volume (Pod setting wins)
kube-root-ca.crtConfigMap in every namespace with the CA bundle for verifying the API server
RBACRole-based access control: rbac.authorization.k8s.io/v1, purely additive rules
Role / ClusterRoleNamespaced / cluster-wide set of rules
RoleBinding / ClusterRoleBindingGrants a role's rules to subjects in one namespace / everywhere
roleRefThe role a binding grants; immutable
Verbsget list watch create update patch delete deletecollection; special: bind, escalate, impersonate, approve
Resources and subresourcesPlural type names (pods) and their sub-paths (pods/log, pods/exec, deployments/scale)
resourceNamesRule restriction to named objects; not for top-level create or deletecollection
nonResourceURLsPaths like /healthz, /metrics in ClusterRole rules
Aggregated ClusterRoleClusterRole whose rules are the union of ClusterRoles selected by its aggregationRule
Default ClusterRolesview, edit, admin, cluster-admin plus system:* component roles; auto-reconciled
kubectl auth can-iCLI over SelfSubjectAccessReview; --list shows all rules in a namespace
ImpersonationImpersonate-* headers (kubectl --as, --as-group) to act as another identity; needs the impersonate verb
SelfSubjectAccessReview / SubjectAccessReviewAPIs asking the authorizer chain for a decision about yourself / anyone
Least privilegeGranting the minimum verbs on the minimum resources in the minimum namespaces
Escalate / bind verbsRBAC verbs that bypass the checks preventing users from granting permissions they lack
Node authorizerAuthorizer limiting kubelets to objects related to Pods on their node
NodeRestrictionAdmission plugin limiting what kubelets may modify
Workload identityExchanging a projected ServiceAccount token for cloud credentials
IRSAIAM Roles for Service Accounts on EKS: OIDC provider + eks.amazonaws.com/role-arn
EKS Pod IdentityEKS API associations and an agent DaemonSet instead of an OIDC provider
GKE Workload IdentityWorkload Identity Federation for GKE: principals in PROJECT_ID.svc.id.goog
Azure Workload IdentityEntra Workload ID: federated identity credential, azure.workload.identity/* annotation and label
Pod Security StandardsThree cumulative levels: privileged, baseline, restricted
Pod Security AdmissionBuilt-in admission plugin applying the levels per namespace via labels
PSA modesenforce (reject Pods), audit (annotate audit events), warn (client warnings)
PSA exemptionsUsernames, runtime classes and namespaces skipped entirely; static configuration
Admission webhooksHTTPS callbacks registered by MutatingWebhookConfiguration / ValidatingWebhookConfiguration
failurePolicyFail (default, reject on webhook error) or Ignore (allow)
matchConditionsCEL pre-filters on webhooks and policies (max 64)
ValidatingAdmissionPolicyIn-process CEL validation, stable v1.30; effective only with a binding
MutatingAdmissionPolicyIn-process CEL mutation (apply configuration or JSON patch), stable v1.36
CELCommon Expression Language used by VAP, MAP, CRD validation, authentication config
KyvernoKubernetes-native policy engine; ValidatingPolicy, ImageValidatingPolicy, legacy ClusterPolicy
OPA GatekeeperPolicy engine running Rego from ConstraintTemplates, enforced through Constraints
ConstraintTemplate / ConstraintGatekeeper's Rego + schema / its instantiation with match and parameters
cosignSigstore tool for signing and verifying OCI artefacts, keyless with OIDC identities
Image signature verificationAdmission check that an image digest carries a trusted signature
Audit policyaudit.k8s.io/v1 Policy; rules evaluated in order, first match sets the level
Audit levelsNone, Metadata, Request, RequestResponse
Audit stagesRequestReceived, ResponseStarted, ResponseComplete, Panic
Audit backendsLog (file) and webhook (HTTP), with blocking or batch modes
NetworkPolicynetworking.k8s.io/v1 L3/L4 allow-list for Pods, implemented by the CNI
Default denyA policy selecting all Pods with no rules, isolating them in the listed directions
ipBlockCIDR peer in a NetworkPolicy, meant for cluster-external addresses
CNIContainer Network Interface plugin (Calico, Cilium, cloud CNIs) that also enforces NetworkPolicy
CiliumNetworkPolicyCilium's policy kind with L7 HTTP/DNS rules, toFQDNs and entities
Calico GlobalNetworkPolicyCalico's cluster-wide, ordered policy with deny rules
Encryption at restEncrypting Secrets in etcd via --encryption-provider-config (KMS recommended)
CIS Kubernetes BenchmarkConsensus configuration guidelines for Kubernetes (2.1.0) and managed variants
kube-benchAqua Security tool running the CIS checks as a Job
Multi-tenancySharing a cluster between teams or customers with isolation controls
Namespace boundaryThe scope of RBAC, PSA, NetworkPolicy and quota; weak inside, the unit of trust between
Hierarchical namespacesHNC pattern of sub-namespaces inheriting policy (repository archived)
vClusterVirtual clusters: a tenant control plane running in a host-cluster namespace
client-goThe Go client library for the Kubernetes API (k8s.io/client-go)
In-cluster configrest.InClusterConfig(): API address from env, token and CA from the ServiceAccount mount

References ​

Built by Morteza Negahi