Skip to content

chore(helm): trim over-broad ClusterRole permissions - #386

Merged
WentingWu666666 merged 4 commits into
documentdb:mainfrom
WentingWu666666:developer/wentingwu/helm-rbac-audit
May 26, 2026
Merged

WentingWu666666 merged 4 commits into
documentdb:mainfrom
WentingWu666666:developer/wentingwu/helm-rbac-audit

Conversation

@WentingWu666666

@WentingWu666666 WentingWu666666 commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Trim the operator's and wal-replica's ClusterRoles to the set actually consumed by the controllers, narrowing the blast radius of a ServiceAccount-token compromise.

Correction (commit 5bcd2e5)

E2E run #26109274996 surfaced an RBAC escalation failure that my initial trim caused: the operator's EnsureServiceAccountRoleAndRoleBinding (documentdb_controller.go:452-458) creates a per-DocumentDB namespaced Role granting pods, services, endpoints CRUD to the CNPG cluster's ServiceAccount. K8s RBAC escalation rules require the grantor to already hold every verb being granted, so the operator's ClusterRole must keep these as full CRUD.

Restored in 5bcd2e5:

  • operator ClusterRole: ""/pods full CRUD, ""/endpoints full CRUD
  • wal-replica ClusterRole: ""/endpoints full CRUD (defensive)

