How to Mock a TLS Certificate Rotation Schedule in Python

Simulate a TLS certificate rotation schedule with a Python class that tracks last and next rotation dates and decides when to rotate.

Easy Python 3.9+ Aug 9, 2026 Auth & security at scale 16 views 0 copies

Python code

35 lines
Python 3.9+
import datetime
import random
import time


class CertRotator:
    def __init__(self, cert_name, rotation_days=30):
        self.cert_name = cert_name
        self.rotation_days = rotation_days
        self.last_rotated = datetime.date.today() - datetime.timedelta(days=random.randint(10, 25))
        self.next_rotation = self.last_rotated + datetime.timedelta(days=self.rotation_days)

    def should_rotate(self):
        return datetime.date.today() >= self.next_rotation

    def rotate(self):
        if self.should_rotate():
            self.last_rotated = datetime.date.today()
            self.next_rotation = self.last_rotated + datetime.timedelta(days=self.rotation_days)
            return True
        return False

    def status(self):
        return f"Certificate '{self.cert_name}': last rotated {self.last_rotated}, next rotation {self.next_rotation}"


if __name__ == "__main__":
    rotator = CertRotator("api.example.com", rotation_days=30)
    print(rotator.status())
    print(f"Should rotate today? {rotator.should_rotate()}")
    if rotator.rotate():
        print("Rotated successfully.")
        print(rotator.status())
    else:
        print("Not due for rotation yet.")

Output

stdout
Certificate 'api.example.com': last rotated 2025-03-05, next rotation 2025-04-04
Should rotate today? False
Not due for rotation yet.

How it works

The CertRotator class stores the last rotation date and calculates the next rotation by adding the rotation interval. The should_rotate method compares today's date with the scheduled next rotation, returning True when today is on or after that date. When triggered, rotate updates the last rotation to today and reschedules the next one, #mimicking# real certificate rotation logic. Randomizing the initial last rotation simulates certificates at different stages of their lifecycle for testing. This pattern is useful for building schedulers or automated test fixtures without touching actual infrastructure.

Common mistakes

  • Forgetting that date comparisons are inclusive (using `>` instead of `>=`) can skip the rotation on the exact due day.
  • Storing dates as strings instead of `datetime.date` objects causes comparison errors.
  • Not considering timezone differences when using UTC in production; this mock uses local date, so adjust accordingly.

Variations

  1. Use `datetime.datetime` with timezone awareness for precise scheduling across servers.
  2. Add a callback or event hook to notify a logging service when rotation occurs.

Real-world use cases

  • Powering a cron job or scheduler that periodically checks multiple certificates and triggers rotation for due ones.
  • Creating fixtures for load testing certificate renewal systems without waiting days between rotations.
  • Validating alerting logic by simulating a certificate that falls behind its rotation schedule.

Sponsored

Run this sample

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

Open editor

More from Auth & security at scale

Related tutorials and quizzes for this topic.