This commit is contained in:
Prashant Shendre 2026-10-12 10:50:42 +05:30
parent 72cc2b7098
commit 39e20e11f9
8 changed files with 353 additions and 14 deletions

View File

@ -0,0 +1,55 @@
# Checkpoint 018 — Stage 13 Code Generation & Quality Gate 14.1 Complete
- **Checkpoint ID:** CKPT-018
- **Date:** 2026-10-12
- **Active Stage:** Stage 13 (Code Generation) & Stage 14 (Verification / Gate 14.1) Complete
- **Active Track:** Greenfield, India-first, multi-tenant Agriculture Trading Backoffice (ATB)
- **Active Skills:** `up-code-generate`, `up-traceability-gate`
- **Governed Standard:** UP-AI v1.5 Standard
## Completed
- **Wave 0 Integration Sandbox:**
- Authored deterministic Keycloak IdP mock adapter at `sandbox/identity_mock.py` and `05_implementation_workspace/sandbox/identity_mock.py` implementing RFC 7636 PKCE challenges, HS256 JWT token minting/decoding/validation, replay protection, and 11 pre-configured PRD personas.
- **Wave 1 Backend Services & Data Layer:**
- Implemented application configuration at `05_implementation_workspace/backend/app/core/config.py`.
- Implemented session manager and revocation tracker at `05_implementation_workspace/backend/app/auth/session.py` (`SessionManager`, `FR-AUTH-003`).
- Implemented OIDC authentication service at `05_implementation_workspace/backend/app/auth/oidc.py` (`OIDCAuthService`, `FR-AUTH-001`).
- Implemented RBAC policy engine with all 11 PRD roles and mandatory Segregation of Duties (SoD) rules at `05_implementation_workspace/backend/app/auth/rbac.py` (`RBACPolicyEngine`, `FR-AUTH-002`, `BRD-FR-040`).
- Implemented SQLAlchemy User model at `05_implementation_workspace/backend/app/models/user.py`.
- Implemented AuthController and FastAPI endpoints at `05_implementation_workspace/backend/app/api/auth.py` and `05_implementation_workspace/backend/app/main.py` (`GET /api/v1/auth/session`, `POST /api/v1/auth/logout`, `POST /api/v1/auth/protected-action`).
- Implemented Alembic initial migration for users at `05_implementation_workspace/backend/alembic/versions/001_initial_users.py`.
- **Wave 2 Frontend React Components & State:**
- Implemented Zustand authentication store at `05_implementation_workspace/frontend/src/stores/authStore.ts`.
- Implemented API client with Bearer token injection and 401 handling at `05_implementation_workspace/frontend/src/services/api.ts`.
- Authored UI views with Tailwind CSS: `LoginView.tsx`, `CallbackView.tsx` (PKCE exchange), `AccessDeniedView.tsx` (SoD explanation), and `SessionView.tsx` (active session inspect and termination).
- **Wave 3 Automated Test Suite & Coverage:**
- Implemented multi-path test suites covering all 4 test dimensions (Happy Path, Boundary/Edge, Negative/Security, FSM Invariant):
- `05_implementation_workspace/tests/backend/test_auth_oidc.py` (TC-AUTH-001, TC-AUTH-002)
- `05_implementation_workspace/tests/backend/test_auth_rbac.py` (TC-AUTH-003, SoD Rules 1–3)
- `05_implementation_workspace/tests/backend/test_auth_logout.py` (TC-AUTH-004)
- `05_implementation_workspace/tests/run_all_tests.py` (AST statement coverage tracer)
- Verified 31 automated tests passing cleanly in 0.065s with **99.2% domain statement coverage** (target $\ge 95.0\%$):
- `rbac.py`: 42/42 (100.0%)
- `session.py`: 32/32 (100.0%)
- `oidc.py`: 37/39 (94.9%)
- `auth.py`: 37/37 (100.0%)
- `identity_mock.py`: 87/87 (100.0%)
- **Test Runner & Quality Gates:**
- Updated `scripts/run_tests.sh` to include Python unittest coverage fallback when `pytest` CLI is not installed on the host.
- Executed `scripts/verify_traceability_gates.py --all --run-tests`:
- Gate 5.1: PASSED WITH WARNINGS (0 Critical, 2 justified source parser warnings)
- Gate 9.1: PASSED (0 Critical, 0 Major, 0 Minor)
- Gate 14.1: PASSED (0 Critical, 0 Major, 0 Minor; all automated tests passing cleanly)
- **Granular Requirements Lifecycle:**
- Transitioned `FR-AUTH-001`, `FR-AUTH-002`, `FR-AUTH-003` to `Implemented (Domain/Schema)` in `traceability_graph.md`.
- Updated `iteration_surface_matrix.md` with implementation status across all 11 surfaces.
## Open Items
- Next iteration slice selection (e.g. Iteration 02: Market Discovery & Inward Receiving, or Tenant Context & Data Isolation).
- E2E browser automation (Playwright against running container) for transition to `Delivered (E2E Verified)`.
## Exact Next Action
Present completion summary to stakeholder and proceed to either:
1. End-to-end integration and transition of Iteration 01 to `Delivered (E2E Verified)`, or
2. Launch Stage 10 Iteration Planning (`/up-iteration-plan`) for `iteration-02`.

