Fetch Secrets from a Mock Secrets Manager in Python

Build a minimal in-memory secrets manager that stores and retrieves secret values, raising a KeyError for missing names.

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

Python code

30 lines
Python 3.9+
import json

class SecretsManager:
    """Mock secrets manager that returns secrets from a local store."""
    
    def __init__(self, store=None):
        self.store = store or {
            "api_key": "mock-api-key-123",
            "db_password": "s3cret-p@ss",
            "jwt_secret": "dev-only-secret"
        }
    
    def get_secret(self, name):
        if name not in self.store:
            raise KeyError(f"Secret '{name}' not found")
        return self.store[name]


if __name__ == "__main__":
    manager = SecretsManager()
    print("Fetching secrets:")
    for secret_name in ["api_key", "db_password", "jwt_secret"]:
        value = manager.get_secret(secret_name)
        print(f"  {secret_name}: {value}")
    
    print("\nAttempting to fetch missing secret:")
    try:
        manager.get_secret("nonexistent")
    except KeyError as e:
        print(f"  Error: {e}")

Output

stdout
Fetching secrets:
  api_key: mock-api-key-123
  db_password: s3cret-p@ss
  jwt_secret: dev-only-secret

Attempting to fetch missing secret:
  Error: Secret 'nonexistent' not found

How it works

The SecretsManager class mimics a real secrets store by holding a small dictionary of name-to-value pairs. Calling get_secret performs a simple membership check and either returns the stored value or raises a KeyError to signal a missing secret. This pattern is a thin stand-in for cloud secret services and lets you develop locally without credentials.

The provided __main__ block exercises the happy path and the error case, showing exactly what happens when a secret isn't registered. Keeping the mock independent of any third-party library means you can drop it into unit tests or early-stage prototypes with zero setup.

Because the store is just a Python dict, you can easily seed it from a file, environment variables, or a real SDK-backed provider later without changing the interface.

Common mistakes

  • Forgetting to handle KeyError when the secret doesn't exist, causing crashes in production code.
  • Hardcoding secrets in the store for real environments instead of using a secure vault or environment variables.
  • Exposing secret values in logs or error messages, which leaks sensitive data into observability tools.

Variations

  1. Use `os.environ.get(name)` to retrieve secrets from environment variables with a fallback default.
  2. Implement a behind-the-scenes `fetch_from_vault` method that calls the AWS Secrets Manager or Google Secret Manager SDK when in production.

Real-world use cases

  • Seeding local development environments with fake credentials so developers can run services without real secrets.
  • Writing unit tests that verify your application handles missing secrets gracefully without hitting a cloud API.
  • Providing a fallback secrets source in CI pipelines where vault access is unavailable.

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.