From 20d074e7e4770d42bf1d68e2b687a0358eaf5677 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 12 Jul 2026 00:08:05 +0200 Subject: [PATCH] =?UTF-8?q?docs(#197):=20api-conventions=20=C2=A79=20auth?= =?UTF-8?q?=20posture=20+=20decisions.md=20Bundle=20A=20entry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 4.8 (1M context) --- docs/api-conventions.md | 31 ++++++++++++++++++++++++++++ docs/decisions.md | 45 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/docs/api-conventions.md b/docs/api-conventions.md index fb0543a37..eefbe63f7 100644 --- a/docs/api-conventions.md +++ b/docs/api-conventions.md @@ -281,6 +281,11 @@ single-leading-cap names (`fFmpegPath`, `fFprobePath`, `zIndex`, `rFrameRate`) a explicit `[SkipApiKeyAuthorizationAttribute]` exemption; only `ScannerController` is exempt today). A minimum-count guard asserts the scan found a sane number of controllers, so a namespace rename can't silently make the scan match nothing and give this test a false pass. + It also asserts the **sensitive-read tier** (`Troubleshoot`/`Logs`/`Settings`/`Maintenance`) + carries `[RequiresApiKey]` and that `ScannerController` carries `[LocalhostOnly]` — reflectively, + so the tier can't silently drop a gate. `ApiKeyAuthorizationFilterTests.cs` unit-tests the filter + itself: writes are always fail-closed, reads are gated when `Api:RequireKeyForReads` (default true) + or `[RequiresApiKey]`, `OPTIONS` preflight and non-`/api` paths are exempt. - **Handler tests** (business logic behind the controller) use the shared in-memory SQLite fixture: `ErsatzTV.Tests/Support/InMemoryTvContext.cs`. Pattern: `SqliteConnection("Data Source=:memory:;Foreign Keys=False")` kept open for the fixture's lifetime, `EnsureCreatedAsync()` (not full migration @@ -464,3 +469,29 @@ for items that have no group, so the SPA can render an "ungrouped" bucket (`Id = unusedGroup.Id * -1`, `Name = "(none)"`). See issue #172. If you add a similar "ungrouped" concept elsewhere, this is the established pattern to follow — but be aware it means `Id` is not a reliable real-entity id for those synthetic rows. + +## 9. Authentication — API key posture (fail-closed) + +The whole `/api` surface is gated by the `X-Api-Key` header via the global `ApiKeyAuthorizationFilter` +(issue #197 Bundle A). When you add an endpoint: + +- **Do nothing** for the common case. Writes (POST/PUT/PATCH/DELETE) always require the key + (fail-closed — there is no "open" mode). Reads (GET/HEAD) require the key when + `Api:RequireKeyForReads` is enabled, which is the **default** (`true`). `OPTIONS` preflight is exempt. +- The effective key comes from `IApiKeyProvider` (`ErsatzTV/Services/ApiKeyProvider.cs`): `Api:WriteKey` + if configured, else a key persisted at `FileSystemLayout.ApiKeyPath` (`/config/api.key`, `0600`), else + a freshly generated 256-bit key. It is never empty. +- **Sensitive-read GETs** that disclose secrets/paths or trigger work must carry `[RequiresApiKey]` so + they stay gated even if an operator sets `Api:RequireKeyForReads=false`. Current tier: + `Troubleshoot`/`Logs`/`Settings`/`Maintenance`. `ApiControllerSecurityTests` asserts this reflectively. +- **Internal loopback callbacks** (the scanner's `/api/scan/*`) use `[SkipApiKeyAuthorization]` + + `[LocalhostOnly]` — the API key is a poor fit for a co-located child process, so the gate is the + loopback check (sound only because `ForwardedHeaders` trust is restricted via + `ForwardedHeaders:KnownProxies`/`KnownNetworks`). +- **CORS** is opt-in: no cross-origin access by default (the SPA is same-origin from `/app`); set + `Api:CorsAllowedOrigins` (semicolon-separated exact origins) to allow specific browser origins — the + policy already permits `X-Api-Key`/`If-Match` and exposes `ETag`. +- The SPA sends the stored key (`ctv-api-key`) on **every** request; users enter it on the keyless + **API Key** screen (`web/src/screens/ApiKeyScreen.tsx`, route `/app/api-key`). See spa-conventions §5e. + +The declarative OpenAPI security scheme + global 401 documentation are Phase-2 (#286/#287), not this tier. diff --git a/docs/decisions.md b/docs/decisions.md index 34c42326e..b3d6d478c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -941,3 +941,48 @@ fail-closed/CORS/versioning posture work tracked in #280–#289. The larger #197 posture (fail-closed writes, sensitive-read auth tier, CORS lockdown, `/api/v1` versioning, the OpenAPI security scheme) is decomposed into #280–#289 with the phased roadmap on #197; those PRs will append their own decisions here as they land. + +## 2026-07-12 — Fail-closed API auth + sensitive-read tier + CORS/ForwardedHeaders lockdown (#197 Bundle A, PR #PRNUM) + +Phase-1 of the #197 remediation — the auth posture that must land before any remote exposure. +Owner decisions (confirmed this session): **single API key** (no read/write split), and +**`Api:RequireKeyForReads` defaults `true`** (the whole `/api` surface requires the key). This does +**not** affect Jellyfin/streaming: `/iptv/*` (playlist/guide/streams/logos) and `/artwork/*` are outside +the filter's `/api` scope and keep their own optional access-token; only the management API the SPA talks +to is gated. + +- **Fail-closed writes (#280, S1).** The empty-key "open" branch is deleted; there is no open mode. New + `IApiKeyProvider` (`ErsatzTV/Services/ApiKeyProvider.cs`, singleton, resolved once at startup) yields a + never-empty key: `Api:WriteKey` if set, else a key persisted at `FileSystemLayout.ApiKeyPath` + (`/config/api.key`, `0600`, path logged not value), else a generated 256-bit hex key. Every mutating + `/api` request now requires `X-Api-Key`. +- **Sensitive-read tier (#282, S3/S5).** Reads are gated by `Api:RequireKeyForReads` (default true) OR a + new `[RequiresApiKey]` marker (mirror of `[SkipApiKeyAuthorization]`) applied to + `Troubleshoot`/`Logs`/`Settings`/`Maintenance`, so that tier stays gated even if an operator opts reads + open. `OPTIONS` preflight is exempt (CORS middleware owns it). `ApiControllerSecurityTests` asserts the + tier reflectively. +- **Delete dead non-`/api` mutation surfaces (#281, S2).** `SortController` + (`POST media/collections/{id}/items`, dead Blazor SortableJS residue — the SPA uses + `PUT /api/collections/{id}/custom-order`) and `AccountController` (`POST account/logout`, dead OIDC) + bypassed the key because they sat outside `/api`. Removed rather than guarded. +- **CORS opt-in (#284, S6).** `AllowAnyOrigin/Method/Header` is replaced by the `ApiCors` policy: an + exact-origin allowlist from `Api:CorsAllowedOrigins` (semicolon list) that permits `X-Api-Key`/`If-Match` + and exposes `ETag`; with no origins configured there is no cross-origin access (the SPA is same-origin). +- **ForwardedHeaders trust + scanner loopback (#285, S7/S10).** `GET /api/maintenance/gc` → `POST` + (crawler-triggerable GC; spec regenerated). `ForwardedHeaders` trust is configurable via + `ForwardedHeaders:KnownProxies`/`KnownNetworks` — **unconfigured preserves the current trust-all + behavior but logs a warning** (flipping the default to loopback-only would break reverse-proxy scheme/host + detection and thus M3U/XMLTV absolute URLs — the operator must name their proxy network). `ScannerController` + gains `[LocalhostOnly]` (the scanner always calls back over `http://localhost:{UiPort}/api/scan/...`), which + is only spoof-resistant once ForwardedHeaders trust is restricted — the two interlock. `search/all-items` + DoS-paging is **deferred** (it feeds the SPA "add all" flow and needs coordinated pagination; the unauth + exposure is already closed by read-gating). +- **SPA (`web/`).** The client sends the stored key (`ctv-api-key`) on **every** method (not just + mutations); a new keyless **API Key** screen (`/app/api-key`) lets the user paste the generated key, and a + shell-level banner points there on any 401. See spa-conventions §5e. **First-run/upgrade UX:** with reads + gated by default, the SPA shows no data until the key (from `/config/api.key`) is entered — an intended + consequence of the strict default. + +Phase-2 (contract freeze) — the declarative OpenAPI security scheme, global 401 docs, and `/api/v1` +versioning — remains #286/#287/#288. Phase-3 follow-ups: #265, #269, #172 remainder, `search/all-items` +paging, per-key rate limiting.