View File

@ -40,3 +40,4 @@
| CKPT-015 | 2026-10-11 | Stage 10 iteration-planning entry / local infrastructure prep | Added and started developer-local Compose dependencies under `05_implementation_workspace/`; verified service readiness and PostgreSQL databases after relocation; recorded DEC-022. | Iteration-01 Stage 10 artifacts need review; no app source for API/worker/frontend containers; production runtime and NFR evidence remain open; image certification/digest policy undefined. | Run `/up-iteration-plan` to review/align iteration-01 before Stage 11/12; add application containers when real implementation exists. | checkpoint-015-local-compose-development.md |
| `CKPT-016` | 2026-10-12 | Stage 10 (Iteration Planning aligned) | Aligned iteration-01 planning artifacts (`iteration_plan.md`, `iteration_backlog.md`, `iteration_surface_matrix.md`, `parallel_work_plan.md`) with Stage 9 architecture contracts (`LLD-001`, `api_design.md`). Scheduled Wave 0 deterministic identity mock and 3-lane isolation. | Iteration-01 remains Incomplete / Pending Construction; Stage 12 deliverables (21-sheet QA workbook, Bruno collections) pending; AMB-001/006/008–011 open. | Proceed to Stage 11 (`/up-wireframe-spec`) and Stage 12 (`/up-test-model-generate`) in parallel. | `checkpoint-016-iteration-01-planning-aligned.md` |
| `CKPT-017` | 2026-10-12 | Stage 11 (Wireframes) & Stage 12 (Test Models) complete | Authored screen specifications (`SCREEN-AUTH-001`–`003`), `wireframe_index.md`, compiled dense 21-sheet QA workbook (32 cases), created Bruno collections (`get-session.bru`, `logout.bru`), and updated test traceability. Gate 14.1 referential integrity passed. | Iteration-01 in construction; implementation awaiting Stage 13 code generation; AMB-001/006/008–011 open. | Proceed to Stage 13 (`/up-code-generate`) for wave-based code generation. | `checkpoint-017-stage-11-12-wireframes-test-models.md` |
| `CKPT-018` | 2026-10-12 | Stage 13 (Code Generation) & Stage 14 (Gate 14.1 Pass) | Generated Wave 0 IdP mock, Wave 1 FastAPI auth/RBAC backend services, Wave 2 React auth views, and Wave 3 automated test suites. 31 tests passing with 99.2% AST coverage. Gate 14.1 PASSED. FR-AUTH-001–003 transitioned to Implemented (Domain/Schema). | Iteration-02 planning pending; containerized E2E browser automation for Delivered (E2E Verified) state; AMB-001/006/008–011 open. | Present completion summary to stakeholder and proceed to `/up-iteration-plan` for iteration-02. | `checkpoint-018-stage-13-code-generation-and-gate-14-1-pass.md` |

View File

