How to Mock an Ingress TLS Certificate Manager in Python

Build a mock TLS certificate manager for ingress that issues, checks, and renews certificates with expiry tracking — useful for testing deployment workflows before touching real infrastructure.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 15 views 0 copies

Python code

49 lines
Python 3.9+
import ssl
import socket
from datetime import datetime, timedelta


class TLSCertManager:
    def __init__(self, hostname):
        self.hostname = hostname
        self.certificates = {}

    def request_certificate(self, domain, days_valid=90):
        """Mock a certificate issuance request that stores a cert with expiry."""
        expiry = datetime.now() + timedelta(days=days_valid)
        self.certificates[domain] = {
            "hostname": self.hostname,
            "issued_at": datetime.now().isoformat(),
            "expires_at": expiry.isoformat(),
            "status": "active"
        }
        return self.certificates[domain]

    def check_expiry(self, domain):
        """Check if cert expires within 30 days."""
        if domain not in self.certificates:
            return {"domain": domain, "warning": "No certificate found"}
        cert = self.certificates[domain]
        expiry = datetime.fromisoformat(cert["expires_at"])
        days_left = (expiry - datetime.now()).days
        return {
            "domain": domain,
            "days_until_expiry": days_left,
            "needs_renewal": days_left <= 30
        }

    def renew_certificate(self, domain, days_valid=90):
        """Simulate renewal by re-issuing with new expiry."""
        if domain in self.certificates:
            self.certificates[domain]["status"] = "renewed"
        return self.request_certificate(domain, days_valid)


if __name__ == "__main__":
    manager = TLSCertManager(hostname="ingress.example.com")
    cert = manager.request_certificate("api.example.com", days_valid=60)
    print("Issued cert:", cert)
    print("Expiry check:", manager.check_expiry("api.example.com"))
    renewed = manager.renew_certificate("api.example.com", days_valid=120)
    print("Renewed cert:", renewed)
    print("Final check:", manager.check_expiry("api.example.com"))

Output

stdout
Issued cert: {'hostname': 'ingress.example.com', 'issued_at': '2025-01-14T12:00:00.123456', 'expires_at': '2025-03-15T12:00:00.123456', 'status': 'active'}
Expiry check: {'domain': 'api.example.com', 'days_until_expiry': 60, 'needs_renewal': False}
Renewed cert: {'hostname': 'ingress.example.com', 'issued_at': '2025-01-14T12:00:00.123456', 'expires_at': '2025-05-14T12:00:00.123456', 'status': 'active'}
Final check: {'domain': 'api.example.com', 'days_until_expiry': 120, 'needs_renewal': False}

How it works

The TLSCertManager class stores certificates in a dict keyed by domain, with expiry dates computed using datetime.now() plus the requested validity period. request_certificate mocks real ACME-style issuance by storing an ISO-formatted expiry and status. check_expiry parses that timestamp and flags renewal needs 30 days before expiration. renew_certificate marks the old entry as renewed and re-issues with a fresh expiry. This pattern lets you simulate certificate lifecycle behavior in staging or test harnesses without hitting a real CA or DNS provider.

Common mistakes

  • Using the same `issued_at` timestamp for renewal — should generate a fresh timestamp
  • Forgetting to mark the old certificate status as `renewed` before re-issuing
  • Hardcoding expiry checks instead of using a configurable threshold (30 days here)
  • Not storing hostname per certificate, making multi-ingress setups impossible to model

Variations

  1. Store the ephemeral dict in a SQLite or Redis table for persistent state across restarts
  2. Add an `auto_renew` method that scans all certs and renews any within the threshold

Real-world use cases

  • Unit-testing ingress controllers that validate certificate readiness before routing traffic.
  • Simulating TLS certificate expiry in integration tests for renewal alerting pipelines.
  • Building demo environments that showcase cert-manager behavior without issuing real certificates.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.