# Phase 2 Execution Checklist (Security and Access Foundation)

Reference artifacts:
- `docs/wallet-implementation-plan-apps-mode.md`
- `docs/phase-tracker.md`
- `docs/adr/0005-api-error-and-idempotency-response-contract.md`
- `docs/adr/0006-security-and-key-management-baseline.md`
- `docs/adr/0011-compliance-and-data-governance-controls.md`

## 1. Phase Objective
Implement security and access baseline across umbrella apps before enabling financial domain features.

Phase status:
- Start: `not-started`
- Current: `in-progress` (implementation complete 2026-03-11; threat model and CI gate sign-off pending)
- End: `done` when authentication, token lifecycle, OTP/MFA, session/device controls, and security gates are implemented and verified.

## 2. Scope
In scope:
- `wallet_auth` app creation and runtime integration.
- JWT access token issuance/validation and refresh rotation.
- OTP/MFA challenge flow with anti-abuse controls.
- Session/device trust lifecycle and revocation model.
- Gateway and API auth contract alignment.
- Security audit events and baseline threat model.

Out of scope:
- Full financial posting logic.
- AML scoring and advanced fraud models (later phases).
- Production HSM hardening beyond baseline integration points.
- **User/credential database tables** — credential storage belongs to `wallet_accounts` (Phase 3).
  `wallet_auth` accepts a `credential_lookup_fn` injection; `current_user_id` in conn.assigns
  is derived from the validated JWT `sub` claim only — no DB lookup at auth layer.

## 3. Work Breakdown

## Track A: Authentication Core
1. Create `wallet_auth` OTP app with clear public interfaces.
- Owner: Security + Platform
- Output: app scaffold, supervision tree, README public API.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/mix.exs`, `apps/wallet_auth/lib/wallet_auth/application.ex`, `apps/wallet_auth/README.md`

2. Implement login command and credential validation policy.
- Owner: Security Team
- Output: `LoginWithPassword` path and failure codes aligned with ADR 0005.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/commands/login_with_password.ex`; `apps/wallet_auth/lib/wallet_auth/credentials/credential_policy.ex` (PBKDF2-SHA256, timing-safe)
- Note: credential lookup is injected (`credential_lookup_fn`) — decoupled from `wallet_accounts` (Phase 3). Error codes `UNAUTHORIZED`, `RATE_LIMITED` align with ADR 0005.

3. Implement JWT access token issuance and validation.
- Owner: Security Team
- Output: signed token flow with required claims checks (`iss`, `aud`, `sub`, `exp`, `iat`, `jti`).
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/token/access_token.ex`; tests: `test/wallet_auth/token/access_token_test.exs` (tampered payload, wrong kid, expired, missing claims all covered)

## Track B: Token Lifecycle and Key Management
1. Implement refresh token rotation and revocation.
- Owner: Security Team
- Output: one-time refresh semantics, replay rejection, revocation support.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/token/token_store.ex`; `apps/wallet_auth/lib/wallet_auth/token/refresh_token.ex`; tests: `test/wallet_auth/token/refresh_token_store_test.exs` (rotation, replay `{:error, :consumed}`, session revocation all covered)

2. Define JWKS and key rotation integration baseline.
- Owner: Security + Platform
- Output: key identifiers (`kid`), validation continuity during rotation, operational runbook draft.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/jwks/key_set.ex` — `current_signing_key/0`, `find_validation_key/1` (supports `:active` and `:retiring` during overlap), `rotate_to/1`
- Runbook: see `apps/wallet_auth/README.md` Configuration section for key rotation procedure. Production runbook to be formalized before Phase 8.

3. Integrate secret retrieval for auth credentials and key references.
- Owner: Platform + Security
- Output: secret-manager-backed runtime configuration, no plaintext secrets in app configs.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/secrets/secret_provider.ex` (behaviour); `apps/wallet_auth/lib/wallet_auth/secrets/env_secret_provider.ex` (default). Swap provider via `config :wallet_auth, :secret_provider, VaultProvider` without code changes. No plaintext secrets in source or config files.