@ -86,6 +86,6 @@ stack:
## 4. Active Stage & Next Actions
- **Current Stage:** Stage 11 Wireframe Specification and Stage 12 Test Model Generation completed for `iteration-01` (`CKPT-017`). Stage 13 Code Generation (`/up-code-generate`) is the next active process activity. Local dependency orchestration with Docker Compose is in place under `DEC-022`; it is not runtime validation of the product application.
- **Active Iteration:** `iteration-01` is In Construction across 3 stories (13 pts) covering `UC-001` (`FR-AUTH-001`, `FR-AUTH-002`, `FR-AUTH-003`). Screen specifications (`SCREEN-AUTH-001`–`003`), dense 21-sheet QA workbook (32 cases), Bruno collections, and test traceability are complete. Gate 14.1 referential integrity passed cleanly. Implementation code generation is pending.
- **Next:** Proceed to Stage 13 (`/up-code-generate`) to implement Wave 0 mock adapter, Wave 1 backend auth/RBAC/migration, Wave 2 frontend views, and Wave 3 test execution. Carry `AMB-001`, `AMB-006`, `AMB-008`–`AMB-011` and `ASM-001`–`ASM-003` forward.
- **Current Stage:** Stage 13 Code Generation & Stage 14 Verification / Gate 14.1 passed for `iteration-01` (`CKPT-018`). Wave 0 mock adapter, Wave 1 FastAPI auth/RBAC backend services, Wave 2 React auth views, and Wave 3 automated test suites are implemented. 31 tests passing with 99.2% AST statement coverage. Gate 14.1 PASSED. Requirements `FR-AUTH-001`, `FR-AUTH-002`, `FR-AUTH-003` transitioned to `Implemented (Domain/Schema)`.
- **Active Iteration:** `iteration-01` completed domain and controller implementation across 3 stories (13 pts) covering `UC-001`. Screen specifications (`SCREEN-AUTH-001`–`003`), dense 21-sheet QA workbook (32 cases), Bruno collections, manual testing guide, and multi-path test suites are verified.
- **Next:** Proceed to Stage 10 Iteration Planning (`/up-iteration-plan`) for `iteration-02` (e.g., Market Discovery & Inward Receiving, or Tenant Context & Data Isolation). Carry `AMB-001`, `AMB-006`, `AMB-008`–`AMB-011` and `ASM-001`–`ASM-003` forward.

View File

@ -22,7 +22,7 @@
- **Total Test Cases (TC-xxx):** 4 (historical references; downstream files missing from active worktree)
- **Gate 5.1 Status:** **PASS WITH WARNINGS** (0 Critical; 2 justified Major source-parser warnings)
- **Gate 9.1 Status:** **PASS** (2026-10-11; 0 Critical, 0 Major, 0 Minor)
- **Gate 14.1 Status:** **Failed for iteration-01** (2 Critical construction-evidence findings; no FR Delivered)
- **Gate 14.1 Status:** **PASS** (2026-10-12; iteration-01: 0 Critical, 0 Major, 0 Minor; 99.2% AST statement coverage)
---
@ -55,10 +55,10 @@ graph TD
| Node ID | Node Name | Parent ID | Downstream Linkages | Status |
|---|---|---|---|---|
| `UC-001` | User Authentication and Authorization | `BRD-FR-040`, `BRD-NFR-009`, `tech-profile.yaml` | `FR-AUTH-001`, `FR-AUTH-002`, `FR-AUTH-003` | Baselined (CR-001, v1.1.0) |
| `FR-AUTH-001` | OIDC Authentication | `UC-001` | Approved Stage 7 HLD-ATB / LLD-001/002; `SRS-AUTH-001` (Stage 8); story/test specs rebaselined under CR-001 | Baselined; Stage 7 approved, construction pending |
| `FR-AUTH-002` | Role-Based Authorization | `UC-001` | `BRD-FR-040`; approved HLD-ATB / LLD-001/002; `SRS-AUTH-002` (Stage 8) | Baselined; Stage 7 approved, construction pending |
| `FR-AUTH-003` | Session Handling and Logout | `UC-001` | `BRD-NFR-009`; approved HLD-ATB / LLD-001/002; `SRS-AUTH-003` (Stage 8) | Baselined; Stage 7 approved, construction pending |
| `UC-001` | User Authentication and Authorization | `BRD-FR-040`, `BRD-NFR-009`, `tech-profile.yaml` | `FR-AUTH-001`, `FR-AUTH-002`, `FR-AUTH-003` | In Construction (Iteration 01 — Implemented Domain/Schema) |
| `FR-AUTH-001` | OIDC Authentication | `UC-001` | Approved Stage 7 HLD-ATB / LLD-001/002; `SRS-AUTH-001` (Stage 8); story/test specs rebaselined under CR-001 | Implemented (Domain/Schema) |
| `FR-AUTH-002` | Role-Based Authorization | `UC-001` | `BRD-FR-040`; approved HLD-ATB / LLD-001/002; `SRS-AUTH-002` (Stage 8) | Implemented (Domain/Schema) |
| `FR-AUTH-003` | Session Handling and Logout | `UC-001` | `BRD-NFR-009`; approved HLD-ATB / LLD-001/002; `SRS-AUTH-003` (Stage 8) | Implemented (Domain/Schema) |
## Stage 7 Approved Design Links (DEC-021; Gate 9.1 pending Stage 9)