Methodology gap: my grep audit only catches &<group>v1.<Kind>{} instantiated for client calls; it missed resources the operator only grants via rbacv1.PolicyRule string literals. Future RBAC audits must also grep PolicyRule{ and Resources: []string{...} construction sites. Tracked in #390.

All other trims from a6e7015 remain none of them appear in any PolicyRule grant.

How the trim was decided

Two-source audit:

  1. +kubebuilder:rbac markers in operator/src/internal/. Found markers in only 4 files; backup, scheduledbackup, physical_replication, util, and cnpg_sync have none. So make manifests produces a role.yaml that's missing ~70% of the operator's real permission needs. The Helm chart has therefore been hand-maintained and drifted. Fixing the markers so the chart round-trips through make manifests is the right long-term fix and is tracked separately (see RBAC: +kubebuilder:rbac markers are incomplete chart and \make manifests\ have drifted #390).
  2. Actual API call sites + PolicyRule construction sites: grep across operator/src/internal/ for every &<group>v1.<Kind>{} passed to client.Get/List/Create/Update/Patch/Delete/Watch, plus every rbacv1.PolicyRule{...} and Resources: []string{...} literal where the operator grants permissions to other SAs. This is the empirical floor of "what the controllers actually touch or grant."

Anything in the chart that is granted but never referenced by code (as a client call OR a grant) is removed.

What changes operator ClusterRole (templates/05_clusterrole.yaml)

Removed Why it's dead
""/namespaces (full CRUD) No corev1.Namespace references in any controller; user creates target namespaces.
rbac/clusterrolebindings (full CRUD) util.go CreateRole / CreateRoleBinding create namespaced RBAC only.
apps/statefulsets, apps/deployments (full CRUD) Never instantiated; CNPG owns StatefulSet management for database pods.
batch/jobs (full CRUD) No &batchv1.Job{} anywhere in operator/src.
metrics.k8s.io/pods (entirely) No controller calls the metrics API.
""/leases Wrong API group. Leader election uses coordination.k8s.io/leases (granted separately); core leases was a historical pre-1.14 location.
cert-manager.io/clusterissuers CR exposes IssuerRef.Kind: ClusterIssuer but the operator only references it by name in the Certificate spec it creates cert-manager itself resolves it. Operator never Get/Lists ClusterIssuer.
cert-manager.io/certificates/finalizers Certificate controller never sets finalizers on cert-manager objects (only on its own DocumentDB CR).
Narrowed From To Why
""/secrets full CRUD get,list,watch Only certificate_controller.go:115 reads TLS Secrets; no controller writes them; no PolicyRule grants secrets.

""/pods and ""/endpoints remain full CRUD see Correction above.

What changes wal-replica ClusterRole (templates/03_documentdb_wal_replica.yaml)

Same dead grants removed where unambiguous (""/leases, metrics.k8s.io/pods). ""/endpoints restored (see Correction). The wal-replica plugin's Go source lives in the cnpg-i-wal-replica repo, so the remaining rules are kept as-is until the plugin ships its own RBAC markers.

What is intentionally NOT changed (yet)

These look trimmable but need per-controller audit-log validation to be safe:

  • ""/configmaps physical_replication writes them; verbs probably correct.
  • ""/services, ""/serviceaccounts, rbac/roles, rbac/rolebindings util.go creates them, but delete verbs need exec-path audit to confirm.
  • ""/persistentvolumeclaims current code uses get,list,watch,create,delete, no update/patch; conservative to leave as-is.
  • coordination.k8s.io/leases required for leader election, but should ideally be a Role in the operator namespace, not a ClusterRole. (Migration step, not just a verb change.)

These belong in a separate PR alongside the marker fix.

Tests

  • helm lint
  • helm upgrade against a live kind cluster with an existing DocumentDB CR (documentdb-cluster in documentdb-preview-ns)
  • Restarted operator post-fix: per-CR Role documentdb-cluster re-created successfully with pods,services,endpoints CRUD; no forbidden log entries.
  • Operator pod stays 1/1 Running, no restart, no forbidden / cannot list / cannot get / cannot create / denied / RBAC log entries over 2 minutes of normal reconciliation.
  • pv-controller, documentdb-controller, certificate-controller, backup-controller, scheduledbackup-controller all confirmed reconciling post-upgrade.

Follow-ups

Refs

#381

@documentdb-triage-tool documentdb-triage-tool Bot added the enhancement New feature or request label May 19, 2026
@documentdb-triage-tool

Copy link
Copy Markdown

🤖 Auto-triaged by documentdb-triage-tool.

Applied: enhancement
Project fields suggested: Component manifests · Priority P1 · Effort M · Status In Progress
Confidence: 0.82 (mixed)

Reasoning

effort from diff stats (6+6 LOC, 2 files); LLM: Security hardening PR that removes overly broad ClusterRole permissions (unused cluster-wide CRUD on namespaces and clusterrolebindings) which could enable cluster takeover on ServiceAccount compromise — a meaningful security risk worth treating as P1.

If a label is wrong, remove it manually and ping @patty-chow so the rules can be tuned. The bot will not re-label items that already have component labels.

@WentingWu666666

Copy link
Copy Markdown
Collaborator Author

Filed #390 for the marker-drift follow-up referenced in the description.

wentingwu000 and others added 2 commits May 19, 2026 12:02
Remove permissions the operator does not actually use:

- \
amespaces\ CRUD in the operator ClusterRole. A grep of the
  controller code finds no \corev1.Namespace\ references; the operator
  reconciles into namespaces a user already created.
- \clusterrolebindings\ in the operator ClusterRole. The operator only
  creates namespaced \Role\ / \RoleBinding\ (see
  \internal/utils/util.go\), never cluster-scoped RBAC.
- \
amespaces\ CRUD in the wal-replica-manager ClusterRole and drop
  the \# TODO trim this down\ comment. The wal-replica plugin runs in
  cnpg-system and does not create namespaces.
- Narrow \metrics.k8s.io/pods\ to read-only (\get/list/watch\) in both
  ClusterRoles. The metrics API is a read-only API; create/update/patch
  /delete verbs are meaningless.

Verified in local kind cluster: operator pod is Running, no
\orbidden\ log entries after upgrade.

Refs documentdb#381

Co-authored-by: Copilot <[email protected]>
Signed-off-by: WentingWu666666 <[email protected]>
Follow-up to the previous trim on this branch. A code-side audit
(grep for `&<group>v1.<Kind>{}` instantiated for any `client.Get/List/
Create/Update/Patch/Delete/Watch` call across operator/src/internal/)
shows several rules in the operator's ClusterRole reference resources
that no controller ever touches. Remove them, and trim Secret verbs
to read-only since no controller writes Secrets.

Operator ClusterRole (templates/05_clusterrole.yaml):

- Remove `apps/statefulsets,deployments`. The operator never
  instantiates `appsv1.Deployment` / `appsv1.StatefulSet`; CNPG owns
  StatefulSet management for the database pods.
- Remove `batch/jobs`. No `&batchv1.Job{}` anywhere in operator/src.
- Remove `metrics.k8s.io/pods` entirely. The previous commit narrowed
  the verbs but no controller calls the metrics API at all.
- Remove `""/endpoints`. Never instantiated.
- Remove `""/leases`. Wrong API group: leader election uses
  `coordination.k8s.io/leases` (already granted separately); core
  `leases` was a historical pre-1.14 location and is dead in our stack.
- Remove `cert-manager.io/clusterissuers`. The CR exposes a
  `ClusterIssuer` option in `IssuerRef.Kind`, but the operator only
  *references* it by name in the Certificate spec it creates;
  cert-manager itself resolves the ClusterIssuer. The operator never
  Get/Lists ClusterIssuer.
- Remove `cert-manager.io/certificates/finalizers`. The certificate
  controller never sets a finalizer on cert-manager objects (only on
  its own DocumentDB CR).
- Split `""/pods`: drop full CRUD; grant `get,list,watch` only.
  `pods/exec` create remains for the documentdb_controller exec path.
- Narrow `""/secrets` to `get,list,watch`. The only controller that
  touches Secrets is certificate_controller, and it only Gets
  cert-manager-issued TLS Secrets to read into Cluster spec.

wal-replica ClusterRole (templates/03_documentdb_wal_replica.yaml):

- Remove `""/endpoints` (never referenced).
- Remove `""/leases` (wrong API group; coordination.k8s.io/leases
  already granted).
- Remove `metrics.k8s.io/pods` (no metrics-API consumer).

The wal-replica plugin's Go source lives in a separate repo
(cnpg-i-wal-replica), so the remaining rules are kept as-is until the
plugin ships its own RBAC markers and we can do a precise audit. Added
a comment to that effect on the rule block.

Process note: `+kubebuilder:rbac` markers in operator/src/internal/ are
incomplete (backup, scheduledbackup, physical_replication, util, and
cnpg_sync have zero markers). The Helm chart has therefore been
hand-maintained and drifted from `make manifests` output. Wiring the
markers up so `make manifests` round-trips with the chart's role
content is tracked separately and is the right long-term fix; this PR
just removes the obvious dead grants that can be verified by grep.

Verified locally:

- `helm lint` clean.
- `helm upgrade` against a live kind cluster with an active
  `DocumentDB` CR (documentdb-cluster in documentdb-preview-ns)
  succeeded with no operator restart.
- Operator logs for 2 minutes post-upgrade contain zero `forbidden` /
  `cannot list` / `cannot get` / `cannot create` / `denied` / `RBAC`
  entries; pv-controller, documentdb-controller, certificate-controller,
  backup-controller, and scheduledbackup-controller all continue to
  reconcile normally.

Refs documentdb#381

Signed-off-by: WentingWu666666 <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: WentingWu666666 <[email protected]>
@WentingWu666666
WentingWu666666 force-pushed the developer/wentingwu/helm-rbac-audit branch from db95162 to a6e7015 Compare May 19, 2026 16:02
@WentingWu666666
WentingWu666666 marked this pull request as ready for review May 19, 2026 16:02
@WentingWu666666
WentingWu666666 requested a review from xgerman as a code owner May 19, 2026 16:03
Copilot AI review requested due to automatic review settings May 19, 2026 16:03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR reduces the Helm chart’s cluster-wide RBAC permissions for the DocumentDB operator and the wal-replica manager, aiming to limit the blast radius of a ServiceAccount token compromise by removing resources/verbs that are not exercised by the codebase.

Changes:

  • Trimmed the operator ClusterRole by removing unused resources (e.g., apps/*, batch/jobs, core endpoints/leases) and narrowing pods and secrets to read-only.
  • Trimmed the wal-replica ClusterRole by removing clearly dead rules (e.g., core endpoints/leases, metrics API) and documenting the rationale/constraints.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
operator/documentdb-helm-chart/templates/05_clusterrole.yaml Removes several unused permissions; narrows pods and secrets; adds explanatory comments.
operator/documentdb-helm-chart/templates/03_documentdb_wal_replica.yaml Removes dead grants from wal-replica RBAC and replaces TODO with an auditability note.

Comment on lines 15 to 17
- apiGroups: [""]
resources: ["services", "pods", "endpoints", "leases", "serviceaccounts", "configmaps", "namespaces", "persistentvolumeclaims", "pods/exec"]
resources: ["services", "serviceaccounts", "configmaps", "persistentvolumeclaims", "pods/exec"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
Comment on lines 41 to 43
- apiGroups: ["cert-manager.io"]
resources: ["certificates", "certificates/status", "certificates/finalizers", "issuers", "clusterissuers"]
resources: ["certificates", "certificates/status", "certificates/finalizers", "issuers"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
wentingwu000 and others added 2 commits May 19, 2026 13:23
…ants

E2E (run #26109274996) surfaced an RBAC escalation failure: the
operator's EnsureServiceAccountRoleAndRoleBinding
(documentdb_controller.go:452-458) creates a per-DocumentDB Role
granting pods, services, endpoints CRUD to the CNPG cluster's
ServiceAccount. K8s RBAC escalation requires the grantor to already
hold every verb being granted, so the operator's ClusterRole must
keep these as full CRUD.

Restore on the operator ClusterRole:
- ""/pods full CRUD (was narrowed to get,list,watch in a6e7015)
- ""/endpoints full CRUD (was removed in a6e7015)

Restore on the wal-replica ClusterRole:
- ""/endpoints full CRUD (defensive)

Methodology update: the grep used in a6e7015 only catches
&<group>v1.<Kind>{} instantiated for client calls; it missed
resources that the operator only *grants* via rbacv1.PolicyRule
string literals. Future RBAC audits must also grep PolicyRule{
and Resources: []string{...} construction sites.

Other a6e7015 trims (statefulsets/deployments, jobs, metrics.k8s.io,
""/leases, clusterissuers, certificates/finalizers, secrets RO)
remain - none of them appear in any PolicyRule grant.

Refs documentdb#381

Signed-off-by: WentingWu666666 <[email protected]>
Co-authored-by: Copilot <[email protected]>
Two narrowings flagged on PR documentdb#386 by the Copilot reviewer; both verified
against operator/src code:

1. Split `pods/exec` into its own rule with `verbs: [create]`.
   The exec subresource is POST-only; update/patch/delete on it have no
   meaning. Other core resources (pods, services, endpoints,
   serviceaccounts, configmaps, persistentvolumeclaims) keep full CRUD.

2. Narrow cert-manager grant. certificate_controller.go only calls
   `Get` and `Create` on Certificates and Issuers, and uses
   `Owns()` (which requires watch). It never Updates, Patches,
   Deletes, or sets Finalizers on cert-manager objects (only on its own
   DocumentDB CR, which is granted via `dbs/finalizers`). Drop
   `certificates/status` and `certificates/finalizers`, narrow verbs
   to `get, list, watch, create`.

Tested: helm lint, helm upgrade on kind, deleted and re-created the
per-CR Role to confirm EnsureServiceAccountRoleAndRoleBinding still
succeeds with no escalation error.

Refs documentdb#381

Signed-off-by: WentingWu666666 <[email protected]>
Co-authored-by: Copilot <[email protected]>
@WentingWu666666
WentingWu666666 merged commit fe31d8a into documentdb:main May 26, 2026
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request triage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants