
# Implementation Plan: FastAPI JWT Access Middleware

**Branch**: `001-its-a-python` | **Date**: 2025-10-04 | **Spec**: [/Users/tianhaowang/Documents/GitHub/Vibrant-auth-middleware/specs/001-its-a-python/spec.md](/Users/tianhaowang/Documents/GitHub/Vibrant-auth-middleware/specs/001-its-a-python/spec.md)
**Input**: Feature specification from `/specs/001-its-a-python/spec.md`

## Summary
Deliver an organization-wide FastAPI middleware that extracts JWTs from cookies or the Authorization header, verifies HS256/RS256 signatures with live configuration service material, and emits structured authentication decisions while denying unsafe requests by default.

## Technical Context
**Language/Version**: Python 3.13  
**Primary Dependencies**: FastAPI, Starlette, PyJWT, httpx (for configuration service + SSE)  
**Storage**: N/A (in-memory caches only)  
**Testing**: pytest with httpx.AsyncClient + pytest-asyncio  
**Target Platform**: Linux containers running under organization Kubernetes  
**Project Type**: single  
**Performance Goals**: ≤5 ms middleware overhead at 1,000 req/s per application instance  
**Constraints**: Default-deny posture, configuration service delivers signing material via HTTPS + SSE, secrets never logged  
**Scale/Scope**: Shared library for ~50 FastAPI services across multiple clusters

## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*

- **Authenticated Entry Only**: Middleware inserted as first Starlette middleware; plan adds contract tests ensuring requests without validated decisions are denied before route execution.
- **Deterministic Identity Contracts**: Define `AuthDecision` dataclass and token-source enum; contract tests lock decision payloads so identical inputs always produce identical outcomes.
- **Test-Enforced Guard Rails**: Phase 1 delivers failing tests covering valid tokens, expired/revoked tokens, malformed payloads, missing token_type, and rotation pending states before any implementation work.
- **Traceable Access Decisions**: Plan includes structured JSON logging with correlation IDs, token source, decision, reason, and principal; quickstart instructs teams on telemetry expectations.
- **Least-Privilege Configuration**: Settings default to deny when configuration service is unavailable or materials are stale; research locks deny-until-refresh behavior during rotations.

## Project Structure

### Documentation (this feature)
```
specs/001-its-a-python/
├── plan.md
├── research.md
├── data-model.md
├── quickstart.md
├── contracts/
│   └── middleware-behavior.md
└── tasks.md            # Generated by /tasks command (future)
```

### Source Code (repository root)
```
src/
├── vibrant_auth_middleware/
│   ├── __init__.py
│   ├── middleware.py
│   ├── config.py
│   ├── token_source.py
│   ├── decisions.py
│   └── telemetry.py

tests/
├── unit/
│   ├── test_cookie_extraction.py
│   ├── test_header_extraction.py
│   ├── test_algorithm_switch.py
├── contract/
│   └── test_middleware_contract.py
└── integration/
    ├── test_rotation_events.py
    └── test_negative_paths.py
```

**Structure Decision**: Single-project library; middleware package under `src/vibrant_auth_middleware`, tests colocated under `tests/` by layer.

## Phase 0: Outline & Research
- Consolidated library choices and performance expectations in `research.md`, selecting PyJWT and SSE-based key rotation per clarification.
- Captured observability requirements for correlation IDs and structured logging.
- Confirmed default-deny behavior during configuration outages and rotation events.

**Output**: research.md complete; no outstanding clarifications.

## Phase 1: Design & Contracts
- Documented entities (`TokenSource`, `SigningMaterial`, `AuthDecision`, `MiddlewareSettings`) and lifecycle in `data-model.md` to drive implementation.
- Auth behavior contract captured in `contracts/middleware-behavior.md`, mapping scenarios to decision outcomes for failing tests.
- Authenticated flows and setup guidance published in `quickstart.md` for adopter teams.
- Upcoming tests will include unit coverage for cookie/header parsing, contract tests for decision payloads, and integration tests simulating rotation events.
- Agent context update script will run during implementation to register new dependencies (FastAPI, PyJWT, httpx).

**Output**: data-model.md, contracts/middleware-behavior.md, quickstart.md drafted with failing-test expectations.

## Phase 2: Task Planning Approach
- `/tasks` command will read this plan plus Phase 1 artifacts to generate 25-30 tasks prioritized by TDD.
- Contract and integration tests will be emitted before middleware implementation; tasks will keep token-source files and telemetry utilities isolated for parallelism.
- Security posture tasks must include negative authentication paths, rotation-deny checks, and structured logging verification per constitution.

**Estimated Output**: tasks.md enumerating setup, testing, middleware implementation, telemetry wiring, and configuration-service integration steps.

## Phase 3+: Future Implementation
*Outlined for completeness; execution happens after /tasks command.*

**Phase 3**: Task execution (/tasks command creates tasks.md)  
**Phase 4**: Implementation (execute tasks.md following constitutional principles)  
**Phase 5**: Validation (run tests, execute quickstart.md, performance validation)

## Complexity Tracking
No deviations from the standard approach at this stage.

| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| _None_ | — | — |

## Progress Tracking
*This checklist is updated during execution flow*

**Phase Status**:
- [x] Phase 0: Research complete (/plan command)
- [x] Phase 1: Design complete (/plan command)
- [x] Phase 2: Task planning complete (/plan command - describe approach only)
- [ ] Phase 3: Tasks generated (/tasks command)
- [ ] Phase 4: Implementation complete
- [ ] Phase 5: Validation passed

**Gate Status**:
- [x] Initial Constitution Check: PASS
- [x] Post-Design Constitution Check: PASS
- [x] All NEEDS CLARIFICATION resolved
- [x] Complexity deviations documented (none)

---
*Based on Constitution v1.0.0 - See `.specify/memory/constitution.md`*
