# Users, Roles, 2FA & SSO

> Human Admin Plane authentication, Argon2id passwords, rotating refresh token families, TOTP & WebAuthn/Passkeys MFA, OIDC SSO, Step-Up MFA, CSRF defenses, and the 5-role RBAC capability matrix.

The **Admin Plane** (`/admin-api/v1/*`) is exclusively for human operators. API keys (`ocms_...`) are unconditionally rejected on Admin routes, and human tokens/cookies are unconditionally rejected on Agent routes.

## What Is Never Exposed to Public or Agent APIs

A common security question is whether internal auth, user accounts, or infrastructure secrets can ever leak through your public Delivery API or AI Agent API. **They cannot:**

- **Users, password hashes, sessions, invitations, 2FA secrets, and OIDC config** exist strictly on the human Admin Plane (`/admin-api/v1/*`). There are zero routes for them on Delivery or Agent/MCP.
- **API keys, webhooks, audit logs, and organization settings** are strictly Admin-only. An AI agent key can never list, create, or revoke keys or read audit logs.
- **Server secrets** (`OVERTCMS_SECRET_KEY`, database DSN, S3/R2 secret access key, SMTP password, OIDC client secret, webhook signing secrets) never leave the backend process. Even the Admin runtime diagnostics route (`GET /admin-api/v1/system/runtime`) returns strictly non-secret metadata (e.g., bucket name and origin, never credentials).
- **Public auth bootstrap check**: `GET /admin-api/v1/auth/status` returns only three non-secret booleans (`setupRequired`, `oidcEnabled`, `smtpVerified`) so the Admin sign-in screen knows whether to show First-Time Setup or SSO.

## Password Hashing & Login Hardening

- **Initial bootstrap**: `POST /admin-api/v1/auth/setup` creates the first `owner` user when the organization has zero users, then permanently locks (`409 setup_already_completed`).
- **Minimum password length**: 8 characters.
- **Argon2id hashing**: Passwords and recovery codes are hashed with Argon2id (`m=19456`, `t=2`, `p=1`).
- **Timing-attack & enumeration defense**: Unknown-email logins and OIDC-only accounts without a password still run Argon2id against a dummy hash (`dummyArgon2Hash`), and disabled status is checked *only after* password verification succeeds.
- **Auth rate limiting**:
  - Per-IP auth endpoints (`/login`, `/mfa/verify`, `/webauthn/login/begin`, `/refresh`, `/oidc/login`): **30 requests/minute** (`adminAuthRateLimit`).
  - Per-email login lockout: **20 attempts per 5 minutes**.
  - Per-user MFA attempts: **10 attempts per 5 minutes**; per-challenge JTI: **5 attempts per 10 minutes**, single-use consumption on success.

---

## Sessions, Access JWTs & Refresh Token Rotation

Human authentication supports both **Bearer Access JWTs** and **`HttpOnly` cookies**:

| Cookie Name | Path | Attributes | Default Max-Age |
| :--- | :--- | :--- | :--- |
| `overtcms_access` | `/admin-api` | `HttpOnly`, `SameSite=Lax`, `Secure` (when `OVERTCMS_COOKIE_SECURE=true`) | `15m` (`OVERTCMS_ACCESS_TOKEN_TTL`) |
| `overtcms_refresh` | `/admin-api/v1/auth` | `HttpOnly`, `SameSite=Lax`, `Secure` | `720h` / 30d (`OVERTCMS_REFRESH_TOKEN_TTL`) |
| `overtcms_oidc_state` | `/admin-api/v1/auth/oidc` | `HttpOnly`, `SameSite=Lax`, `Secure` | `600s` (10m) |

### Refresh Token Family Reuse Detection

Every login creates a `UserSession` belonging to a `familyId`. Refreshing via `POST /admin-api/v1/auth/refresh` atomically marks the old session rotated and issues a new opaque refresh token in the same family.

```mermaid
sequenceDiagram
    participant Client
    participant Admin as Admin Plane
    participant DB as Session Store

    Client->>Admin: POST /admin-api/v1/auth/refresh (Token R1)
    Admin->>DB: Lookup SHA-256(R1)
    alt R1 already rotated (Replay Attack!)
        Admin->>DB: Revoke ENTIRE session family (familyId)
        Admin->>DB: Audit auth.session.compromised
        Admin-->>Client: 401 session_compromised
    else R1 active & unrotated
        Admin->>DB: Rotate R1 -> R2 (same familyId)
        Admin-->>Client: 200 OK (new Access JWT + R2)
    end
```