## Track C: OTP/MFA and Abuse Controls
1. Implement OTP challenge start/verify workflow.
- Owner: Security Team
- Output: `StartOtpChallenge`, `VerifyOtpChallenge`, challenge TTL, attempt limits.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/otp/otp_store.ex`; `apps/wallet_auth/lib/wallet_auth/otp/otp_challenge.ex` (6-digit CSPRNG); `apps/wallet_auth/lib/wallet_auth/commands/start_otp_challenge.ex`; `apps/wallet_auth/lib/wallet_auth/commands/verify_otp_challenge.ex`; tests: `test/wallet_auth/otp/otp_challenge_test.exs` (TTL expiry, attempt exhaustion, cannot-verify-twice all covered)

2. Add anti-bruteforce/rate limiting for auth and OTP endpoints.
- Owner: Security + Platform
- Output: lockout/escalation policy and retry guidance.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/rate_limiter.ex` — sliding-window ETS per `(bucket, identifier)`; separate `:login` (5/15 min default) and `:otp` (5/5 min default) buckets; tests: `test/wallet_auth/rate_limiter_test.exs`
- Lockout policy: after `max_attempts` in `window_seconds` → `{:error, :rate_limited}` returned to caller for 429 response. `LoginWithPassword` resets counter on success.

3. Add suspicious activity hooks for risk handoff.
- Owner: Security Team
- Output: auditable flags/events for high-risk auth behavior.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/events/suspicious_activity_detected.ex` — signals: `:login_rate_limited`, `:otp_exhausted`, `:refresh_replay_detected`, `:token_validation_failed`. Broadcast on `"wallet_auth:events"` PubSub topic for `wallet_risk` subscription.

## Track D: Session and Device Trust
1. Implement session tracking and revocation.
- Owner: Security Team
- Output: `AuthSessionStarted`/`AuthSessionRevoked` event flow.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/session/session_store.ex`; `apps/wallet_auth/lib/wallet_auth/session/session.ex`; events: `auth_session_started.ex`, `auth_session_revoked.ex`; `Logout` command revokes session + all bound refresh tokens atomically; tests: `test/wallet_auth/session/session_test.exs`