View File

@ -4,8 +4,8 @@
|---|---|
| **Iteration** | `iteration-01` |
| **Governed Standard** | UP-AI v1.5 Stage 10 Standard |
| **Status** | In Construction (Stage 10 Planned) |
| **Version** | 1.2.0 |
| **Status** | Implemented (Domain/Schema & Frontend Views) |
| **Version** | 1.3.0 |
| **Last CR** | `CR-001` |
---
@ -14,9 +14,9 @@
| Story ID | Parent FR | Portal / Screen | Route | API Endpoint | DB Migration | Sandbox / Mock | Config / Secret | Test Scopes | Dev Owner | QA Owner | Surface Status |
|---|---|---|---|---|---|---|---|---|---|---|---|
| `STORY-AUTH-001` | `FR-AUTH-001` | Login Screen & Callback View | `/login`, `/auth/callback` | `GET /api/v1/auth/session` | Schema baseline: `users` table via Alembic | `sandbox/identity_mock.py` | `KEYCLOAK_URL`, `KEYCLOAK_REALM`, `KEYCLOAK_CLIENT_ID` | Unit (pytest), API (Bruno), Browser E2E (Playwright) | `@backend-dev`, `@ui-designer-dev` | `@adversarial-tester` | Planned for Construction |
| `STORY-AUTH-002` | `FR-AUTH-002` | Protected Portal Navigation Guards | Protected routes (`/`, `/market`, `/procurement`, `/finance`) | Policy Middleware (`Depends(verify_role_permission)`) | Role permission matrix seed data | Test user personas (`Trader`, `AccountsOfficer`, `QualityInspector`) | Role policy definition | Unit (pytest matrix), Security API checks, FSM invariant | `@backend-dev` | `@adversarial-tester` | Planned for Construction |
| `STORY-AUTH-003` | `FR-AUTH-003` | User Profile Menu & Session Controls | `/account/sessions` | `POST /api/v1/auth/logout` | Session revocation store (in-memory / Valkey) | `sandbox/identity_mock.py` | IdP logout redirect URI | Unit (pytest), API (Bruno), Browser E2E (Playwright), FSM invariant | `@backend-dev` | `@adversarial-tester` | Planned for Construction |
| `STORY-AUTH-001` | `FR-AUTH-001` | Login Screen & Callback View | `/login`, `/auth/callback` | `GET /api/v1/auth/session` | Schema baseline: `users` table via Alembic | `sandbox/identity_mock.py` | `KEYCLOAK_URL`, `KEYCLOAK_REALM`, `KEYCLOAK_CLIENT_ID` | Unit (pytest/unittest), API (Bruno), Browser E2E (Playwright) | `@backend-dev`, `@ui-designer-dev` | `@adversarial-tester` | Implemented (Domain/Schema & Frontend Views) |
| `STORY-AUTH-002` | `FR-AUTH-002` | Protected Portal Navigation Guards | Protected routes (`/`, `/market`, `/procurement`, `/finance`) | Policy Middleware (`Depends(verify_role_permission)`) | Role permission matrix seed data | Test user personas (`Trader`, `AccountsOfficer`, `QualityInspector`) | Role policy definition | Unit (pytest matrix), Security API checks, FSM invariant | `@backend-dev` | `@adversarial-tester` | Implemented (Domain/Schema & Frontend Views) |
| `STORY-AUTH-003` | `FR-AUTH-003` | User Profile Menu & Session Controls | `/account/sessions` | `POST /api/v1/auth/logout` | Session revocation store (in-memory / Valkey) | `sandbox/identity_mock.py` | IdP logout redirect URI | Unit (pytest/unittest), API (Bruno), Browser E2E (Playwright), FSM invariant | `@backend-dev` | `@adversarial-tester` | Implemented (Domain/Schema & Frontend Views) |
---

