Skip to content

[Bug]: CA certificate rotation creates deadlock — operator cannot restart pods due to x509 verification failure #10433

Description

@Daniel-dev22

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-path storage class, operator-managed certificates (default)
  • No cert-manager — using CNPG's built-in PKI

Timeline (Cluster 1)

  • 2026-04-11T04:01:06Z — CA secret shared-pg-ca rotated (new creationTimestamp)
  • Pods shared-pg-2, shared-pg-4, shared-pg-5 were not restarted by the operator
  • Operator entered infinite requeue loop with x509 errors for all 3 pods
  • -rw service 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:

  1. The new CA cert is written to the {cluster}-ca secret
  2. The operator starts using the new CA to verify TLS connections to pods
  3. But the pods still have TLS certificates signed by the old CA loaded in memory
  4. The operator's status probe (GET https://{pod-ip}:8000/pg/status) fails with x509 verification error
  5. Without pod status, the reconciler cannot determine cluster state or trigger rolling restarts
  6. 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:

  1. Detect that existing pods have TLS certificates signed by the old CA (e.g., by comparing {cluster}-ca secret's update timestamp against pod start times)
  2. Trigger a rolling restart of all cluster pods so they pick up certificates signed by the new CA
  3. 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-pg

The 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.certificateDuration configuration (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 maintenance log 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.

Activity

  1. dosubot commented on Apr 12, 2026

    @dosubot

    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 via renewCASecret(), the CA private key is preserved and only the ca.crt is updated with fresh validity dates and a new serial number [2]. However, RenewLeafCertificate() — which decides whether to regenerate server TLS certificates in the {cluster}-server secret — 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:

    1. renewCASecret() updates ca.crt in the {cluster}-ca secret [4]
    2. The operator creates a fresh TLS context from the current CA secret on every reconciliation loop [5], so it immediately starts verifying pod connections against the new CA [6]
    3. The instance manager's HTTP server on port 8000 uses dynamic GetCertificate callbacks [7], so it could serve a new cert — but RefreshSecrets() fetches the unchanged {cluster}-server secret [8], which still contains the cert signed by the old CA
    4. Pod rollout (which would fix things) only triggers if the PodSpec annotation hash changes [9] — but since the server cert secret wasn't regenerated, the PodSpec doesn't change, so no rollout occurs
    5. The operator cannot get pod status → cannot manage the cluster → infinite requeue

    There'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 renewCASecret preserves 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's x509.Certificate.Verify() [11] is doing a full chain validation that compares the CA certificate's AuthorityKeyIdentifier or 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 differ
    • Alternatively, implement a dual-CA bundle during the rotation window so certificates signed by either the old or new CA are accepted
    • As a safety net, the reconciler should detect persistent x509 failures across all pods and escalate to forced rolling restart rather than requeueing indefinitely

    To reply, just mention @dosu.


    Share context across your team and agents. Try Dosu.

    Leave Feedback Learn about cloudnative-pg with Dosu Add Dosu to your team

  2. unchangedraman commented on Apr 17, 2026

    @unchangedraman

    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.

  3. Daniel-dev22 commented on Apr 20, 2026

    @Daniel-dev22
    Author

    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 → -rw service 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:

    • Cluster stays at readyInstances: N-1/N, phase Creating a new replica
    • -rw service has endpoints (existing pods keep serving fine because their in-memory certs were loaded before the CA/secret drift)
    • Operator spawns {cluster}-{N}-join pods every few minutes; each one fails with remote error: tls: unknown certificate authority connecting to {cluster}-rw as streaming_replica
    • Join pod counter grows indefinitely (we reached shared-pg-50-join before intervening)

    Root cause evidence on my cluster:

    • {cluster}-ca serial E753A12E2C88FDDE1133997CF50C2A21
    • Primary pod's mounted /controller/certificates/client-ca.crt serial: same E753A12E…
    • {cluster}-server leaf: openssl verify -CAfile ca.crt tls.crt → OK
    • {cluster}-replication leaf (streaming_replica cert): openssl verify → error 20: unable to get local issuer certificate

    Both CAs in play have the exact same Subject (OU={ns}, CN={cluster}), which is presumably why the name-based checks inside RenewLeafCertificate() 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}-replication from the current CA within seconds; the next join pod the operator spawns mounts the fresh secret and pg_basebackup succeeds. 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}-server is also signed by a different CA than {cluster}-ca currently holds, but running pods don't care because they have their in-memory cert from before the rotation. kubectl get cluster shows readyInstances: N/N but phase flips to Instance 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:

    1. (Variant B) Stale -replication only → partial-ready cluster, infinite join-retry loop, no outage
    2. (latent) Stale -server → running pods fine, but next restart = outage
    3. (Variant A) Both stale → full outage the moment anything restarts

    All three would be fixed by the AuthorityKeyIdentifier vs SubjectKeyIdentifier check @unchangedraman proposed for RenewLeafCertificate() — 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.

  4. unchangedraman commented on Apr 20, 2026

    @unchangedraman

    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 — the streaming_replica client 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, so tls: unknown certificate authority and 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 via SetServerCertificate) — 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.

  5. flmichel commented on Aug 9, 2026

    @flmichel

    I don't think renewCASecret is the cause here. It re-signs ca.crt with the same private key
    (internal/controller/cluster_pki.go:221-232), so leaves signed by the old cert still verify against
    the new one. I checked both cases:

    • CA renewed in place with the same key, which is what renewCASecret does: the existing leaf still
      verifies 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.

      x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification
      failure" while trying to verify candidate authority certificate "cluster-example")
      

    So a scheduled renewal can't produce that error. The CA key itself has to have changed.

    The creationTimestamp changed, and renewCASecret ends in r.Update,
    which never changes it, so the Secret was deleted and recreated rather than renewed. The only code
    that recreates it is ensureCASecret:194, and certs.go:447 always 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,
    CreateRootCA and CreateAndSignPair build them all in the test.

    The gap is the early return at pkg/certs/k8s.go:114, which never checks that the leaf still chains
    to 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.

  6. added this to the Now milestone on Sep 24, 2026
  7. zoepfchen commented on Oct 6, 2026

    @zoepfchen

    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 with ca.key, so the operator keeps signing the leaves). The <cluster>-server leaf was only a few days old, so RenewLeafCertificate() left it alone; the operator immediately switched its trust to the new CA and lost all instances:

    Cannot extract Pod status ... Get "https://<instance-ip>:8000/pg/status": tls: failed to verify certificate: x509: certificate signed by unknown authority
    

    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>-server made 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.IsValid with ExtKeyUsageAny, the same verification the operator uses towards the instances). That covers the operator-managed rotation (both leaves go through this function), the stale -replication join loop and the user-provided-CA switch. Unit tests for server and client leaves included.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions