morethanadiagnosis-hub/openspec/changes/2025-11-17-authentication-system/proposal.md
Claude 0afa81280e
feat(openspec): propose foundational infrastructure specs
Add three critical infrastructure proposals for implementation readiness:

1. Data Model v1 (Consolidated Schema)
   - All entities from approved features (User, Profile, Forum, Blog, etc.)
   - Field-level data classification (Public/PII/PHI)
   - Relationships, indexes, and retention policies
   - DSR support and migration strategy
   - Target: openspec/specs/data-model.md

2. Authentication & Authorization System
   - OAuth2/OIDC with PKCE for secure auth
   - RBAC (member, moderator, admin roles)
   - Pseudonym support for privacy
   - MFA (TOTP), password reset, account lockout
   - Audit logging for compliance
   - Target: openspec/specs/architecture.md

3. Design System & Component Library
   - Unified components for Android/iOS/Web parity
   - WCAG 2.2 AA+ accessibility built-in
   - Design tokens (colors, typography, spacing)
   - Theming (light/dark/high contrast)
   - Platform-specific adaptations (RN, Next.js)
   - Target: openspec/specs/architecture.md

These proposals unblock implementation work across all features.

/review areas=backend,security,compliance,accessibility,mobile,web,design
2025-11-18 00:17:49 +00:00

153 lines
8 KiB
Markdown

