Repository navigation
chore(helm): trim over-broad ClusterRole permissions - #386
WentingWu666666 merged 4 commits into
Conversation
|
🤖 Auto-triaged by documentdb-triage-tool. Applied: Reasoningeffort 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 |
|
Filed #390 for the marker-drift follow-up referenced in the description. |
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]>
db95162 to
a6e7015
Compare
There was a problem hiding this comment.
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
ClusterRoleby removing unused resources (e.g.,apps/*,batch/jobs, coreendpoints/leases) and narrowingpodsandsecretsto read-only. - Trimmed the wal-replica
ClusterRoleby removing clearly dead rules (e.g., coreendpoints/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. |
| - 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"] |
| - 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"] |
…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]>
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 grantingpods, services, endpointsCRUD 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:""/podsfull CRUD,""/endpointsfull CRUD""/endpointsfull CRUD (defensive)Methodology gap: my grep audit only catches
&<group>v1.<Kind>{}instantiated for client calls; it missed resources the operator only grants viarbacv1.PolicyRulestring literals. Future RBAC audits must also grepPolicyRule{andResources: []string{...}construction sites. Tracked in #390.All other trims from
a6e7015remain none of them appear in any PolicyRule grant.How the trim was decided
Two-source audit:
+kubebuilder:rbacmarkers inoperator/src/internal/. Found markers in only 4 files; backup, scheduledbackup, physical_replication, util, and cnpg_sync have none. Somake manifestsproduces arole.yamlthat'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 throughmake manifestsis the right long-term fix and is tracked separately (see RBAC: +kubebuilder:rbac markers are incomplete chart and \make manifests\ have drifted #390).operator/src/internal/for every&<group>v1.<Kind>{}passed toclient.Get/List/Create/Update/Patch/Delete/Watch, plus everyrbacv1.PolicyRule{...}andResources: []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)""/namespaces(full CRUD)corev1.Namespacereferences in any controller; user creates target namespaces.rbac/clusterrolebindings(full CRUD)util.goCreateRole/CreateRoleBindingcreate namespaced RBAC only.apps/statefulsets,apps/deployments(full CRUD)batch/jobs(full CRUD)&batchv1.Job{}anywhere inoperator/src.metrics.k8s.io/pods(entirely)""/leasescoordination.k8s.io/leases(granted separately); coreleaseswas a historical pre-1.14 location.cert-manager.io/clusterissuersIssuerRef.Kind: ClusterIssuerbut 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""/secretsget,list,watchcertificate_controller.go:115reads TLS Secrets; no controller writes them; no PolicyRule grantssecrets.""/podsand""/endpointsremain 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).""/endpointsrestored (see Correction). The wal-replica plugin's Go source lives in thecnpg-i-wal-replicarepo, 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:
""/configmapsphysical_replication writes them; verbs probably correct.""/services,""/serviceaccounts,rbac/roles,rbac/rolebindingsutil.gocreates them, butdeleteverbs need exec-path audit to confirm.""/persistentvolumeclaimscurrent code usesget,list,watch,create,delete, noupdate/patch; conservative to leave as-is.coordination.k8s.io/leasesrequired for leader election, but should ideally be aRolein the operator namespace, not aClusterRole. (Migration step, not just a verb change.)These belong in a separate PR alongside the marker fix.
Tests
helm linthelm upgradeagainst a live kind cluster with an existing DocumentDB CR (documentdb-clusterindocumentdb-preview-ns)documentdb-clusterre-created successfully withpods,services,endpointsCRUD; noforbiddenlog entries.1/1 Running, no restart, noforbidden/cannot list/cannot get/cannot create/denied/RBAClog entries over 2 minutes of normal reconciliation.Follow-ups
+kubebuilder:rbacmarkers across all controllers somake manifestsproduces arole.yamlthat matches the chart, and extend audit methodology to grepPolicyRule{construction sites, then add CI assertion.leasesfrom ClusterRole to namespace-scoped Role.Refs
#381