330 lines
12 KiB
Python
330 lines
12 KiB
Python
"""Deterministic Keycloak OIDC Identity Mock Adapter.
|
|
|
|
Standardized per UP-AI v1.5 / tech-profile.yaml.
|
|
Provides offline, deterministic authentication, PKCE verification, and JWT generation
|
|
for test runners and local development without external network dependencies.
|
|
"""
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import secrets
|
|
import time
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
|
# Deterministic test signing secret and HMAC key
|
|
MOCK_JWT_SECRET = "atb-deterministic-test-jwt-secret-key-32b!"
|
|
MOCK_ISSUER = "http://localhost:8080/realms/atb-realm"
|
|
MOCK_AUDIENCE = "atb-web-portal"
|
|
|
|
# Pre-seeded disposable test personas (matching Iteration 01 Manual Testing Guide)
|
|
TEST_PERSONAS: Dict[str, Dict[str, Any]] = {
|
|
"admin@alpha.com": {
|
|
"sub": "usr_01J8K92ADM001",
|
|
"email": "admin@alpha.com",
|
|
"name": "Alpha Tenant Admin",
|
|
"roles": ["Tenant Administrator"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"buyer@alpha.com": {
|
|
"sub": "usr_01J8K92BUY001",
|
|
"email": "buyer@alpha.com",
|
|
"name": "Ramesh Kumar (Buyer)",
|
|
"roles": ["Mandi Buyer"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"pmgr@alpha.com": {
|
|
"sub": "usr_01J8K92MGR001",
|
|
"email": "pmgr@alpha.com",
|
|
"name": "Suresh Patel (Purchase Mgr)",
|
|
"roles": ["Purchase Manager"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"yard@alpha.com": {
|
|
"sub": "usr_01J8K92YRD001",
|
|
"email": "yard@alpha.com",
|
|
"name": "Vikram Singh (Yard Sup)",
|
|
"roles": ["Yard Supervisor"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"qc@alpha.com": {
|
|
"sub": "usr_01J8K92QCO001",
|
|
"email": "qc@alpha.com",
|
|
"name": "Ananya Sharma (QC)",
|
|
"roles": ["Quality Officer"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"sales@alpha.com": {
|
|
"sub": "usr_01J8K92SAL001",
|
|
"email": "sales@alpha.com",
|
|
"name": "Rohit Verma (Sales Exec)",
|
|
"roles": ["Sales Executive"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"smgr@alpha.com": {
|
|
"sub": "usr_01J8K92SMG001",
|
|
"email": "smgr@alpha.com",
|
|
"name": "Meera Nair (Sales Mgr)",
|
|
"roles": ["Sales Manager"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"logistics@alpha.com": {
|
|
"sub": "usr_01J8K92LOG001",
|
|
"email": "logistics@alpha.com",
|
|
"name": "Dinesh Rao (Logistics)",
|
|
"roles": ["Logistics Coordinator"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"finance@alpha.com": {
|
|
"sub": "usr_01J8K92ACC001",
|
|
"email": "finance@alpha.com",
|
|
"name": "Kavita Joshi (Accounts)",
|
|
"roles": ["Accounts Executive"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"director@alpha.com": {
|
|
"sub": "usr_01J8K92DIR001",
|
|
"email": "director@alpha.com",
|
|
"name": "Harish Patel (Partner/MD)",
|
|
"roles": ["Partner / MD"],
|
|
"tenant_id": "tenant-alpha"
|
|
},
|
|
"sysadmin@atb.io": {
|
|
"sub": "usr_01J8K92SYS001",
|
|
"email": "sysadmin@atb.io",
|
|
"name": "System Administrator",
|
|
"roles": ["System Administrator"],
|
|
"tenant_id": "platform"
|
|
},
|
|
"admin@beta.com": {
|
|
"sub": "usr_01J8K92BET001",
|
|
"email": "admin@beta.com",
|
|
"name": "Beta Tenant Admin",
|
|
"roles": ["Tenant Administrator"],
|
|
"tenant_id": "tenant-beta"
|
|
},
|
|
"multi@trader.com": {
|
|
"sub": "usr_01J8K92MLT001",
|
|
"email": "multi@trader.com",
|
|
"name": "Arjun Sharma (Multi-Trader)",
|
|
"roles": ["Mandi Buyer"],
|
|
"tenant_id": "tenant-alpha"
|
|
}
|
|
}
|
|
|
|
# Pre-seeded disposable tenant fixtures
|
|
TEST_TENANTS: Dict[str, Dict[str, Any]] = {
|
|
"tenant-alpha": {
|
|
"tenant_id": "tenant-alpha",
|
|
"business_name": "Alpha Agro Traders",
|
|
"legal_identifier": "27AAACA1234A1Z5",
|
|
"contact_email": "admin@alpha.com",
|
|
"primary_mandi": "APMC-PUN-01",
|
|
"status": "ACTIVE",
|
|
"created_at": "2026-01-01T00:00:00Z"
|
|
},
|
|
"tenant-beta": {
|
|
"tenant_id": "tenant-beta",
|
|
"business_name": "Beta Grain Merchants",
|
|
"legal_identifier": "27BBBCB5678B1Z6",
|
|
"contact_email": "admin@beta.com",
|
|
"primary_mandi": "APMC-NSK-01",
|
|
"status": "ACTIVE",
|
|
"created_at": "2026-01-01T00:00:00Z"
|
|
},
|
|
"tenant-gamma": {
|
|
"tenant_id": "tenant-gamma",
|
|
"business_name": "Gamma Agro Corp",
|
|
"legal_identifier": "27CCCD7890C1Z7",
|
|
"contact_email": "admin@gamma.com",
|
|
"primary_mandi": "APMC-NAG-01",
|
|
"status": "SUSPENDED",
|
|
"created_at": "2026-01-01T00:00:00Z"
|
|
},
|
|
"tenant-closed": {
|
|
"tenant_id": "tenant-closed",
|
|
"business_name": "Closed Agro Trading",
|
|
"legal_identifier": "27DDDD1111D1Z8",
|
|
"contact_email": "admin@closed.com",
|
|
"primary_mandi": "APMC-SOL-01",
|
|
"status": "CLOSED",
|
|
"created_at": "2026-01-01T00:00:00Z"
|
|
}
|
|
}
|
|
|
|
# Pre-seeded disposable membership fixtures
|
|
TEST_MEMBERSHIPS: List[Dict[str, Any]] = [
|
|
{"membership_id": "mem_001", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92ADM001", "email": "admin@alpha.com", "role": "Tenant Administrator", "status": "ACTIVE"},
|
|
{"membership_id": "mem_002", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92BUY001", "email": "buyer@alpha.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
|
{"membership_id": "mem_003", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92QCO001", "email": "qc@alpha.com", "role": "Quality Officer", "status": "ACTIVE"},
|
|
{"membership_id": "mem_004", "tenant_id": "tenant-beta", "user_id": "usr_01J8K92BET001", "email": "admin@beta.com", "role": "Tenant Administrator", "status": "ACTIVE"},
|
|
{"membership_id": "mem_005", "tenant_id": "tenant-alpha", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
|
{"membership_id": "mem_006", "tenant_id": "tenant-beta", "user_id": "usr_01J8K92MLT001", "email": "multi@trader.com", "role": "Partner / MD", "status": "ACTIVE"},
|
|
{"membership_id": "mem_007", "tenant_id": "tenant-gamma", "user_id": "usr_01J8K92GAM001", "email": "user@gamma.com", "role": "Mandi Buyer", "status": "ACTIVE"},
|
|
]
|
|
|
|
|
|
|
|
def base64url_encode(data: bytes) -> str:
|
|
"""Encodes bytes to URL-safe base64 without padding."""
|
|
return base64.urlsafe_b64encode(data).rstrip(b'=').decode('utf-8')
|
|
|
|
|
|
def base64url_decode(data: str) -> bytes:
|
|
"""Decodes URL-safe base64 string with padding restoration."""
|
|
padding = '=' * (4 - len(data) % 4) if len(data) % 4 != 0 else ''
|
|
return base64.urlsafe_b64decode((data + padding).encode('utf-8'))
|
|
|
|
|
|
def generate_pkce_challenge(verifier: str) -> str:
|
|
"""Calculates SHA-256 base64url code_challenge from code_verifier."""
|
|
digest = hashlib.sha256(verifier.encode('utf-8')).digest()
|
|
return base64url_encode(digest)
|
|
|
|
|
|
def verify_pkce(verifier: str, challenge: str) -> bool:
|
|
"""Verifies that the verifier matches the code_challenge."""
|
|
calculated = generate_pkce_challenge(verifier)
|
|
return hmac.compare_digest(calculated, challenge)
|
|
|
|
|
|
class DeterministicIdentityMock:
|
|
"""In-memory deterministic mock of Keycloak OIDC Provider."""
|
|
|
|
def __init__(self, secret: str = MOCK_JWT_SECRET, issuer: str = MOCK_ISSUER, audience: str = MOCK_AUDIENCE):
|
|
self.secret = secret
|
|
self.issuer = issuer
|
|
self.audience = audience
|
|
self.auth_codes: Dict[str, Dict[str, Any]] = {}
|
|
self.revoked_tokens: set = set()
|
|
|
|
def create_authorization_code(self, email: str, code_challenge: str, redirect_uri: str, state: str) -> str:
|
|
"""Issues a one-time authorization code bound to challenge and persona."""
|
|
if email not in TEST_PERSONAS:
|
|
raise ValueError(f"Unknown test persona email: {email}")
|
|
|
|
code = f"auth_code_{secrets.token_hex(16)}"
|
|
self.auth_codes[code] = {
|
|
"email": email,
|
|
"code_challenge": code_challenge,
|
|
"redirect_uri": redirect_uri,
|
|
"state": state,
|
|
"expires_at": time.time() + 300,
|
|
"used": False
|
|
}
|
|
return code
|
|
|
|
def exchange_code_for_tokens(self, code: str, code_verifier: str, redirect_uri: str) -> Dict[str, Any]:
|
|
"""Exchanges authorization code and PKCE verifier for signed tokens."""
|
|
if code not in self.auth_codes:
|
|
raise ValueError("Invalid or expired authorization code.")
|
|
|
|
record = self.auth_codes[code]
|
|
if record["used"]:
|
|
raise ValueError("Authorization code has already been exchanged (replay detected).")
|
|
|
|
if time.time() > record["expires_at"]:
|
|
raise ValueError("Authorization code has expired.")
|
|
|
|
if not verify_pkce(code_verifier, record["code_challenge"]):
|
|
raise ValueError("PKCE code verification failed (challenge/verifier mismatch).")
|
|
|
|
# Mark code as consumed (one-time use invariant)
|
|
record["used"] = True
|
|
|
|
persona = TEST_PERSONAS[record["email"]]
|
|
access_token = self.mint_jwt(
|
|
subject=persona["sub"],
|
|
email=persona["email"],
|
|
name=persona["name"],
|
|
roles=persona["roles"],
|
|
tenant_id=persona["tenant_id"],
|
|
expires_in_seconds=3600
|
|
)
|
|
return {
|
|
"access_token": access_token,
|
|
"token_type": "Bearer",
|
|
"expires_in": 3600,
|
|
"scope": "openid profile email roles"
|
|
}
|
|
|
|
def mint_jwt(self, subject: str, email: str, name: str, roles: List[str], tenant_id: str,
|
|
expires_in_seconds: int = 3600, not_before_seconds: int = 0,
|
|
custom_claims: Optional[Dict[str, Any]] = None) -> str:
|
|
"""Mints a deterministic HS256-signed JWT token."""
|
|
now = int(time.time())
|
|
header = {
|
|
"alg": "HS256",
|
|
"typ": "JWT",
|
|
"kid": "mock-key-01"
|
|
}
|
|
payload = {
|
|
"iss": self.issuer,
|
|
"sub": subject,
|
|
"aud": self.audience,
|
|
"exp": now + expires_in_seconds,
|
|
"nbf": now + not_before_seconds,
|
|
"iat": now,
|
|
"jti": secrets.token_hex(16),
|
|
"email": email,
|
|
"name": name,
|
|
"realm_access": {
|
|
"roles": roles
|
|
},
|
|
"tenant_id": tenant_id
|
|
}
|
|
if custom_claims:
|
|
payload.update(custom_claims)
|
|
|
|
header_b64 = base64url_encode(json.dumps(header, separators=(',', ':')).encode('utf-8'))
|
|
payload_b64 = base64url_encode(json.dumps(payload, separators=(',', ':')).encode('utf-8'))
|
|
|
|
signing_input = f"{header_b64}.{payload_b64}".encode('utf-8')
|
|
signature = hmac.new(self.secret.encode('utf-8'), signing_input, hashlib.sha256).digest()
|
|
signature_b64 = base64url_encode(signature)
|
|
|
|
return f"{header_b64}.{payload_b64}.{signature_b64}"
|
|
|
|
def decode_and_verify_jwt(self, token: str) -> Dict[str, Any]:
|
|
"""Validates token signature, expiration, issuer, and revocation status."""
|
|
if token in self.revoked_tokens:
|
|
raise ValueError("Token has been revoked.")
|
|
|
|
parts = token.split('.')
|
|
if len(parts) != 3:
|
|
raise ValueError("Malformed JWT token structure.")
|
|
|
|
header_b64, payload_b64, signature_b64 = parts
|
|
signing_input = f"{header_b64}.{payload_b64}".encode('utf-8')
|
|
expected_sig = hmac.new(self.secret.encode('utf-8'), signing_input, hashlib.sha256).digest()
|
|
|
|
provided_sig = base64url_decode(signature_b64)
|
|
if not hmac.compare_digest(expected_sig, provided_sig):
|
|
raise ValueError("Invalid JWT signature.")
|
|
|
|
payload = json.loads(base64url_decode(payload_b64).decode('utf-8'))
|
|
now = time.time()
|
|
|
|
if payload.get("exp") and now > payload["exp"]:
|
|
raise ValueError("JWT token has expired.")
|
|
|
|
if payload.get("nbf") and now < payload["nbf"]:
|
|
raise ValueError("JWT token is not active yet (nbf claim).")
|
|
|
|
if payload.get("iss") != self.issuer:
|
|
raise ValueError(f"Invalid issuer: expected {self.issuer}, got {payload.get('iss')}")
|
|
|
|
if payload.get("aud") != self.audience:
|
|
raise ValueError(f"Invalid audience: expected {self.audience}, got {payload.get('aud')}")
|
|
|
|
return payload
|
|
|
|
def revoke_token(self, token: str) -> None:
|
|
"""Records token revocation."""
|
|
self.revoked_tokens.add(token)
|
|
|
|
|
|
# Global singleton instance for testing and runtime mocking
|
|
mock_idp = DeterministicIdentityMock()
|