How to mock a SPIFFE workload identity in Python

Generate a mock SPIFFE ID and token for a workload using a trust domain, namespace, and service account.

Easy Python 3.9+ Aug 9, 2026 Microservices patterns 13 views 0 copies

Python code

33 lines
Python 3.9+
import hashlib
import json
from dataclasses import dataclass, asdict


@dataclass
class SPIFFEIdentity:
    trust_domain: str
    namespace: str
    service_account: str

    @property
    def id(self) -> str:
        return f"spiffe://{self.trust_domain}/ns/{self.namespace}/sa/{self.service_account}"


def mock_workload_identity(trust_domain: str, namespace: str, service_account: str) -> str:
    identity = SPIFFEIdentity(trust_domain, namespace, service_account)

    # Generate a mock token by hashing the SPIFFE ID
    token = hashlib.sha256(identity.id.encode()).hexdigest()

    return json.dumps({
        "spiffe_id": identity.id,
        "token": token,
        "type": "spiffe",
        "expires_in": 3600,
    }, indent=2)


if __name__ == "__main__":
    result = mock_workload_identity("example.org", "production", "payment-service")
    print(result)

Output

stdout
{
  "spiffe_id": "spiffe://example.org/ns/production/sa/payment-service",
  "token": "6f2df6e0a9ed9f6b6f4d3c6a0b2d7f8f6d1f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5",
  "type": "spiffe",
  "expires_in": 3600
}

How it works

The SPIFFEIdentity dataclass groups the trust domain, namespace, and service account into one cohesive structure. Its id property constructs the standard SPIFFE ID URI format, which is essential for authenticating workloads in microservices. The function then hashes that ID with SHA-256 to create a deterministic mock token, simulating what a real SVID token would look like. Finally, json.dumps with indentation returns a formatted JSON payload that mimics a workload API response.

Common mistakes

  • Forgetting to include the `spiffe://` prefix in the constructed ID
  • Using a random token instead of a deterministic hash, making tests flaky
  • Hardcoding the trust domain instead of passing it as a parameter

Variations

  1. Use `secrets.token_hex(32)` for a cryptographically secure random token instead of a hash
  2. Include a custom `audience` field in the JSON payload for specific service expectations

Real-world use cases

  • Testing microservices that validate SPIFFE-issued JWT tokens without a real SPIFFE infrastructure.
  • Simulating workload identity in local development to avoid provisioning a service mesh.
  • Generating mock credentials for integration tests in CI pipelines where SPIFFE is not available.

Sponsored

Run this sample

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

Open editor

More from Microservices patterns

Related tutorials and quizzes for this topic.