- Every Access JWT (`HS256`, signed with `OVERTCMS_SECRET_KEY`) is cross-checked against its live `UserSession` row—so revoking a session, logging out (which revokes the entire `familyId`), or disabling a user takes effect **immediately**, without waiting for JWT expiration.
- Auth responses always set `Cache-Control: no-store` and `Pragma: no-cache`.

### CSRF Origin Enforcement

All mutating Admin requests (`POST`, `PATCH`, `PUT`, `DELETE`) authenticated via cookies must pass `VerifyCSRFOriginWithOptions`:
1. Rejects `Sec-Fetch-Site: cross-site` with `403 csrf_cross_site`.
2. Requires a valid `Origin` header (`403 csrf_origin_missing` if absent).
3. Verifies exact canonical `scheme://host` equality against the request host (requiring `https://` when `OVERTCMS_COOKIE_SECURE=true`) or `OVERTCMS_WEBAUTHN_RP_ORIGIN` (the default `http://localhost:8080` is ignored on non-localhost hosts).

---

## Multi-Factor Authentication (TOTP, Recovery Codes & WebAuthn)

### Organization MFA Policies

Owners can enforce an organization-wide `mfaPolicy` via `PATCH /admin-api/v1/organization`:

| Policy Value | Enforcement |
| :--- | :--- |
| `optional` (default) | MFA is voluntary for all users. |
| `required_for_publishers_and_admins` | `owner`, `admin`, and `editor` roles are flagged with `mfaEnrollmentRequired: true` until they enroll TOTP or WebAuthn. |
| `required_for_all` | All 5 roles are required to enroll MFA. |

### TOTP (RFC 6238) & Single-Use Recovery Codes

- **Secret generation**: 160-bit random Base32 secret (`SHA1`, 6 digits, 30s period) encrypted at rest in `user_mfa` with **AES-256-GCM** derived from `OVERTCMS_SECRET_KEY`.
- **Replay prevention**: Validates with `±1` step clock skew (`30s`) and strictly rejects any time step `<= lastUsedStep`, preventing reuse of the same 6-digit code within its window.
- **Recovery codes**: Confirming TOTP enrollment returns **10** single-use recovery codes formatted `XXXX-XXXX-XXXX` once. Only Argon2id hashes are stored; consuming a code permanently removes it.

### WebAuthn / Passkeys (FIDO2 Level 2)

OvertCMS Core implements pure-Go **WebAuthn Level 2 ES256 (ECDSA P-256)** verification with zero external WebAuthn libraries:
- Generates 32-byte cryptographically random base64url challenges (`5m` TTL).
- Verifies `clientDataJSON` (`type`, constant-time `challenge`, exact `origin`, `crossOrigin: false`), `authenticatorData` (`sha256(rpId)`, `UP` flag, optional `UV` flag), and ASN.1 DER ECDSA-SHA256 signature.
- **Clone detection**: Whenever either stored or asserted `signCount > 0`, `newSignCount` must strictly advance (`> storedSignCount`), or verification fails with `401 webauthn_cloned_credential`.

### Step-Up MFA

For users with MFA enrolled, sensitive Admin operations require fresh second-factor verification within `OVERTCMS_STEP_UP_MFA_TTL` (default `15m`). Call `POST /admin-api/v1/auth/mfa/step-up` with a TOTP code, recovery code, or WebAuthn assertion to receive a refreshed Access JWT with an updated `mfaVerifiedAt` claim.

**Operations protected by Step-Up MFA:**
- Updating organization settings / `mfaPolicy` (`PATCH /admin-api/v1/organization`)
- Enrolling, disabling, or managing TOTP / WebAuthn credentials
- Updating user roles/status or revoking sessions
- Resuming paused agent writes (`POST /admin-api/v1/sites/{siteSlug}/agent-writes/resume` or `PATCH /admin-api/v1/sites/{siteSlug}`)
- Creating or revoking API keys (`POST` / `DELETE /admin-api/v1/sites/{siteSlug}/api-keys`)
- Deleting PostTypes (`DELETE /admin-api/v1/sites/{siteSlug}/post-types/{postTypeSlug}`)
- Creating, updating, or deleting Webhooks (`POST` / `PATCH` / `DELETE /admin-api/v1/sites/{siteSlug}/webhooks`)
- Applying a live site NDJSON import (`POST /admin-api/v1/sites/{siteSlug}/import?dryRun=false`)