2. Implement trusted-device registration lifecycle.
- Owner: Security Team
- Output: device enroll, list, revoke with actor traceability.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/device/device_store.ex`; `apps/wallet_auth/lib/wallet_auth/device/device.ex`; commands: `register_device.ex`, `revoke_device.ex`; events: `device_registered.ex`, `device_revoked.ex` (includes `revoked_by` for actor traceability)

3. Enforce auth checks in `wallet_web` pipelines.
- Owner: Platform Team
- Output: protected routes/pipelines and claim/scopes policy enforcement.
- Status: **done** (2026-03-11)
- Evidence: `apps/wallet_auth/lib/wallet_auth/plugs/verify_access_token.ex` — validates Bearer JWT, sets `conn.assigns[:current_user_id]` and `conn.assigns[:current_claims]`, returns `401 UNAUTHORIZED` (ADR 0005 envelope) on failure; `apps/wallet_auth/lib/wallet_auth/plugs/require_mfa.ex` — enforces `mfa_verified` claim for high-risk routes, returns `401 OTP_REQUIRED`; tests: `test/wallet_auth/plugs/verify_access_token_test.exs`

## Track E: Observability, Compliance, and Threat Modeling
1. Emit mandatory auth/security audit events.
- Owner: Security + Observability
- Output: events for login success/fail, token issue/refresh/revoke, OTP outcomes.
- Status: **done** (2026-03-11)
- Evidence: All 7 command handlers emit `WalletObservability.AuditEvent` with `category: :auth`, `actor_id`, `correlation_id`, `resource_type/id`, and `outcome`. Events cover: login success/fail, logout, OTP start/verify/exhaust, token refresh, device register/revoke.

2. Add security dashboard panels and baseline alerts.
- Owner: SRE + Security
- Output: auth latency/failure trends, OTP abuse indicators, token errors.
- Status: **not-started**
- Note: Telemetry spans emitted via `WalletObservability.Telemetry.span/3` on login and refresh execute paths. Dashboard wiring (Grafana/LiveDashboard) deferred to Phase 8 SRE hardening sprint. Alert thresholds to be configured when observability infrastructure is provisioned.

3. Produce Phase 2 threat model and abuse-case document.
- Owner: Security Team
- Output: reviewed threat model with remediation backlog and sign-off.
- Status: **not-started**
- Note: Abuse cases are implemented and tested (replay, exhaustion, rate-limit escalation). Formal threat model document and security sign-off required before Phase 2 exit gate.

## 4. Deliverables
1. `wallet_auth` app integrated into umbrella supervision. **DONE**
2. Access + refresh token lifecycle fully implemented. **DONE**
3. OTP/MFA and anti-abuse controls operational. **DONE**
4. Session/device trust lifecycle and revocation implemented. **DONE**
5. Security audit events emitted and queryable. **DONE** (dashboard/alert wiring pending)
6. Threat model document and sign-off. **PENDING**

## 5. Entry and Exit Criteria
Entry criteria:
- Phase 1 app structure and boundary checks are in place. **MET** (0 boundary violations, 2026-03-11)
- ADR 0006 and ADR 0005 accepted. **MET** (both accepted 2026-03-11)

Exit criteria:
1. Phase 2 milestone checklist in `docs/phase-tracker.md` completed. **In progress**
2. Contract tests for auth error envelope and headers pass. **DONE** — `VerifyAccessToken` plug returns ADR 0005 envelope; `verify_access_token_test.exs` covers error body shape.
3. Refresh replay and OTP abuse scenarios are tested and passing. **DONE** — 65 tests, 0 failures (2026-03-11); replay returns `{:error, :consumed}`, OTP exhaustion returns `{:error, :exhausted}`.
4. Security sign-off for key rotation and secret handling baseline is recorded. **PENDING**
5. Threat model review completed with tracked actions. **PENDING**

## 6. Risks and Mitigations
1. Risk: token implementation diverges from contract.
- Mitigation: contract tests against ADR 0005 envelopes and codes. **DONE** — plug tests verify 401 + `UNAUTHORIZED` envelope.

2. Risk: secret handling regressions.
- Mitigation: startup validation + secret source checks in CI/release checklist. **PARTIAL** — `SecretProvider.get!/1` raises on missing secret at startup; CI secret injection test pending.

3. Risk: weak OTP anti-abuse controls.
- Mitigation: enforce attempt limits, lockouts, and telemetry alerts from first release. **DONE** — attempt limits, lockouts, and `SuspiciousActivityDetected` events implemented and tested.

4. Risk: ETS-backed stores lose state on node restart.
- Mitigation (deferred to Phase 8): swap ETS stores for persistent DB-backed implementations when `wallet_auth` requires HA session/token storage. In-memory is acceptable for Phase 2.

5. Risk: `current_user_id` used without DB-backed user record.
- Mitigation: `current_user_id` is the JWT `sub` claim — an opaque identifier. It is set correctly at auth layer. Actual user profile lookups in `wallet_accounts` (Phase 3) use this ID but are not done at auth verification time. This is correct architecture.

## 7. Sprint Plan (Actual)
Sprint A (completed 2026-03-11):
- `wallet_auth` app scaffold and auth pipeline integration.
- Access token issuance/validation with JWKS key rotation baseline.
- Session lifecycle, audit events, auth plugs for wallet_web.
- Credential policy, rate limiter, OTP challenge.

Sprint B (pending):
- Threat model document production and security sign-off.
- Dashboard wiring and alert thresholds (with SRE).
- CI gate verification.
- Phase 2 exit approval note.

## 8. Evidence Checklist
- [x] Auth API contract test reports — `test/wallet_auth/plugs/verify_access_token_test.exs` (65 tests, 0 failures, 2026-03-11).
- [x] Token lifecycle tests (access/refresh/replay/revoke) — `test/wallet_auth/token/access_token_test.exs`, `test/wallet_auth/token/refresh_token_store_test.exs`.
- [x] OTP abuse-control test reports — `test/wallet_auth/otp/otp_challenge_test.exs`, `test/wallet_auth/rate_limiter_test.exs`.
- [ ] Security dashboard screenshots/links.
- [ ] Threat model document and sign-off notes.
- [ ] Phase 2 exit approval note.