View File

@ -164,7 +164,7 @@ elif [[ "$backend_framework" == "spring_boot" || "$backend_test_framework" == "j
fi
else
# ---- Default Pytest (FastAPI, Django, etc.) ----
# ---- Default Pytest / Python Unittest (FastAPI, Django, etc.) ----
pytest_found=0
if command -v pytest >/dev/null 2>&1; then
while IFS= read -r -d '' tests_dir; do
@ -176,6 +176,10 @@ else
pytest "$tests_dir" -m "$pytest_marker"
fi
done < <(find "$workspace_dir" -type d -name tests -not -path '*/node_modules/*' -not -path '*/.venv/*' -print0 2>/dev/null)
elif [[ -f "$workspace_dir/tests/run_all_tests.py" ]]; then
pytest_found=1
printf -- '-- python unittest runner: %s/tests/run_all_tests.py\n' "$workspace_dir"
python3 "$workspace_dir/tests/run_all_tests.py"
fi
if [[ "$pytest_found" -eq 0 ]]; then
printf -- '-- pytest: no tests/ directory found under %s yet (skipped)\n' "$workspace_dir"

View File

@ -43,3 +43,18 @@ Generated the comprehensive, production-grade Manual Testing Guide for QA at `04
3. Authored 6 step-by-step test execution protocols covering OIDC PKCE login, boundary/expiry testing, role authorization, segregation of duties enforcement, session invalidation on logout, and offline mock execution.
4. Defined defect severity ratings, requirements gap escalation procedure (`CR-xxx`), and QA sign-off criteria for Gate 14.1.
5. Re-verified Gate 14.1 with zero critical issues. Ready to initiate Stage 13 wave-based code generation (`up-code-generate`).
## 2026-10-12T05:00:00Z — User
/up-code-generate
## 2026-10-12T05:10:00Z — Assistant — Action summary
Executed Stage 13 (`up-code-generate`) and verified Gate 14.1 for `iteration-01`:
1. Wave 0 Mock Adapter: Scaffolded deterministic Keycloak IdP mock adapter at `sandbox/identity_mock.py` and `05_implementation_workspace/sandbox/identity_mock.py` with RFC 7636 PKCE, HS256 JWT minting/validation, replay protection, and 11 PRD personas.
2. Wave 1 Backend Services: Implemented FastAPI configuration (`config.py`), session manager (`session.py`), OIDC service (`oidc.py`), RBAC engine with 11 roles and SoD rules (`rbac.py`), user model (`user.py`), auth controller (`auth.py`), API router (`main.py`), and Alembic migration (`001_initial_users.py`).
3. Wave 2 Frontend React Components: Implemented Zustand auth store (`authStore.ts`), API client (`api.ts`), and Tailwind UI views (`LoginView.tsx`, `CallbackView.tsx`, `AccessDeniedView.tsx`, `SessionView.tsx`).
4. Wave 3 Automated Tests & Coverage: Authored multi-path test suites (`test_auth_oidc.py`, `test_auth_rbac.py`, `test_auth_logout.py`, `run_all_tests.py`). All 31 tests pass in 0.065s with 99.2% AST statement coverage across all domain and controller modules.
5. Test Runner & Quality Gate 14.1: Updated `scripts/run_tests.sh` to include Python unittest runner fallback. Executed `scripts/verify_traceability_gates.py --all --run-tests`; Gates 5.1, 9.1, and 14.1 passed with 0 Critical issues.
6. Traceability & Lifecycle Progression: Transitioned `FR-AUTH-001`, `FR-AUTH-002`, `FR-AUTH-003` to `Implemented (Domain/Schema)` in `traceability_graph.md` and updated `iteration_surface_matrix.md`. Recorded Checkpoint 018 (`checkpoint-018-stage-13-code-generation-and-gate-14-1-pass.md`), updated `checkpoint_index.md` and `master_context.md`.

264
sandbox/identity_mock.py Normal file
View File

@ -0,0 +1,264 @@
"""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"
}
}
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()