---

## Pure-Go OIDC SSO (Authorization Code + PKCE S256)

Configure `OVERTCMS_OIDC_ISSUER`, `OVERTCMS_OIDC_CLIENT_ID`, `OVERTCMS_OIDC_REDIRECT_URL`, and optionally `OVERTCMS_OIDC_CLIENT_SECRET` to enable Single Sign-On:

- `GET /admin-api/v1/auth/oidc/login` discovers `/.well-known/openid-configuration` (cached `10m`), generates a random `state`, `nonce`, and **PKCE S256** `code_verifier`/`code_challenge`, binds `state` in the `HttpOnly` `overtcms_oidc_state` cookie, and returns `{ authUrl, state }`.
- `GET /admin-api/v1/auth/oidc/callback` verifies the CSRF `state` cookie in constant time, exchanges the authorization code with PKCE `code_verifier`, fetches and caches the provider's JWKS (`10m` TTL), verifies **RS256** (RSA `>= 2048`-bit modulus) or **ES256** (P-256) ID token signatures, and strictly checks `iss`, `aud`, `azp`, `exp`, `nbf`, `nonce`, and `sub`.
- All outbound OIDC discovery, token, and JWKS HTTP requests use an **SSRF-safe dialer** that refuses private/loopback IPs and HTTP redirects, and enforces HTTPS endpoints whenever the configured issuer is HTTPS.

---

## 5-Role RBAC Capability Matrix

Every human user has one built-in role (`owner`, `admin`, `editor`, `writer`, or `viewer`) plus an optional `allowedPostTypes` allowlist (empty or `["*"]` grants access to all PostTypes).

| Capability | `owner` | `admin` | `editor` | `writer` | `viewer` |
| :--- | :---: | :---: | :---: | :---: | :---: |
| `entry:read` | Yes | Yes | Yes | Yes | Yes |
| `entry:create` | Yes | Yes | Yes | Yes | — |
| `entry:edit_own` | Yes | Yes | Yes | Yes | — |
| `entry:edit_all` | Yes | Yes | Yes | — | — |
| `entry:publish` | Yes | Yes | Yes | — | — |
| `entry:delete` | Yes | Yes | Yes | — | — |
| `media:read` | Yes | Yes | Yes | Yes | Yes |
| `media:upload` | Yes | Yes | Yes | Yes | — |
| `media:delete` | Yes | Yes | Yes | — | — |
| `schema:read` | Yes | Yes | Yes | Yes | Yes |
| `schema:manage` | Yes | Yes | — | — | — |
| `api_key:manage` | Yes | Yes | — | — | — |
| `user:manage` | Yes | Yes | — | — | — |
| `audit:read` | Yes | Yes | — | — | — |
| `site:manage` | Yes | Yes | — | — | — |
| `org:manage` | Yes | — | — | — | — |

### Key RBAC Invariants

- **Writer ownership**: Users with `writer` (`entry:edit_own` without `entry:edit_all`) may only edit or restore entries where `entry.createdBy.id == user.id`; attempting to edit another author's entry returns `403 forbidden_not_owner`. Writers also cannot create/edit published or scheduled entries or modify `unpublishAt`.
- **Restricted post-type delegation**: An `admin` with a restricted `allowedPostTypes` list cannot invite users or assign roles with wildcard `*` or PostTypes outside their own allowlist.
- **Last-owner protection**: Demoting or disabling the last active `owner` in an organization is atomically blocked with `409 last_owner_protected`.
- **Team invitations**: `owner` and `admin` users invite team members with a 7-day single-use opaque invite token (`POST /admin-api/v1/invitations`), accepted at `POST /admin-api/v1/invitations/accept`. If [SMTP email](/self-hosting/email-and-smtp) is configured and verified, OvertCMS automatically emails a clickable invite link while still returning the one-time token for manual sharing.
