Files
StarPunk/docs/architecture/simplified-auth-architecture.md
T
PhilandClaude Opus 5.5 75946be7b2 maint: Dependency upgrades and High backlog items (v2.11.0)
- All dependencies to current releases (97 known vulnerabilities -> 0),
  Python 3.14, uv pinned, requirements-test.txt, lxml/dateutil pinned
- CSRF tokens on admin forms, logout and IndieAuth consent
- IndieAuth client and crosspost link-card fetches via safe_get
- FLASK_DEBUG/FLASK_ENV default off/production; image sets them
- Foreign keys enforced on pooled connections; migration 018 removes orphans
- Rate limits shared across processes (rate_limits, migration 019)
- datetime.utcnow() and sqlite3 default adapters replaced
- compose.yaml fixed; duplicate dev_auth.py and test.ini removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:09:52 -07:00

345 lines
16 KiB
Markdown

# Authentication and Authorization Architecture
Current as of v2.10.1. Decision record: [ADR-064](../decisions/ADR-064-oidc-admin-login-and-builtin-indieauth-server.md),
which supersedes the "no self-hosted IndieAuth" decisions
([ADR-050](../decisions/ADR-050-remove-custom-indieauth-server.md),
[ADR-056](../decisions/ADR-056-no-selfhosted-indieauth.md)) and the external
token verification of ADR-030 / ADR-036.
> The filename is historical: it described the v1.x "external provider only"
> design. Other documents link to it, so it is kept.
## Overview
StarPunk is a single-user site with two kinds of client and two auth
mechanisms:
| Who | Mechanism | Credential | Code |
|---|---|---|---|
| The site owner in a browser (admin UI, consent screen) | OpenID Connect login against an external provider (e.g. Pocket ID) | `starpunk_session` cookie, backed by a hashed row in `sessions` | `starpunk/auth.py`, `starpunk/routes/auth.py` |
| Micropub apps (Quill, Indigenous, ...) | StarPunk's own IndieAuth authorization server | Bearer access token, backed by a hashed row in `indieauth_tokens` | `starpunk/indieauth.py`, `starpunk/routes/indieauth.py` |
The two are chained: a Micropub app is approved on a consent screen that
requires an admin session, so every token ultimately rests on the OIDC
login. StarPunk stores no passwords.
```
Browser (owner) StarPunk OIDC provider
─────────────── ──────── ─────────────
POST /auth/login ─────────────▶ initiate_login() ── redirect ──▶ authorize (PKCE, nonce)
owner authenticates
GET /auth/callback?code&state ◀────────────────────── redirect ───┘
handle_callback(): code exchange, ID token checks,
sub == OIDC_ADMIN_SUB → create_session(ADMIN_ME)
◀── Set-Cookie: starpunk_session
Micropub app StarPunk
──────────── ────────
discovers indieauth-metadata / authorization_endpoint / token_endpoint
GET /auth/authorize?... ────────▶ validate request → (OIDC login if no session) → consent page
owner approves ─────────────────▶ POST /auth/authorize/approve → redirect: code, state, iss
POST /auth/token (code, verifier) ▶ access token (hash stored in indieauth_tokens)
POST /micropub, /micropub/media ─▶ verify_access_token() + scope check
```
## 1. Admin login (OIDC)
### Flow
1. `GET /auth/login` shows `templates/admin/login.html`, or redirects to the
dashboard if the session cookie is already valid.
2. `POST /auth/login` calls `auth.initiate_login(next)`:
- Fetches `{OIDC_ISSUER}/.well-known/openid-configuration` (cached for an
hour per process). The document's `issuer` must equal `OIDC_ISSUER`, and
it must name `authorization_endpoint`, `token_endpoint` and `jwks_uri`.
- Generates `state`, `nonce` and a PKCE `code_verifier`, and stores them in
`oidc_login_state` with the sanitized `next` URL (same site only) and a
10-minute expiry.
- Redirects to the provider with `response_type=code`, `scope=openid` and
`code_challenge_method=S256`.
3. `GET /auth/callback`:
- A provider `error` parameter, or a missing `code`/`state`, flashes an
error and returns to the login page.
- The `state` row is fetched and deleted in one step: it is single use and
must not have expired.
- If the provider sent `iss` (RFC 9207), it must match the issuer.
- The code is exchanged at the token endpoint along with the
`code_verifier`. StarPunk authenticates as a confidential client (HTTP
Basic, `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET`).
- The ID token is verified with PyJWT against the provider's JWKS. The
checks are: the signature (algorithms from the provider metadata, never
`none`), `iss`, `aud` equal to the client id, `exp`, required `iat` and
`sub`, a 60 s leeway, and a `nonce` equal to the stored one.
- `sub` must equal `OIDC_ADMIN_SUB` (constant-time comparison). Any other
account gets "Not authorized as admin".
- A session is created for `ADMIN_ME`, the owner's identity URL. It is also
the `me` of every issued token. The author h-card is refreshed from
`ADMIN_ME` on a best-effort basis that never blocks login (see
[ADR-061](../decisions/ADR-061-author-discovery.md)).
### Sessions
- `create_session(me)` makes a random 32-byte URL-safe token. Only its
SHA-256 hash is stored in `sessions`, with `me`, `expires_at`
(`SESSION_LIFETIME` days, default 30), the user agent and the IP. Expired
sessions and login states are cleaned up each time a session is created.
- Cookie `starpunk_session`: `HttpOnly`, `SameSite=Lax`, `Secure` when
`SITE_URL` is https, `max-age` equal to the session lifetime.
- `verify_session(token)` looks up the hash, checks expiry and updates
`last_used_at`.
- `@require_auth` protects `/admin/*`. Without a valid session it remembers
the URL and redirects to `/auth/login`. It sets `g.user` and `g.me`.
- A `before_request` hook also resolves the session on public pages that
carry the cookie, so the header can show "Admin" instead of "Log in".
- `POST /auth/logout` deletes the session row and the cookie.
### Configuration
Outside `DEV_MODE`, `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`,
`OIDC_ADMIN_SUB` and `ADMIN_ME` are required, and startup fails without them.
The provider must have `{SITE_URL}/auth/callback` registered as a redirect
URI.
### Development mode
With `DEV_MODE=true` (and `DEV_ADMIN_ME`), `/dev/login` creates a session
without OIDC. The blueprint is registered only in dev mode, and its
`before_request` guard returns 404 if `DEV_MODE` is off. Every page shows a
warning banner while it is on. Never enable it in production.
## 2. Built-in IndieAuth authorization server
StarPunk issues tokens for exactly one identity, `ADMIN_ME`. It implements
the authorization code flow of the current IndieAuth spec
(https://indieauth.spec.indieweb.org/), with PKCE required.
### Endpoints
| Method | Path | Purpose |
|---|---|---|
| GET | `/.well-known/oauth-authorization-server` | Server metadata (the target of `rel=indieauth-metadata`) |
| GET | `/auth/authorize` | Validate the request; show the consent screen (admin session required) |
| POST | `/auth/authorize/approve` | Consent decision from the screen |
| POST | `/auth/authorize` | Profile-only code redemption, returns `{"me": ...}` |
| POST | `/auth/token` | Exchange a code for an access token; also legacy `action=revoke` |
| GET | `/auth/token` | Legacy token verification (Bearer token → `me`, `client_id`, `scope`) |
| POST | `/auth/revoke` | RFC 7009 revocation (always 200) |
All JSON responses carry `Cache-Control: no-store`. Errors use the OAuth
form `{"error", "error_description"}`.
### Metadata
```json
{
"issuer": "<SITE_URL>/",
"authorization_endpoint": "<SITE_URL>/auth/authorize",
"token_endpoint": "<SITE_URL>/auth/token",
"revocation_endpoint": "<SITE_URL>/auth/revoke",
"revocation_endpoint_auth_methods_supported": ["none"],
"scopes_supported": ["create", "update", "delete", "media", "profile"],
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code"],
"code_challenge_methods_supported": ["S256"],
"authorization_response_iss_parameter_supported": true
}
```
StarPunk has no introspection or userinfo endpoint. Only StarPunk itself
checks its tokens.
### Authorization request validation (`validate_authorization_request`)
- `client_id` must be an http(s) URL without a fragment.
- `redirect_uri` must be present and have no fragment. It must either share
the `client_id`'s scheme, host and port, or be published by the client. To
check the second case, StarPunk fetches the `client_id` URL (5 s timeout,
with an SSRF check on the URL unless `DEV_MODE` is on). It reads
`redirect_uris` from a JSON client metadata document, or
`rel="redirect_uri"` from the `Link` header and from `<link>`/`<a>`
elements.
- Problems with `client_id` or `redirect_uri` are shown to the user on an
error page (HTTP 400). They are never redirected, because the redirect
target can't be trusted.
- Other problems are redirected to the client with `error`,
`error_description`, `state` and `iss`. These are: a `response_type` other
than `code` (`unsupported_response_type`), a missing `state`, a missing
`code_challenge`, or a `code_challenge_method` other than `S256`.
- `scope` is split on spaces. Requested scopes are not filtered against
`scopes_supported`.
### Consent screen
If `GET /auth/authorize` gets a valid request but there is no admin session,
StarPunk stores the request URL and redirects to the OIDC login, which
returns to that URL afterwards. With a session, it renders
`templates/admin/authorize.html`. The page shows the client id, the identity
the client will act as, the redirect URI, and one checkbox per requested
scope (all checked). A request without scopes is described as "only wants to
confirm your identity".
`POST /auth/authorize/approve` checks the session again and re-validates the
request from hidden form fields. "Deny" redirects with
`error=access_denied`. "Approve" grants only the scopes that were both
requested and left checked, issues a code, and redirects with `code`,
`state` and `iss`.
### Codes and tokens
| | Authorization code | Access token |
|---|---|---|
| Table | `indieauth_codes` | `indieauth_tokens` |
| Value | 32 random bytes, URL-safe | 32 random bytes, URL-safe |
| Stored as | SHA-256 hash | SHA-256 hash |
| Lifetime | 10 minutes | `INDIEAUTH_TOKEN_LIFETIME_DAYS` (default 90) |
| Bound to | `client_id`, `redirect_uri`, `scope`, `code_challenge` | `client_id`, `scope` |
`redeem_authorization_code` handles redemption for both `POST /auth/token`
and `POST /auth/authorize`:
1. `code` and `code_verifier` are required.
2. An atomic `UPDATE ... SET used_at = now WHERE code_hash = ? AND used_at IS
NULL AND expires_at > now` makes the code single-use, even across
gunicorn workers.
3. `client_id` and `redirect_uri` must match the code exactly.
4. `BASE64URL(SHA256(code_verifier))` must equal the stored challenge
(constant-time comparison).
The token endpoint accepts only `grant_type=authorization_code`. It refuses
a code issued with no scope (`invalid_grant`), because such codes are for
the profile-only flow at the authorization endpoint. The response is
`{access_token, token_type: "Bearer", scope, me, expires_in}`. There are no
refresh tokens: a client re-authorizes when its token expires.
Expired codes are deleted whenever a new code is issued.
### Verification and revocation
- `verify_access_token(token)` hashes the token and accepts it if it is
neither revoked nor expired, then updates `last_used_at`. It returns
`{me: ADMIN_ME, client_id, scope}`.
- `check_scope(required, scope)` matches whole words in the space-separated
scope string.
- Revocation sets `revoked_at`. It can happen by token value, through
`POST /auth/revoke` or the legacy `POST /auth/token` with `action=revoke`
(unknown tokens are ignored, per RFC 7009). It can also happen by id, from
the admin page.
- `/admin/tokens` ("Connected Apps") lists active tokens with their client,
scope, dates and last use. Each has a Revoke button.
### Scopes
| Scope | Allows |
|---|---|
| `create` | Micropub create (published or draft), media upload, `q=source`, `q=category` |
| `draft` | Micropub create, always saved as a draft (v2.9.0); `q=source`, `q=category` |
| `update` | Micropub update; `q=source`, `q=category` |
| `delete` | Micropub delete and undelete; `q=source`, `q=category` |
| `media` | Media endpoint uploads |
| `profile` | Nothing beyond identity (there is no profile or userinfo endpoint) |
`q=config` and `q=syndicate-to` work with any valid token.
## 3. Token use at the Micropub and media endpoints
`routes/micropub.py` handles `GET/POST /micropub` and
`POST /micropub/media`. The old `POST /media` path is kept for existing
clients.
### Extracting the token (`micropub.extract_bearer_token`)
- The token comes from `Authorization: Bearer <token>`, with the scheme
matched case-insensitively (RFC 7235).
- Or it comes from `access_token` in the form body (POST) or the query
string (GET).
- A token in both places gets **400 `invalid_request`** (RFC 6750 §2,
v2.9.0).
- No token gets **401 `unauthorized`**, "No access token provided".
- An unknown, expired or revoked token gets **401 `unauthorized`**,
"Invalid or expired access token".
Every 401 carries `WWW-Authenticate: Bearer realm="micropub"`. When a token
was sent but isn't valid, `error="invalid_token"` is added (RFC 6750 §3,
v2.9.0).
### Scope rules
| Operation | Required scope | Notes |
|---|---|---|
| create | `create` or `draft` | With only `draft`, the post is saved unpublished whatever `post-status` says |
| update | `update` | |
| delete / undelete | `delete` | |
| `q=source`, `q=category` | any of `create`, `update`, `delete`, `draft` | These show drafts and tags (v2.9.0) |
| `q=config`, `q=syndicate-to` | any valid token | |
| media upload | `media` or `create` | `create` is accepted for older clients |
A missing scope gets **403 `insufficient_scope`** (RFC 6750). The Micropub
Recommendation's error table lists 401 for this case. StarPunk keeps 403 on
purpose (see the [v2.9.0 review](../design/v2.9.0/2026-11-03-micropub-review.md),
"Kept as is").
Micropub request handling itself is described in
[indieweb-protocols.md](indieweb-protocols.md#micropub).
## 4. Discovery
`templates/base.html` puts these links on every page, whether or not
`WEBMENTION_ENABLED` is set (v2.8.0):
```html
<link rel="micropub" href="<SITE_URL>/micropub">
<link rel="indieauth-metadata" href="<SITE_URL>/.well-known/oauth-authorization-server">
<link rel="authorization_endpoint" href="<SITE_URL>/auth/authorize">
<link rel="token_endpoint" href="<SITE_URL>/auth/token">
<link rel="me" href="<author home>">
<link rel="author" href="<author home>">
```
Micropub clients start from the URL the user types, which is normally
`ADMIN_ME`. If `ADMIN_ME` is the StarPunk site itself, the links above are
enough. If it is another page, that page must advertise StarPunk's
`indieauth-metadata` (or `authorization_endpoint` and `token_endpoint`) and
`micropub` links. Otherwise clients won't find StarPunk
([ADR-064](../decisions/ADR-064-oidc-admin-login-and-builtin-indieauth-server.md) §3).
## 5. Data (migration 011)
| Table | Purpose | Key columns |
|---|---|---|
| `sessions` | Admin browser sessions | `session_token_hash`, `me`, `expires_at`, `last_used_at`, `user_agent`, `ip_address` |
| `oidc_login_state` | One pending OIDC login | `state` (PK), `nonce`, `code_verifier`, `next_url`, `expires_at` |
| `indieauth_codes` | Authorization codes | `code_hash`, `client_id`, `redirect_uri`, `scope`, `code_challenge`, `expires_at`, `used_at` |
| `indieauth_tokens` | Access tokens | `token_hash`, `client_id`, `scope`, `expires_at`, `last_used_at`, `revoked_at` |
The legacy v1 tables `auth_state`, `tokens` and `authorization_codes` are
not used (see the migration's header comment).
## 6. Security properties and known gaps
In place:
- No secrets at rest: session tokens, codes and access tokens are stored only
as SHA-256 hashes.
- OIDC: PKCE S256, a nonce, single-use expiring state, issuer checks (in the
metadata and the RFC 9207 `iss`), full ID-token validation, and a single
allowed `sub`.
- IndieAuth: PKCE S256 required, single-use 10-minute codes bound to the
client and redirect URI, `iss` in every authorization response, and
untrusted redirect URIs never followed.
- Post-login redirects are limited to this site.
CSRF (v2.11.0): admin form POSTs, `/auth/logout` and the consent form's
approve button need a `csrf_token` field (or `X-CSRF-Token` header) equal to
an HMAC-SHA256 of the `starpunk_session` cookie under `SECRET_KEY`; anything
else gets 400. The token changes with every login and needs no storage.
Endpoints apps call with bearer tokens are not affected. The client metadata
fetch uses `webmention_ssrf.safe_get` (every redirect hop checked, the
connection pinned, a 5-second limit).
Known gaps:
- `scopes_supported` leaves out `draft`, although Micropub honours it and
the consent screen grants it when requested. Unknown scopes are also shown
and granted as requested; they just have no effect.
- No token introspection endpoint and no refresh tokens.