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.
Python code
33 linesimport 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
{
"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
- Use `secrets.token_hex(32)` for a cryptographically secure random token instead of a hash
- 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
More from Microservices patterns
- BFF aggregation pattern: combine multiple service responses in Python easy
- Backward Compatible Schema Evolution in Python medium
- Bulkhead Thread Pool per Service Mock in Python medium
- CQRS with Separate Read and Write Repositories in Python medium
- Cache-Aside Pattern in Python: Per-Service Mock easy
- Consumer Driven Contract Pact Mock in Python medium
Keep learning
Related tutorials and quizzes for this topic.