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.
Python code
35 linesimport 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
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
- Use `datetime.datetime` with timezone awareness for precise scheduling across servers.
- 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
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.