How to Create a Mock Docker Registry Auth Token Server in Python

Build a mock Docker Registry token authentication server that issues signed JWT-like tokens for push and pull access using Python's standard library.

Medium Python 3.9+ Aug 9, 2026 Automation & scripting 16 views 0 copies

Python code

60 lines
Python 3.9+
import base64
import hashlib
import hmac
import json
import time
from http.server import BaseHTTPRequestHandler, HTTPServer


class TokenAuthHandler(BaseHTTPRequestHandler):
    """Mock Docker Registry token authentication server."""

    SECRET_KEY = b"mock-secret-key"

    def generate_token(self, username: str, password: str) -> str:
        """Generate a mock Bearer token with HMAC signature."""
        payload = {
            "iss": "mock-registry-auth",
            "sub": username,
            "exp": int(time.time()) + 3600,  # 1 hour expiry
            "access": [{"type": "repository", "name": "myapp", "actions": ["push", "pull"]}]
        }
        header = {"alg": "HS256", "typ": "JWT"}

        header_b64 = base64.urlsafe_b64encode(json.dumps(header).encode()).rstrip(b"=")
        payload_b64 = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b"=")
        signing_input = header_b64 + b"." + payload_b64
        signature = hmac.new(self.SECRET_KEY, signing_input, hashlib.sha256).digest()
        signature_b64 = base64.urlsafe_b64encode(signature).rstrip(b"=")
        return f"{signing_input.decode()}.{signature_b64.decode()}"

    def do_GET(self):
        """Handle GET /token with Basic Auth credentials."""
        auth_header = self.headers.get("Authorization", "")
        if not auth_header.startswith("Basic "):
            self.send_response(401)
            self.send_header("WWW-Authenticate", 'Basic realm="Registry"')
            self.end_headers()
            return

        creds = base64.b64decode(auth_header.split(" ", 1)[1]).decode()
        username, password = creds.split(":", 1)
        token = self.generate_token(username, password)

        response = json.dumps({"token": token, "expires_in": 3600, "issued_at": time.time()})
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(response.encode())


def main():
    server = HTTPServer(("localhost", 5000), TokenAuthHandler)
    print("Mock registry auth server running on http://localhost:5000")
    print("GET /token with Basic Auth (e.g., admin:password)")
    print("Example response contains a mock JWT token for push/pull access.")
    server.serve_forever()


if __name__ == "__main__":
    main()

Output

stdout
Mock registry auth server running on http://localhost:5000
GET /token with Basic Auth (e.g., admin:password)
Example response contains a mock JWT token for push/pull access.

How it works

This code implements a mock Docker Registry token server using only the Python standard library. The BaseHTTPRequestHandler class handles GET requests and parses the Basic Authorization header to extract credentials. Tokens are generated as JWT-like structures with an HMAC-SHA256 signature, including claims for issuer, subject, expiry, and access permissions. The server runs on localhost port 5000 and returns a JSON response with the token, expiration time, and issue timestamp. This setup allows testing registry clients and CI pipelines without a real authentication infrastructure.

Common mistakes

  • Forgetting to strip padding characters (=) from base64 URL-encoded segments
  • Not checking for the 'Basic ' prefix before attempting to decode credentials
  • Hardcoding credentials instead of validating them against a user store
  • Missing the 'WWW-Authenticate' header in 401 responses, which breaks client authentication flow

Variations

  1. Use Flask or FastAPI instead of the standard library http.server for a more concise implementation
  2. Add proper password hashing with `hashlib.pbkdf2_hmac` instead of plaintext comparison

Real-world use cases

  • Testing Docker Registry clients and push/pull commands in a sandboxed CI environment without external dependencies.
  • Simulating registry authentication for integration tests of image tagging and deployment automation scripts.
  • Developing and validating container registry client libraries that implement token-based authentication flows.

Sponsored

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.