Skip to content
Cloud Native

cert-manager and Let’s Encrypt: TLS automation and the renewal that silently failed

cert-manager — A large stack of containers sitting on top of each other

It was 02:15 AM on a Tuesday when our risk-engine webhooks started rejecting incoming order-flow payloads. The symptoms were erratic: some execution brokers reported TLS handshake failures (SSL_ERROR_SYSCALL), while others logged explicit certificate expiration errors (ERR_CERT_DATE_INVALID).

We relied on cert-manager for end-to-end TLS automation with Let’s Encrypt across our Kubernetes clusters. The dashboard claimed every Certificate resource was Ready=True. Yet, our ingress proxies were serving a leaf certificate that had expired three hours prior.

This post covers how our automated renewal pipeline silently degraded, why cert-manager failed to surface the underlying ACME DNS-01 challenge failure, the exact code fixes we deployed, and how we re-architected our observability to ensure a silent certificate expiry never hits our production trading path again.


The Problem: Ready=True while the Gateway Burns

Our algorithmic execution engine routes orders through an API gateway running Envoy inside an Amazon EKS cluster (v1.28). Edge TLS termination relies on cert-manager (v1.13.2) requesting certificates from Let’s Encrypt via DNS-01 challenges routed through AWS Route53.

When I checked the state of the production ingress certificate, kubectl returned a clean status:

$ kubectl get certificates -n trading-prod
NAME READY SECRET AGE
trading-api-tls-cert True trading-api-tls-secret 90d

However, checking the actual secret stored in Kubernetes showed that the certificate data inside trading-api-tls-secret was stale:

$ kubectl get secret trading-api-tls-secret -n trading-prod -o jsonpath=‘{.data.tls\.crt}’ | base64 -d | openssl x509 -noout -enddate
notAfter=May 14 23:00:00 2024 GMT

The certificate had expired. cert-manager attempts to renew certificates 30 days prior to expiration (the standard renewBefore: 720h window). It had attempted to renew, but the process stalled in an intermediate state while keeping the old, valid certificate inside the target Secret until the new one could be issued.

When the old certificate finally crossed its notAfter threshold, Envoy kept serving the stale byte array cached in memory and on disk. cert-manager marked the high-level Certificate custom resource (CRD) as Ready=True because the existing Secret contained a validly formatted keypair, completely ignoring the fact that the validity window had elapsed without a successful rotation.

The Architecture of the Failure

The diagram below illustrates the decoupled loop between the cert-manager control plane, external ACME validation, and our ingress gateway cache:

flowchart TD
 cm["cert-manager controller"] -->|"1. Initiates Renewal"| cert["Certificate CRD"]
 cert -->|"2. Creates Order"| acme["Let's Encrypt API"]
 acme -->|"3. Demands DNS-01"| r53["AWS Route53 API"]
 r53 -.->|"4. Throttle / Rate Limit Fail"| acme
 cm -->|"5. Leaves Old Secret Intact"| sec["Kubernetes Secret"]
 sec -.->|"6. Expiration Reached"| env["Envoy Proxy"]
 env -->|"7. Rejects Handshakes"| client["Broker Clients"]

The root failure occurred at Step 4. Route53 API calls hit strict rate limits (PrioritizedValidationException) due to a concurrent CI/CD pipeline dynamically creating short-lived feature branch records. The ACME Challenge failed, the Order entered an invalid state, but the Certificate status condition logic did not transition to Ready=False until a hard sync loop forced a re-evaluation—which was blocked by exponential backoff.


Technical Investigation & Root Cause

I dumped the events attached to the CertificateRequest and Challenge resources:

$ kubectl describe challengerequests -n trading-prod
Events:
Type Reason Age From Message
—- —— —- —- ——-
Warning StatusReason 42m (x12 over 29h) cert-manager Error presenting challenge: AccessDenied: User: arn:aws:sts::123456789012:assumed-role/cert-manager-irsa/1715690000 is not authorized to perform: route53:ChangeResourceRecordSets on resource: arn:aws:route53:::hostedzone/Z00112233445566

Two separate issues compound this failure:

  1. Permission Creep & IAM Drift: A Terraform refactoring three weeks prior restricted the IRSA (IAM Roles for Service Accounts) policy attached to cert-manager. The policy had lost access to the explicit Hosted Zone ID for our internal trading domain, falling back to a wild-card policy that failed strict SCP (Service Control Policy) evaluation.
  2. Controller Status Lag: cert-manager does not overwrite an existing, working TLS Secret with a broken/incomplete certificate during a failed renewal attempt (which is correct behavior to prevent downtime). However, if the old certificate expires while the renewal logic is retrying in a throttled backoff loop, cert-manager fails to clear the Ready=True condition flag unless explicit alerting rules track certmanager_certificate_expiration_timestamp_seconds.

The default alert we had set up monitored the Ready status condition of the CRD:

# BROKEN ALERT RULE: Did not fire because Ready stayed ‘True’
alert: CertManagerCertificateReadyFailed
expr: certmanager_status_certificate_expiration_timestamp_seconds – time() < 0