# Proposal: Authentication & Authorization System
Status: draft
Authors: Security Team, Identity Team
Owners: Security Lead, Identity Lead, Architecture Lead
Created: 2025-11-17
Scope: spec
Related: openspec/specs/architecture.md, openspec/specs/privacy-compliance.md
Summary
- Implement OAuth2/OIDC-based authentication with role-based access control (RBAC), pseudonym support, session management, and compliance-friendly audit logging.
Motivation
- Secure user authentication is foundational for all features.
- Support privacy-conscious identity (pseudonyms) while maintaining accountability.
- Enable fine-grained authorization for member-only content, moderation, and admin actions.
Goals / Non-Goals
- Goals: OAuth2/OIDC auth flow, session management, RBAC, pseudonym handling, MFA support, password reset, account lockout, audit logging.
- Non-Goals: custom auth protocol (use standards); biometric auth (future); SSO with external providers (future, but design for extensibility).
User Stories
- As a user, I can sign up with email/password and verify my email.
- As a user, I can log in securely and stay logged in across devices.
- As a user, I can use a pseudonym in the community without exposing my real name.
- As a moderator, I have elevated permissions to manage flagged content.
- As an admin, I can view audit logs of authentication events.
Requirements
Functional
- Sign up: email/password registration with email verification.
- Sign in: OAuth2 authorization code flow with PKCE (for mobile/SPA security).
- Session management: access tokens (short-lived, 15 min) and refresh tokens (long-lived, 30 days, rotated).
- Password management: secure hashing (Argon2 or bcrypt), reset flow with time-limited tokens.
- MFA: TOTP (time-based one-time password) support for opt-in users.
- Account lockout: after N failed login attempts (e.g., 5), lock for configurable duration (e.g., 30 min).
- RBAC: roles (member, moderator, admin) with permissions (read_public, write_forum, moderate_content, admin_panel).
- Pseudonym support: user can set pseudonym in profile; display in forum/community contexts.
Accessibility
- Sign-in/sign-up forms: keyboard accessible, screen reader labels, clear error messages.
- MFA setup: accessible QR code alternatives (manual entry codes).
- Password strength feedback: descriptive, not relying solely on color.
Privacy & Compliance
- Email is PII; hashed passwords never logged.
- Audit log: login attempts, password resets, MFA changes (log user ID, timestamp, IP, outcome; no passwords).
- Session tokens: stored securely (HttpOnly, Secure, SameSite cookies for web; secure storage for mobile).
- DSR support: export auth history; delete user account purges tokens and auth records.
Security & Threat Model
- Password hashing: Argon2id (preferred) or bcrypt with high work factor.
- Token security: JWT access tokens (signed, short-lived); refresh tokens (opaque, stored server-side, rotated).
- PKCE: required for mobile/SPA to prevent authorization code interception.
- Rate limiting: login endpoint (e.g., 10 attempts per IP per minute); password reset (e.g., 3 per hour per email).
- Account lockout: protect against brute force; notify user via email on lockout.
- Audit logging: all auth events logged with sanitized details (no credentials).
Architecture & API
Endpoints
- `POST /api/v1/auth/signup` — register new user (email, password); returns user ID, sends verification email.
- `POST /api/v1/auth/verify-email` — verify email with token.
- `POST /api/v1/auth/login` — OAuth2 authorization code flow initiation (returns code).
- `POST /api/v1/auth/token` — exchange code for access/refresh tokens (PKCE).
- `POST /api/v1/auth/refresh` — rotate refresh token, get new access token.
- `POST /api/v1/auth/logout` — revoke refresh token.
- `POST /api/v1/auth/password-reset-request` — send reset email.
- `POST /api/v1/auth/password-reset-confirm` — reset password with token.
- `POST /api/v1/auth/mfa/enable` — enable TOTP MFA (returns QR code + secret).
- `POST /api/v1/auth/mfa/verify` — verify TOTP code.
- `GET /api/v1/auth/me` — get current user info (requires access token).
Data Model
- User: id, email (PII, unique, hashed for lookup), password_hash, email_verified, mfa_enabled, mfa_secret (encrypted), locked_until (nullable), failed_login_attempts, created_at, updated_at, deleted_at.
- Role: id, name (member, moderator, admin), permissions (JSON or relation table).
- UserRole: id, user_id (FK), role_id (FK).
- RefreshToken: id, user_id (FK), token_hash, expires_at, created_at, revoked_at.
- AuthAuditLog: id, user_id (FK, nullable), event_type (signup, login_success, login_fail, password_reset, etc.), ip_address, user_agent, created_at.
Session Flow
1. User signs in → backend generates authorization code.
2. Client exchanges code (+ PKCE verifier) for access token (JWT, 15 min) and refresh token (opaque, 30 days).
3. Client includes access token in Authorization header for API calls.
4. On access token expiry, client uses refresh token to get new access/refresh tokens.
5. On logout, client revokes refresh token; server invalidates it.
Pseudonym Handling
- User profile includes `pseudonym` field (nullable).
- Forum/community contexts display pseudonym if set, otherwise display_name.
- Moderation/admin views show both pseudonym and real identity (with audit logging).
Observability & Telemetry
- Metrics: login success/failure rates, MFA adoption, lockout frequency.
- Alerts: spike in failed logins (possible attack), lockout rate exceeds threshold.
- Traces: auth flow latency (signup, login, token exchange).
Test Plan
- Unit tests: password hashing, token generation/validation, RBAC checks.
- Integration tests: full auth flows (signup, login, refresh, logout, password reset, MFA).
- Security tests: brute force protection (lockout), PKCE validation, token expiry.
- Accessibility tests: keyboard nav on auth forms, screen reader labels.
- Compliance tests: DSR export includes auth history, delete purges tokens.
Migration / Rollout Plan
- Deploy auth service to staging; test with pilot users.
- Migrate existing users (if any from Wix) with password reset flow (cannot import passwords).
- Feature flag for MFA (opt-in, not mandatory initially).
- Monitor login success rates; rollback on anomalies.
Risks & Mitigations
- Password database breach → use Argon2id, salted hashes; consider encrypted fields.
- Token leakage → short-lived access tokens, secure storage, HttpOnly cookies.
- Account enumeration → consistent error messages for signup/login ("email or password incorrect").
- Lockout abuse → notify user via email, require CAPTCHA after multiple lockouts.
Alternatives Considered
- Custom auth vs OAuth2/OIDC → choosing OAuth2/OIDC for standards compliance and future SSO extensibility.
- JWT vs opaque refresh tokens → choosing opaque (server-side validation) for better revocation control.
Work Breakdown
1. Implement password hashing and user registration
2. Build OAuth2 authorization code + PKCE flow
3. Token generation, validation, and refresh logic
4. RBAC middleware and permission checks
5. MFA (TOTP) setup and verification
6. Password reset flow
7. Account lockout logic
8. Audit logging
9. Client SDKs (mobile, web) for auth flows
10. Security review and penetration testing
Acceptance Criteria
- Signup, login, refresh, logout flows functional and tested.
- MFA (TOTP) opt-in working.
- RBAC permissions enforced on protected endpoints.
- Password reset flow with time-limited tokens.
- Account lockout after failed attempts.
- Audit logs capture all auth events (sanitized).
- Accessibility checks pass on auth UI.
- Security review completed with no critical findings.
- Pseudonym display working in community contexts.
Open Questions
- Social login (Google, Apple) support timeline? (Future proposal)
- Passkey/WebAuthn support? (Future proposal)
- Session timeout for inactivity (in addition to token expiry)?
Slash Commands
- `/review areas=security,backend,mobile,web,accessibility,compliance`
- `/apply spec=openspec/specs/architecture.md`
- `/archive link=<PR>`