Mock GCP Secret Manager access version in Python

A minimal mock of GCP Secret Manager that stores secret versions, retrieves payloads by version, and logs access timestamps.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 15 views 0 copies

Python code

42 lines
Python 3.9+
import json
import time
from datetime import datetime, timezone


class MockSecretManager:
    """Minimal mock of GCP Secret Manager access/version behavior."""

    def __init__(self):
        self._secrets = {}
        self._access_log = []

    def create_secret(self, secret_id: str, payload: str) -> dict:
        version = {
            "version": 1,
            "payload": payload,
            "created": datetime.now(timezone.utc).isoformat(),
        }
        self._secrets[secret_id] = version
        return version

    def access_secret_version(self, secret_id: str, version: int = 1) -> str:
        if secret_id not in self._secrets:
            raise KeyError(f"Secret '{secret_id}' not found")
        secret = self._secrets[secret_id]
        if version != secret["version"]:
            raise ValueError(f"Version {version} not available; latest is {secret['version']}")
        entry = {
            "secret_id": secret_id,
            "version": version,
            "accessed_at": datetime.now(timezone.utc).isoformat(),
        }
        self._access_log.append(entry)
        return secret["payload"]


if __name__ == "__main__":
    manager = MockSecretManager()
    manager.create_secret("api-key", "sk-12345-secret")
    value = manager.access_secret_version("api-key")
    print(f"Accessed payload: {value}")
    print(f"Access log: {json.dumps(manager._access_log, indent=2)}")

Output

stdout
Accessed payload: sk-12345-secret
Access log: [
  {
    "secret_id": "api-key",
    "version": 1,
    "accessed_at": "2025-04-02T10:15:30.123456+00:00"
  }
]

How it works

This mock stores each secret as a single version object with a payload and creation timestamp. access_secret_version checks that the requested version exists and matches the stored version, raising KeyError or ValueError for invalid input. Access events are appended to a log list for auditing or testing. The code uses datetime.now(timezone.utc) to produce timezone-aware timestamps, avoiding naive datetime pitfalls. This pattern is useful when developing or testing code that will later call the real GCP Secret Manager API.

Common mistakes

  • Forgetting to check if the secret exists before accessing its version
  • Comparing versions with `!=` instead of checking version availability
  • Using naive datetime instead of timezone-aware UTC timestamps

Variations

  1. Use a dictionary with multiple versions per secret to simulate version history
  2. Add a `delete_secret` method to model secret lifecycle
  3. Implement `list_secret_versions` to return all versions of a secret

Real-world use cases

  • Unit testing application code that reads API keys from Secret Manager without hitting GCP.
  • Simulating secret rotation behavior in local development or CI environments.
  • Auditing access to secrets by capturing timestamps and secret IDs in a log.

Sponsored

Run this sample

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

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.