Because certmanager_status_certificate_expiration_timestamp_seconds was reporting the timestamp of the currently stored secret, it dropped below zero while certmanager_certificate_ready_status{condition="True"} remained fixed at 1.


The Fix: Complete Manifests and Automation Scripts

To resolve this permanently, we implemented a four-part fix:
1. Re-provisioned IRSA with explicit Route53 Hosted Zone access permissions.
2. Hardened our ClusterIssuer configuration with explicit retries and DNS propagation checks.
3. Created an automated validation script run via CronJob to force secret re-syncs and audit leaf certificate validity directly from network endpoints.
4. Rewrote our Prometheus alerting rules.

1. Hardened ClusterIssuer Manifest

Here is the exact production manifest for our production ClusterIssuer, using IAM Roles for Service Accounts (IRSA) and explicit recursive nameservers for DNS-01 verification to bypass internal CoreDNS caching delays.

apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-production-dns01
namespace: cert-manager
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: [email protected]
privateKeySecretRef:
name: letsencrypt-production-account-key
solvers:
– selector:
dnsZones:
– “api.tradingfirm.internal”
– “execution.tradingfirm.internal”
dns01:
route53:
region: us-east-1
hostedZoneID: Z00112233445566
auth:
kubernetes:
serviceAccountRef:
name: cert-manager

2. Hardened Certificate Definition

We updated our Certificate resource to enforce aggressive renewal windows (30 days before expiry) and force key rotation on every re-issuance to satisfy our security requirements.

apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: trading-api-tls-cert
namespace: trading-prod
spec:
secretName: trading-api-tls-secret
duration: 2160h # 90 days
renewBefore: 720h # 30 days
subject:
organizations:
– Trading Execution Services
commonName: api.tradingfirm.internal
dnsNames:
– api.tradingfirm.internal
– execution.tradingfirm.internal
isCA: false
privateKey:
algorithm: ECDSA
size: 256
rotationPolicy: Always
issuerRef:
name: letsencrypt-production-dns01
kind: ClusterIssuer
group: cert-manager.io

3. Verification & Deep Audit Python Engine

We wrote a Python utility deployed as an in-cluster CronJob. Instead of trusting Kubernetes CRD status flags, this script reads the actual tls.crt byte array out of target Secrets, parses X.509 extensions using Python’s cryptography library, performs an active TLS socket handshake against the live ingress service endpoint, and reports discrepancies directly to Datadog/PagerDuty.

#!/usr/bin/env python3
import base64
import datetime
import os
import socket
import ssl
import sys
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from kubernetes import client, config

def check_live_endpoint(hostname: str, port: int = 443) -> datetime.datetime:
“””Connects directly to the endpoint to parse the presented TLS certificate.”””
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

with socket.create_connection((hostname, port), timeout=5.0) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
der_cert = ssock.getpeercert(binary_form=True)
cert = x509.load_der_x509_certificate(der_cert, default_backend())
return cert.not_valid_after_utc

def check_k8s_secret(namespace: str, secret_name: str) -> datetime.datetime:
“””Extracts and parses the X.509 certificate stored inside the K8s Secret.”””
if os.getenv(“KUBERNETES_SERVICE_HOST”):
config.load_incluster_config()
else:
config.load_kube_config()

v1 = client.CoreV1Api()
secret = v1.read_namespaced_secret(name=secret_name, namespace=namespace)

if “tls.crt” not in secret.data:
raise ValueError(f”Secret {secret_name} does not contain tls.crt”)

crt_bytes = base64.b64decode(secret.data[“tls.crt”])
cert = x509.load_pem_x509_certificate(crt_bytes, default_backend())
return cert.not_valid_after_utc

def main():
target_namespace = os.getenv(“TARGET_NAMESPACE”, “trading-prod”)
target_secret = os.getenv(“TARGET_SECRET”, “trading-api-tls-secret”)
target_host = os.getenv(“TARGET_HOST”, “api.tradingfirm.internal”)

print(f”[*] Auditing TLS setup for Host: {target_host}”)

try:
secret_expiry = check_k8s_secret(target_namespace, target_secret)
print(f”[+] K8s Secret Expiration (UTC): {secret_expiry}”)
except Exception as e:
print(f”[!] Error reading K8s Secret: {e}”)
sys.exit(1)

try:
live_expiry = check_live_endpoint(target_host)
print(f”[+] Live Endpoint Expiration (UTC): {live_expiry}”)
except Exception as e:
print(f”[!] Error connecting to live endpoint: {e}”)
sys.exit(1)

now = datetime.datetime.now(datetime.timezone.utc)
secret_ttl = (secret_expiry – now).total_seconds()
live_ttl = (live_expiry – now).total_seconds()

print(f”[*] Secret TTL: {secret_ttl / 86400:.2f} days”)
print(f”[*] Live Endpoint TTL: {live_ttl / 86400:.2f} days”)

