# Milestone 3: Authentication & Authorization

**Duration:** 2 weeks  
**Goal:** Secure access control with passkeys and granular permissions

## Tasks

### Week 5: Passkey Authentication

- [x] WebAuthn server implementation
  - [x] Relying party configuration
  - [x] Challenge generation and storage
  - [x] Attestation verification
  - [x] Credential storage
  
- [x] Passkey registration flow
  - [x] Initiate registration endpoint
  - [x] Verify registration response
  - [x] Store credential with user association
  - [ ] Authenticated multiple-passkey management UI (deferred account polish)
  
- [x] Passkey authentication flow
  - [x] Initiate login endpoint
  - [x] Verify assertion response
  - [x] Create session on success
  
- [x] Session management
  - [x] Opaque HttpOnly cookie generation
  - [x] Session storage in database
  - [x] Session validation middleware
  - [x] Session revocation endpoint
  - [ ] Automatic session refresh (deferred hardening)

### Week 6: Password Fallback & Authorization

- [x] Password authentication
  - [x] Argon2id password hashing
  - [x] Password validation endpoint
  - [x] Password change endpoint
  - [x] Password strength requirements
  
- [x] Role-based access control
  - [x] Permission model: viewer, editor, admin
  - [x] Token scopes: docs, sync, admin
  - [x] Middleware for permission checking
  - [x] Admin UI for managing user roles

- [x] User management
  - [x] User registration (email + passkey/password)
  - [x] User profile management
  - [x] Account deletion
  - [x] User listing (admin only)

- [x] API token support
  - [x] Bearer token format for developer clients
  - [x] Server stores token hashes only
  - [x] Token scopes and revocation
  - [x] Device-code flow for CLI onboarding
  
- [ ] Content signing (optional)
  - Ed25519 key pair generation
  - Document signing on publish
  - Signature verification display
  - Deferred to production hardening because the current publish path does not yet need signing state.

## Acceptance Criteria

### Functional
- [x] Users can register with passkey on supported browsers
- [x] Passkey login endpoints verify browser assertions
- [x] Password fallback works when passkey unavailable
- [x] Sessions expire after default 24h timeout
- [x] Sessions can be revoked
- [x] Read/write/admin permissions enforced on protected endpoints
- [x] API clients can use scoped bearer tokens
- [x] CLI clients can use device-code flow
- [ ] Per-document and per-collection permission UI (deferred until collaboration resource modeling)

### Non-Functional
- [x] Argon2id parameters: time=3, memory=64MB, parallelism=4
- [x] Session cookies: HttpOnly, SameSite=Strict
- [x] Rate limiting: 5 auth attempts per minute per IP/path
- [x] No timing attacks on password comparison (constant-time)
- [x] Password and token comparisons use constant-time comparison
- [x] Auth events logged to audit_log table
- [ ] Ed25519 signatures verified on document read (if enabled)

### Security
- [x] WebAuthn challenges single-use and time-limited (5 minutes)
- [x] Credential IDs are generated by authenticators
- [ ] Password reset requires email verification (out of scope until email/recovery is added)
- [x] Password login uses generic invalid credential responses
- [x] Public registration cannot attach credentials to an existing account
- [x] Device-code polling consumes the code after first token issuance

## Database Schema Additions

```sql
-- WebAuthn credentials
CREATE TABLE webauthn_credentials (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES users(id),
    credential_id BLOB NOT NULL UNIQUE,
    public_key BLOB NOT NULL,
    sign_count INTEGER NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL,
    last_used_at DATETIME
);

-- Sessions, API tokens, device codes, and audit log are defined in migration 000009_auth.

-- Permissions
CREATE TABLE permissions (
    id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL REFERENCES users(id),
    resource_type TEXT NOT NULL CHECK(resource_type IN ('global', 'collection', 'document')),
    resource_id TEXT, -- NULL for global
    permission TEXT NOT NULL CHECK(permission IN ('read', 'write', 'admin')),
    granted_by TEXT REFERENCES users(id),
    created_at DATETIME NOT NULL
);
```

## Deliverables

1. [x] Authentication API documentation
2. [x] WebAuthn flow endpoints
3. [x] Role/scope permission documentation
4. [x] API token and device-flow documentation
5. [x] Browser login/account/device verification screens
6. [x] Security implementation checklist
7. [ ] Independent penetration test guide (production hardening)

## Risk Mitigation

| Risk | Mitigation |
|------|-----------|
| Passkey not supported on user's device | Password fallback always available |
| User loses all passkeys | Recovery email + backup codes |
| Permission system too complex | Start with simple roles, iterate |
| Session hijacking | Short expiry, rotation, revocation |

## Definition of Done

- [x] Core implementation acceptance criteria pass
- [x] Implementation security review completed
- [ ] Auth flow manually tested on Chrome, Firefox, Safari, Edge (production hardening)
- [ ] Mobile passkey tested (iOS, Android) (production hardening)
- [x] Rate limiting verified
- [x] Audit logs verified by service tests
