Repository navigation
Description
Describe the bug
After the operator rotates the internal CA certificate ({cluster}-ca secret), it does not rolling-restart the PostgreSQL pods. The pods continue serving TLS certificates signed by the old CA. When the operator then tries to query pod status via HTTPS (port 8000), it validates against the new CA and gets:
tls: failed to verify certificate: x509: certificate signed by unknown authority
(possibly because of "x509: ECDSA verification failure" while trying to verify
candidate authority certificate "{cluster}")
This creates a deadlock: the operator needs pod status to manage the cluster (including triggering rolling restarts), but it cannot get pod status because of the TLS mismatch. The operator enters an infinite requeue loop every ~15 seconds, and the cluster is completely down — no primary is elected, the -rw service has zero endpoints, and all client connections fail.
The only recovery is manual pod deletion. The operator cannot self-heal from this state.
Reproduction
This occurred on two independent clusters running identical configurations on the same night, confirming it is deterministic and not a transient race condition.
Environment
- Operator version:
ghcr.io/cloudnative-pg/cloudnative-pg:1.28.1(Helm chart 0.27.1) - Kubernetes: k3s v1.31
- Cluster config: 3 instances,
local-pathstorage class, operator-managed certificates (default) - No cert-manager — using CNPG's built-in PKI
Timeline (Cluster 1)
2026-04-11T04:01:06Z— CA secretshared-pg-carotated (newcreationTimestamp)- Pods
shared-pg-2,shared-pg-4,shared-pg-5were not restarted by the operator - Operator entered infinite requeue loop with x509 errors for all 3 pods
-rwservice had zero endpoints — full database outage- Downstream services (Authelia, etc.) lost authentication — full auth outage
- ~1 hour of downtime until manual pod deletion
Timeline (Cluster 2)
2026-04-12T03:01:03Z— CA secret rotated (nearly identical time, consistent with deterministic 90-day rotation)- Same deadlock pattern — operator requeue loop every ~15 seconds
- ~3 hours of downtime until manual intervention
Operator logs (captured live)
The requeue loop runs continuously at ~15-second intervals. Representative sample showing all 3 pods failing simultaneously:
{"level":"info","ts":"2026-04-12T03:58:31Z","msg":"Cannot extract Pod status",
"controller":"cluster","controllerGroup":"postgresql.cnpg.io","controllerKind":"Cluster",
"Cluster":{"name":"shared-pg","namespace":"cnpg-system"},
"podName":"shared-pg-5",
"error":"Get \"https://10.42.1.80:8000/pg/status\": tls: failed to verify certificate: x509: certificate signed by unknown authority (possibly because of \"x509: ECDSA verification failure\" while trying to verify candidate authority certificate \"shared-pg\")"}
{"level":"info","ts":"2026-04-12T03:58:31Z",
"msg":"Failed to extract instance status from ready instances. Attempting to requeue..."}This repeated every ~15 seconds for the entire duration of the outage (1-3 hours). Full requeue timeline from one cluster: 03:00 → 04:00 UTC — 240+ requeue cycles with zero progress.
Root cause analysis
The ensureCASecret() → renewCASecret() path correctly updates the CA secret in-place using r.Update(). However, after the CA is rotated:
- The new CA cert is written to the
{cluster}-casecret - The operator starts using the new CA to verify TLS connections to pods
- But the pods still have TLS certificates signed by the old CA loaded in memory
- The operator's status probe (
GET https://{pod-ip}:8000/pg/status) fails with x509 verification error - Without pod status, the reconciler cannot determine cluster state or trigger rolling restarts
- The reconciler's only action is to requeue — creating an infinite loop with no escape
The fundamental issue is that the CA rotation code path does not trigger a rolling restart of the cluster pods. The operator assumes pods will pick up the new certificates, but since the certificates are baked into the pod's TLS configuration at startup, they are never refreshed without a pod restart.
Expected behavior
After rotating the CA certificate, the operator should:
- Detect that existing pods have TLS certificates signed by the old CA (e.g., by comparing
{cluster}-casecret's update timestamp against pod start times) - Trigger a rolling restart of all cluster pods so they pick up certificates signed by the new CA
- At minimum: if the operator detects persistent x509 verification failures for all pods after a CA rotation, it should escalate to a rolling restart rather than requeueing indefinitely
Workaround
Manually delete all PostgreSQL pods (without deleting PVCs):
kubectl delete pod -n cnpg-system -l cnpg.io/cluster=shared-pgThe operator recreates pods with fresh certificates signed by the current CA, and the cluster recovers.
Additional context
- The CA rotation appears to be triggered deterministically based on the
certificates.certificateDurationconfiguration (default 90 days) - Both clusters rotated within minutes of each other at ~03:01 UTC, consistent with being deployed at the same time
- The
Periodic TLS certificates maintenancelog message appears hourly but does not resolve the issue - After manual pod deletion, the operator logs show
"Cluster has become healthy"— confirming the cluster itself is fine, only the TLS state was broken - The operator eventually created a new pod (
shared-pg-6) to "reattach a PVC" but this new pod also initially failed with the same x509 errors until it fully initialized with new CA certs
🤖 This bug report was generated with Claude Code based on live operator logs and cluster state captured during the incident.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsBacklog
Activity
dosubot commentedon Apr 12, 2026
Hi @Daniel-dev22! I'm Dosu and I’m helping the cloudnative-pg team.
I can confirm this is a real bug and your root cause analysis is largely correct. I traced through the code and can add some specifics on exactly where the gap lies.
The core issue is in
RenewLeafCertificate()[1]. When the CA certificate is renewed viarenewCASecret(), the CA private key is preserved and only theca.crtis updated with fresh validity dates and a new serial number [2]. However,RenewLeafCertificate()— which decides whether to regenerate server TLS certificates in the{cluster}-serversecret — only checks two conditions: (1) whether the server cert itself is expiring, and (2) whether DNS names still match. It does not check whether the server cert is still validly signed by the current CA cert. Since the server cert isn't expired, it skips renewal [3].Why the deadlock forms:
renewCASecret()updatesca.crtin the{cluster}-casecret [4]GetCertificatecallbacks [7], so it could serve a new cert — butRefreshSecrets()fetches the unchanged{cluster}-serversecret [8], which still contains the cert signed by the old CAThere's no dual-CA bundle: the CA cert pool used for verification contains only the single current CA cert [10]. There's no grace period where certificates signed by both old and new CAs are accepted.
Note on the private key detail: since
renewCASecretpreserves the CA private key, certificates signed by the old CA cert should still be cryptographically verifiable by the new CA cert (same public key). The x509 verification failure (ECDSA verification failure) you're seeing is surprising in that context — it may be that Go'sx509.Certificate.Verify()[11] is doing a full chain validation that compares the CA certificate'sAuthorityKeyIdentifieror serial number, not just the cryptographic signature. This would explain why same-key CA renewal still breaks verification.Potential fixes (not exhaustive):
RenewLeafCertificate()should check whether the server cert's issuer matches the current CA cert (e.g., comparing serial numbers or the full CA cert bytes), and force regeneration if they differTo reply, just mention @dosu.
Share context across your team and agents. Try Dosu.
unchangedraman commentedon Apr 17, 2026
I've been digging into this and Dosu's analysis is spot on. The bug appears to be a logic gap in the renewal check rather than a missing rolling-restart path.
The Root Cause
The early return in RenewLeafCertificate() (pkg/certs/k8s.go:108-110) only checks for expiration and DNS name parity. It doesn't validate if the leaf cert was issued by the current CA.
When renewCASecret() rotates the ca.crt (keeping the same private key but updating the serial/validity), the leaf certs remain signed by the now-rotated CA. Because the operator’s fresh TLS context no longer trusts that previous CA instance, but the leaf itself hasn't "expired," the operator returns false on renewal. This keeps the {cluster}-server secret static, preventing a rollout and leading to the x509 deadlock.
Repro Plan
I am testing this on CNPG 1.24.1 (3-instance cluster, operator-managed certs) in an OpenStack/CAPO lab, secrets managed by Openbao and identity only derived from network(NOVA Metadata). I’ll force a CA rotation by bumping the serial on {cluster}-ca and will post the logs confirming the x509 loop before opening the PR.
Proposed Fix
I’d like to take this on. The fix would involve a targeted change in RenewLeafCertificate() to add a third condition:
Issuer Validation: Compare the leaf cert’s AuthorityKeyIdentifier against the current CA’s SubjectKeyIdentifier. If they differ, force a regeneration.
Once the leaf is regenerated, the existing RefreshSecrets() machinery and the dynamic GetCertificate callback in the instance manager should pick it up—likely without needing a pod rollout for the handshake to succeed.
Questions for maintainers:
Is this targeted check preferred, or is there interest in a dual-CA bundle approach to more gracefully handle long-lived connections during rotation?
Does CNPG have an existing helper for comparing AuthorityKeyIdentifier? If not, I’ll add one to pkg/certs.
Since renewCASecret preserves the private key, the most likely explanation is that Go's x509.Verify rejects the chain based on the AuthorityKeyIdentifier / serial mismatch rather than the cryptographic signature. I’ll verify this in my repro and report back.
Daniel-dev22 commentedon Apr 20, 2026
Update — second variant of the same bug
Hit this again in a different form on the same cluster, adding detail because it looks like the bug surfaces in two distinct ways depending on which leaf secret ends up signed by the stale CA.
Variant A (original report above): CA rotates, pods don't restart, the operator's own verification bundle disagrees with what the pods present →
-rwservice drops to 0 endpoints, full outage.Variant B (new): Same root cause —
RenewLeafCertificate()not checking that the leaf was issued by the current CA — but the visible symptom is very different:readyInstances: N-1/N, phaseCreating a new replica-rwservice has endpoints (existing pods keep serving fine because their in-memory certs were loaded before the CA/secret drift){cluster}-{N}-joinpods every few minutes; each one fails withremote error: tls: unknown certificate authorityconnecting to{cluster}-rwasstreaming_replicashared-pg-50-joinbefore intervening)Root cause evidence on my cluster:
{cluster}-caserialE753A12E2C88FDDE1133997CF50C2A21/controller/certificates/client-ca.crtserial: sameE753A12E…{cluster}-serverleaf:openssl verify -CAfile ca.crt tls.crt→ OK{cluster}-replicationleaf (streaming_replica cert):openssl verify→error 20: unable to get local issuer certificateBoth CAs in play have the exact same Subject (
OU={ns}, CN={cluster}), which is presumably why the name-based checks insideRenewLeafCertificate()were happy — only a signature-verify against the current CA's public key catches it.Workaround for Variant B (simpler than the full pod-rotation workaround for Variant A):
kubectl delete secret -n {ns} {cluster}-replication kubectl delete job -n {ns} {cluster}-{N}-join kubectl delete pvc -n {ns} {cluster}-{N}Operator regenerates
{cluster}-replicationfrom the current CA within seconds; the next join pod the operator spawns mounts the fresh secret andpg_basebackupsucceeds. No primary restart needed — running pods already have valid certs from their earlier startup.Quiet follow-on — stale server secret, pods serving anyway: After recovering via the above, I noticed the cluster can end up in a latent state where
{cluster}-serveris also signed by a different CA than{cluster}-cacurrently holds, but running pods don't care because they have their in-memory cert from before the rotation.kubectl get clustershowsreadyInstances: N/Nbut phase flips toInstance Status Extraction Error: HTTP communication issue— which appears to be the operator re-running into Variant A against its own bundle. The ticking time bomb is that the next pod restart (natural eviction, node drain, anything) makes every pod fail to come up because they'll mount the stale server secret fresh.So I think the bug manifests on a spectrum:
-replicationonly → partial-ready cluster, infinite join-retry loop, no outage-server→ running pods fine, but next restart = outageAll three would be fixed by the
AuthorityKeyIdentifiervsSubjectKeyIdentifiercheck @unchangedraman proposed forRenewLeafCertificate()— any mismatch forces leaf regeneration regardless of name match.Reproduced on CNPG 1.28.1 (Helm 0.27.1) / k3s v1.34.2+k3s1 — same setup as the OP, just a second data point on version/environment.
Happy to share kubectl fixture data for either variant if it'd help.
🤖 This bug report was generated with Claude Code based on live operator logs and cluster state captured during the incident.
unchangedraman commentedon Apr 20, 2026
The spectrum framing (Variant B → latent → Variant A) clarifies that this isn't just an "outage on rotation" bug; it's a latent trap that persists even when the cluster reports healthy.
The call chain is identical for both leaf secrets, meaning the fix lands in a single bottleneck:
ensureServerLeafCertificate (internal/controller/cluster_pki.go:229)
ensureReplicationClientLeafCertificate (cluster_pki.go:265)
└─ ensureLeafCertificate (cluster_pki.go:319)
└─ renewAndUpdateCertificate (cluster_pki.go:377)
└─ certs.RenewLeafCertificate (pkg/certs/k8s.go:91)
The early return at k8s.go:108-110—if !expiring && altDNSNamesMatch { return false, nil } is what causes the gap. Extending that condition with a CA-identity check (AKID vs SKID) will cover both variants in one change.
This fix actually restores symmetry with the user-managed path. When a user provides their own TLS secret, the operator hits validateLeafCertificate(), which eventually triggers a proper x509 chain verification.
The bug is that the operator-managed path silently skips this validation if the names match. Adding the identifier comparison to RenewLeafCertificate brings the managed path in line with the (correct) validation logic used for manual certificates.
On In-Memory Reloading
In Variant B, the stale leaf is in
{cluster}-replication— thestreaming_replicaclient cert. Existing pods don't notice because they loaded their replication cert before the rotation. New join pods mount the (now-stale) secret at startup and present its client cert to the primary, which only trusts the rotated CA, sotls: unknown certificate authorityand the join loop starts. Whether the in-memory reload path for the replication cert works without pod restart (it clearly does for the server cert viaSetServerCertificate) — I'll verify during repro.To ensure the PR is bulletproof, could you share scrubbed YAML for:
{cluster}-ca before and after rotation (same key, new serial).
A stale {cluster}-replication (Variant B).
A stale {cluster}-server (Latent state).
I’ll use these to build table-driven tests in pkg/certs/k8s_test.go to ensure RenewLeafCertificate correctly triggers regeneration for all three scenarios.
flmichel commentedon Aug 9, 2026
I don't think
renewCASecretis the cause here. It re-signsca.crtwith the same private key(
internal/controller/cluster_pki.go:221-232), so leaves signed by the old cert still verify againstthe new one. I checked both cases:
CA renewed in place with the same key, which is what
renewCASecretdoes: the existing leaf stillverifies against the renewed CA, no error.
CA replaced with a new key pair: the existing leaf stops verifying, with the same error as in this
report.
So a scheduled renewal can't produce that error. The CA key itself has to have changed.
The
creationTimestampchanged, andrenewCASecretends inr.Update,which never changes it, so the Secret was deleted and recreated rather than renewed. The only code
that recreates it is
ensureCASecret:194, andcerts.go:447always generates a new key there.That's also why the YAML asked for above won't reproduce it. "Same key, new serial" is the in place
renewal, the one that verifies fine. You don't need cluster YAML for any of the three states anyway,
CreateRootCAandCreateAndSignPairbuild them all in the test.The gap is the early return at
pkg/certs/k8s.go:114, which never checks that the leaf still chainsto the CA it was handed. This also looks like a prerequisite for #11121: today the CA and the
leaves share one duration, so they expire together and the leaves get re-signed anyway, which hides
this most of the time. Give the CA its own longer lifetime and that stops being true.
I have a fix with tests on
dev/10433.Unless someone would rather take a different approach, I'll open a PR in a few days.
zoepfchen commentedon Oct 6, 2026
Another data point, and a PR: #11614.
We hit the same gap today on CNPG 1.30.0 through a different entry point — not operator-driven rotation, but switching an existing cluster to a user-provided
spec.certificates.serverCASecret(a long-lived CA withca.key, so the operator keeps signing the leaves). The<cluster>-serverleaf was only a few days old, soRenewLeafCertificate()left it alone; the operator immediately switched its trust to the new CA and lost all instances:Cluster phase
Instance Status Extraction Error: HTTP communication issue,Ready=False, while PostgreSQL itself kept serving (the "latent" variant from the comment above, except that the operator already noticed). Deleting<cluster>-servermade the operator recreate it from the new CA within seconds; the instance managers reloaded it, no client connection was dropped, and the cluster was healthy again — i.e. the same recovery the operator could have done on its own.#11614 adds the missing third condition to
RenewLeafCertificate(): besides "expiring" and "DNS names changed", the leaf is also regenerated when it no longer verifies against the CA passed in (KeyPair.IsValidwithExtKeyUsageAny, the same verification the operator uses towards the instances). That covers the operator-managed rotation (both leaves go through this function), the stale-replicationjoin loop and the user-provided-CA switch. Unit tests for server and client leaves included.