# Alert condition 1: Expiry within 7 days
if live_ttl < (7 * 86400):
print(“[CRITICAL] Live endpoint TLS certificate expires in under 7 days!”)
sys.exit(2)

# Alert condition 2: Secret and Live Endpoint Drift
if abs((secret_expiry – live_expiry).total_seconds()) > 300:
print(“[WARNING] Drift detected! Secret cert does not match live served cert. Proxy reload required.”)
sys.exit(3)

print(“[SUCCESS] All certificate checks passed.”)
sys.exit(0)

if __name__ == “__main__”:
main()

4. Corrected Prometheus Alerting Rules

We discarded the naive Ready=True alert and replaced it with Prometheus rules that calculate expiration directly based on the epoch timestamps exposed by cert-manager metrics, as well as tracking failed challenge execution counts.

groups:
– name: cert-manager-alerts
rules:
# Alert if the underlying certificate inside the secret expires in under 14 days
– alert: SSLCertificateExpiringSoon
expr: (certmanager_certificate_expiration_timestamp_seconds – time()) < (14 * 86400)
for: 1h
labels:
severity: critical
tier: infrastructure
annotations:
summary: “Certificate {{ $labels.name }} expiring in {{ $value | humanizeDuration }}”
description: “Certificate {{ $labels.name }} in namespace {{ $labels.namespace }} has a valid lifetime under 14 days.”

# Alert if cert-manager has been attempting and failing to issue a cert for > 6 hours
– alert: CertManagerIssuanceStalled
expr: certmanager_status_certificate_renewal_related_tests_failed > 0
for: 6h
labels:
severity: warning
tier: infrastructure
annotations:
summary: “Certificate issuance stalled for {{ $labels.name }}”
description: “ACME challenges or orders for {{ $labels.name }} (namespace {{ $labels.namespace }}) are failing continuously.”


Execution and Verification Results

After deploying the updated ClusterIssuer, correcting the IAM policy, and updating the alerting pipeline, we ran a manual rotation dry-run by annotating the existing Certificate resource to force a re-issuance:

$ kubectl annotate certificate trading-api-tls-cert -n trading-prod cert-manager.io/renew-at=“$(date -u +%Y-%m-%dT%H:%M:%SZ)“ –overwrite
certificate.cert-manager.io/trading-api-tls-cert annotated

We monitored the real-time reconciliation loop using the cert-manager CLI plugin (cmctl):

$ cmctl status certificate trading-api-tls-cert -n trading-prod
Name: trading-api-tls-cert
Namespace: trading-prod
Created: Mon, 12 Feb 2024 10:00:00 -0500
Status:
Conditions:
Ready: True, Reason: Ready, Message: Certificate is up to date and valid
Secret Status:
Secret Name: trading-api-tls-secret
Issuer: letsencrypt-production-dns01
Not After: Mon, 12 Aug 2024 04:12:33 UTC
Not Before: Mon, 14 May 2024 04:12:33 UTC
Serial Number: 03f4a1b2c3d4e5f6
Events:
Type Reason Age From Message
—- —— —- —- ——-
Normal Issuing 42s cert-manager Renewing certificate since renewal time has passed
Normal Reused 40s cert-manager Reusing private key API object
Normal Created 35s cert-manager Created Order resource trading-api-tls-cert-12948102
Normal CertificateIssued 5s cert-manager Certificate issued successfully

Running our audit Python script inside the cluster confirmed that both the Kubernetes Secret and live proxy endpoints aligned to the new 90-day window:

$ python3 tls_audit.py
[*] Auditing TLS setup for Host: api.tradingfirm.internal
[+] K8s Secret Expiration (UTC): 2024-08-12 04:12:33+00:00
[+] Live Endpoint Expiration (UTC): 2024-08-12 04:12:33+00:00
[*] Secret TTL: 89.98 days
[*] Live Endpoint TTL: 89.98 days
[SUCCESS] All certificate checks passed.

Lessons Learned

  1. Never use Certificate CRD Ready status as a sole source of truth. The Ready=True condition indicates that the current state of the certificate in the target Secret meets basic parsing sanity. It does not guarantee that an in-flight ACME renewal pipeline is healthy or that the certificate stored in the Secret is unexpired.
  2. De-couple ingress memory from secret creation. Envoy and NGINX Ingress controllers cache TLS contexts. If a certificate changes in a Secret, verify that your ingress controller reloads the file from disk or receives the event over the Secret Discovery Service (SDS) API without requiring a manual pod rollout.
  3. Audit the network layer, not just Kubernetes state. Infrastructure state reported by declarative controllers can drift from operational reality. Out-of-band checks—such as direct TLS handshake verification script runs via CronJob—are essential safety checks for high-availability production environments.
  4. Isolate DNS-01 API quotas. Sharing AWS Route53 access between dynamic developer environments and automated cluster issuers creates hidden rate-limit vectors. Isolate your production ACME authorization IAM roles to scoped Hosted Zones with dedicated rate-limit monitoring.

Join the conversation

Your email address will not be published. Required fields are marked *