feat(api): #286 — mount the whole /api surface at /api/v1
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 10s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m12s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 3m4s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m17s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m36s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped

Version every /api route to /api/v1 (251 controller routes + ~24 Location
headers + the scanner callback URL + the Startup request-log literal),
uniform across the machine API, auth, scanner and scripted-build surfaces.

Add ApiVersionRewriteMiddleware: a legacy unversioned /api/* request is
rewritten (NOT redirected) to /api/v1/* in-pipeline — method, body, auth
headers and query survive — carrying RFC 8594 Deprecation/Sunset headers,
so curl / the future MCP server / bookmarks keep working. An already-
versioned path passes through; a future /api/v2 is never forced to v1.

Standardize the route convention (leading-slash absolute route per method,
no class-[Route] — except the two Scanner/Scripted controllers whose ~all
actions share a parametrized {id} prefix), enforced by ApiRouteVersioningTests
(^/api/v\d+/ over the whole Controllers.Api surface; browser-nav
/auth/oidc/login is out of scope).

Regenerate v1.json (160 paths, all /api/v1)/endpoint-index/v1.d.ts; sweep 945
SPA request literals + the test mocks (regex + positional URL parsers). /api/v1
is additive-only after freeze; the legacy-rewrite shim sunsets in ~2 releases
(owner decision) with removal tracked as a Phase-3 follow-up.

Docs: decisions.md 2026-07-13, api-conventions §1/§9, rest-api/spa-conventions/
blazor-route-parity/e2e-local/domain-model.

fixes #286
refs #197

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-13 00:30:20 +02:00
co-authored by Claude Opus 4.8
parent 51b67dea06
commit ef2bd65c27
218 changed files with 2586 additions and 2285 deletions
+35 -23
View File
@@ -13,8 +13,18 @@ Controllers live in `ErsatzTV/Controllers/Api/*.cs`, one per domain (e.g. `Templ
`BlockController.cs`, `LogsController.cs`). Every action needs this attribute set:
- `[ApiController]` on the class.
- `[HttpGet/Post/Put/Delete("/api/...")]` on the action, with `Name = "..."` on at least the
- `[HttpGet/Post/Put/Delete("/api/v1/...")]` on the action, with `Name = "..."` on at least the
primary GET (used by the SPA's OpenAPI-generated client and by route-assertion tests).
**The route is versioned and absolute** (`/api/v1/...`, leading slash, full path on the method attribute —
no class-level `[Route]`). This is enforced: `ApiRouteVersioningTests` (sibling of `ApiControllerSecurityTests`)
reflects over every `[ApiController]` action in `Controllers.Api` and fails if an effective route doesn't match
`^/api/v\d+/`. The **only** controllers with a class-level `[Route]` are the two whose ~all actions share a
parametrized prefix — `ScannerController` (`[Route("/api/v1/scan/{scanId:guid}")]`) and
`ScriptedScheduleController` (`[Route("/api/v1/scripted/playout/build/{buildId:guid}")]`) — and there the
method segments are relative (`[HttpPost("progress")]`). A browser-nav endpoint deliberately outside `/api`
(`AuthController`'s `GET /auth/oidc/login`) is out of scope for the versioning rule. See `docs/decisions.md`
2026-07-13 (#286) for the versioning contract (additive-only after freeze; the legacy `/api/*`→`/api/v1/*`
in-pipeline rewrite in `ApiVersionRewriteMiddleware`).
- `[Tags("Domain")]` — groups the endpoint in Swagger UI / the SPA's generated client namespace.
- `[EndpointSummary("...")]` — one-line description; optionally `[EndpointDescription("...")]` for
more detail.
@@ -84,7 +94,7 @@ Exemplars:
- **Optional enum filter via query param**: to filter a list endpoint by an enum, add a nullable
enum parameter to the query record (default `null`) and bind it with `[FromQuery] TEnum? name` on
the action; filter server-side only when it has a value. Exemplar: `?fillerKind=` on
`GET /api/filler-presets` (`GetAllFillerPresetsForApi(FillerKind? FillerKind = null)`). An invalid
`GET /api/v1/filler-presets` (`GetAllFillerPresetsForApi(FillerKind? FillerKind = null)`). An invalid
enum value is rejected by model binding (400) — no handler-side guard needed.
## 3. Error mapping
@@ -121,7 +131,7 @@ Established by issue #215 (`PlayoutController` + `ChannelController.ResetPlayout
`IsPlayoutLocked(id)` → `ConflictProblem("Playout build in progress", ...)`; add
`[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]` to each guarded
action. Precedent for the 409 shape: `TraktController` (its private `ConflictProblem()`). Two nuances:
- **Fire-and-forget bulk operations don't 409** — `POST /api/playouts/reset-all` stays 202; its
- **Fire-and-forget bulk operations don't 409** — `POST /api/v1/playouts/reset-all` stays 202; its
handler (`ResetAllPlayoutsHandler`) *skips* locked playouts, matching Blazor + the handler
semantics. Only per-id mutations 409. As of #235 the handler returns a `ResetAllPlayoutsResult`
(`QueuedPlayoutIds` / `SkippedLocked` / `SkippedUnsupported`) and the controller returns the 202
@@ -135,7 +145,7 @@ action. Precedent for the 409 shape: `TraktController` (its private `ConflictPro
maps it) so a client polling one playout has the same flag. The SPA reads it and, on a 409,
refreshes to pick up the flag.
- **Async-op success is 202, not 200** — an endpoint whose success path only *queues* a background
rebuild returns **202 Accepted**, not 200 (#235: `POST /api/channels/{id:int}/playout/reset`
rebuild returns **202 Accepted**, not 200 (#235: `POST /api/v1/channels/{id:int}/playout/reset`
resolves the channel's playout by the immutable channel **`Id`** (`GetPlayoutIdByChannelId`), guards
on `IsPlayoutLocked` → 409, queues a `BuildPlayout` → `AcceptedResult`, and 404s when the channel has
no playout). It is keyed on `{id:int}`, **not** `{channelNumber}` — the single-item Channel admin
@@ -169,19 +179,19 @@ operation itself, not a mutation racing it). Add `[ProducesResponseType]` for 20
after a successful `Lock*`, `Unlock*` in a `catch` and rethrow — one lock ⇄ exactly one release.
A second exemplar (issue #235 slice B), where the lock lives on the **controller** rather than in a
handler: `POST /api/media-sources/{plex|jellyfin|emby}/{id}/scan-collections?deep=` acquires the
handler: `POST /api/v1/media-sources/{plex|jellyfin|emby}/{id}/scan-collections?deep=` acquires the
per-source collections lock (`entityLocker.LockPlexCollections()` etc.) — the lock IS the running
collections scan, so a `false` = 409 — then `WriteAsync`es `Synchronize{X}Collections(id, ForceScan:
true, deep)` to the scanner channel and returns **202**. `ScannerService` releases that lock in a
`finally` when it processes the message; the controller compensating-unlocks in a `catch` if the
enqueue throws. `POST /api/libraries/{id}/scan?deep=` similarly threads an optional `[FromQuery] bool
enqueue throws. `POST /api/v1/libraries/{id}/scan?deep=` similarly threads an optional `[FromQuery] bool
deep` into `QueueLibraryScanByLibraryId(id, DeepScan)`.
**Status counterpart for a lock-backed async op.** A queue-triggering endpoint whose "is it running?"
state lives in a lock/registry should expose a **GET status surface** the SPA can poll to reconcile its
optimistic pending flag, rather than relying on a client-side timeout. Two exemplars:
`GET /api/libraries/scan-status` reads `IScannerProxyService.GetActiveScans()` (per-library, with
percent); `GET /api/media-sources/collections-scan-status` (#271) reads
`GET /api/v1/libraries/scan-status` reads `IScannerProxyService.GetActiveScans()` (per-library, with
percent); `GET /api/v1/media-sources/collections-scan-status` (#271) reads
`IEntityLocker.Are{X}CollectionsLocked()` and returns one `{family}` entry per **family-global**
collections lock that's held (no id, no percent — the lock granularity dictates the DTO shape). Return
only the *active* entries (empty list = nothing running), mirroring the queue op's own lock.
@@ -205,7 +215,7 @@ handler's validation when a lookup fails, so the controller-side mapping falls o
### 3c. A durable-save PUT that also triggers a background sync as a side effect
Some PUT-replace endpoints (issue #202: `PUT /api/media-sources/{plex|jellyfin|emby}/{id}/libraries`)
Some PUT-replace endpoints (issue #202: `PUT /api/v1/media-sources/{plex|jellyfin|emby}/{id}/libraries`)
have a synchronous durable write as their primary purpose — the response must reflect that write —
but Blazor's editor also fired off a background sync per newly-enabled library after the save. This
is a **different shape from §3b**: §3b is for an endpoint whose entire job *is* starting a
@@ -254,7 +264,7 @@ the domain/VM directly and root the path yourself, following the PR #181 pattern
The uploaded-artwork surfaces (channel logo, watermark) must never trust a client-declared content
type — doing so was a stored-XSS chain (upload `<script>` as `image/png`, serve it back as
`text/html`). The contract:
- **Upload**: `POST /api/artwork/uploads` derives the content type from the actual bytes via
- **Upload**: `POST /api/v1/artwork/uploads` derives the content type from the actual bytes via
`ErsatzTV.Core/Images/ImageContentTypes.DetectContentType` (SkiaSharp header sniff — no full
decode), rejecting non-images 422. That helper (`Accepted` set + `IsAccepted`) is the **single
source of truth** for which image types are allowed — reuse it, don't re-list content types.
@@ -376,8 +386,8 @@ GET handlers that feed an ordered list must also `.OrderBy(i => i.Index)` — id
The replace-all aggregate PUTs (blocks, templates, schedules items, playlists, collections, playouts,
etc.) carry an **optimistic-concurrency contract** so a stale second tab can't silently overwrite a
fresher edit (issue #253). The Block endpoints are the reference implementation; **PR2 fanned the same
recipe onto Template, DecoTemplate, Playlist, and schedule-items** (`PUT /api/templates/{id}`,
`/api/deco-templates/{id}`, `/api/playlists/{id}`, `/api/schedules/{id}/items`); PR3 covers the
recipe onto Template, DecoTemplate, Playlist, and schedule-items** (`PUT /api/v1/templates/{id}`,
`/api/v1/deco-templates/{id}`, `/api/v1/playlists/{id}`, `/api/v1/schedules/{id}/items`); PR3 covers the
Diff/Scalar aggregates (Collection, Playout ×2, MultiCollection, RerunCollection) and PR4 is the Phase-2
428 flip.
@@ -397,7 +407,7 @@ from the ETag response header (`client.ts` `requestWithMeta`). Every replace PUT
(`AddAggregateVersions`) adds the column (`nullable: false, defaultValue: 0`). Do **not** overload the
existing `DateUpdated` — a plain `int` is portable across SQLite/MySQL and decoupled from UI cosmetics.
**Transport.** The aggregate's GET (the one the editor loads from — e.g. `GET /api/blocks/{id}/items`)
**Transport.** The aggregate's GET (the one the editor loads from — e.g. `GET /api/v1/blocks/{id}/items`)
emits a strong `ETag: "3"` of `Version`; the PUT sends it back as `If-Match: "3"`. Mismatch → **412
Precondition Failed** (distinct from the §3a **409** "build in progress" lock guard). A successful PUT
returns the **new** ETag (post-increment) so a same-tab second save doesn't 412 against its own write.
@@ -544,7 +554,7 @@ That is correct only when a child row is pure config: reordering merely re-numbe
rows. **Schedule items are the exception** (issue #259): a schedule item anchors persisted runtime state —
`PlayoutScheduleItemFillGroupIndex` (fill-group / shuffle enumerator progression) FKs the item row with
`OnDelete(Cascade)`. Reconciling those by position makes a **moved** item inherit the state of whatever item
previously occupied its new slot. So `PUT /api/schedules/{id}/items` carries a stable child identity:
previously occupied its new slot. So `PUT /api/v1/schedules/{id}/items` carries a stable child identity:
- `ScheduleItemRequest.Id` (`int?`) round-trips each existing item's server id (as returned by the items GET).
**null / absent / 0 ⇒ a new item** (the controller normalizes `0`→null so the handler contract is
@@ -571,7 +581,7 @@ later without breaking anything (the field stays optional).
## 8. Known API warts (don't "fix" without discussion — they're deliberate synthesized rows)
`GET /api/blocks` and `GET /api/templates` (via `GetAllBlocksHandler` / `GetAllTemplatesHandler` in
`GET /api/v1/blocks` and `GET /api/v1/templates` (via `GetAllBlocksHandler` / `GetAllTemplatesHandler` in
`ErsatzTV.Application/Scheduling/Queries/`) synthesize a fake **negative-id "(none)" group row**
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"
@@ -607,12 +617,12 @@ OpenAPI generation, so the spec can't drift). When you add an endpoint:
(renamed from `[RequiresApiKey]`) so they stay gated even if an operator sets `Api:RequireKeyForReads=false`.
A valid session satisfies this tier just as the key does. Current tier: `Troubleshoot`/`Logs`/`Settings`/
`Maintenance`. `ApiControllerSecurityTests` asserts this reflectively.
- **Internal loopback callbacks** (the scanner's `/api/scan/*`) and the **`/api/auth/*` surface itself** use
- **Internal loopback callbacks** (the scanner's `/api/v1/scan/*`) and the **`/api/v1/auth/*` surface itself** use
`[SkipApiAuthorization]` (renamed from `[SkipApiKeyAuthorization]`). The scanner adds `[LocalhostOnly]`; the
auth surface must be reachable before a caller is authenticated, and its one sensitive action
(`POST /api/auth/password`) self-checks the principal. `ApiControllerSecurityTests` asserts these two are the
(`POST /api/v1/auth/password`) self-checks the principal. `ApiControllerSecurityTests` asserts these two are the
**only** auth-exempt controllers.
- **The `/api/auth/*` surface** (`AuthController`, `[ApiExplorerSettings(IgnoreApi = true)]` → excluded from the
- **The `/api/v1/auth/*` surface** (`AuthController`, `[ApiExplorerSettings(IgnoreApi = true)]` → excluded from the
OpenAPI doc, whose audience is machine clients): `GET config` (what auth options exist + `setupRequired`),
`GET session`, `POST setup` (first-run claim), `POST login`, `POST logout`, `POST password`, `GET machine-key`
(returns the server machine key to an authenticated session — the SPA's machine-key-management screen). The browser-nav
@@ -638,16 +648,16 @@ OpenAPI generation, so the spec can't drift). When you add an endpoint:
`Secure` behind TLS.
- **Never add a side-effecting GET/HEAD under `/api`.** The filter's CSRF check only covers mutating verbs, so
a side-effecting GET is a CSRF vector the moment a session cookie is a normal credential (a `SameSite=Lax`
cookie rides a cross-site top-level GET navigation). The former `GET /api/troubleshoot/playback.m3u8` (started
cookie rides a cross-site top-level GET navigation). The former `GET /api/v1/troubleshoot/playback.m3u8` (started
an FFmpeg workload) and the archive/sample GETs were **POST-ified for #301** (PR2): `POST
/api/troubleshoot/playback/start` (returns `{ url }` pointing at the open `/iptv` manifest), `POST
/api/troubleshoot/playback/archive`, `POST /api/troubleshoot/playback/sample/{mediaItemId}` — so the standard
/api/v1/troubleshoot/playback/start` (returns `{ url }` pointing at the open `/iptv` manifest), `POST
/api/v1/troubleshoot/playback/archive`, `POST /api/v1/troubleshoot/playback/sample/{mediaItemId}` — so the standard
session-mutation CSRF gate covers them with no new filter machinery (removing HEAD also fixed a latent
`DeleteOnClose`-on-HEAD artifact-destruction bug). Any new endpoint that *does* something must be a mutating
verb; a GET must be a pure read.
- **The SPA cutover shipped in PR2 (#295 + #301).** The browser now authenticates with the session cookie only —
it no longer sends `X-Api-Key`; the machine key is external/MCP-only, surfaced read-only by the machine-key
screen (`GET /api/auth/machine-key`). See `spa-conventions.md §5e` for the SPA seams (boot gate, central
screen (`GET /api/v1/auth/machine-key`). See `spa-conventions.md §5e` for the SPA seams (boot gate, central
`X-Csrf` on mutations, fetch-blob downloads).
**The OpenAPI "v1" document declares the machine posture by construction (#287).** An `ApiKey` security
@@ -667,4 +677,6 @@ a generated client method (a base id unique across the document stays unsuffixed
never touched). `ValidationProblemOperationTransformer` documents the
`400 ValidationProblemDetails` a model-binding/FluentValidation failure actually returns for any
body/param-binding operation. All four are registered in `Startup.cs` on "v1" only, mirroring
`NewtonsoftSchemaNamingTransformer`. `/api/v1` route versioning remains #286.
`NewtonsoftSchemaNamingTransformer`. **Route versioning shipped in #286**: the whole surface is mounted at
`/api/v1` (see §1 and `docs/decisions.md` 2026-07-13) — the OpenAPI document's `paths` are all `/api/v1/…`, and a
legacy unversioned `/api/*` caller is rewritten in-pipeline by `ApiVersionRewriteMiddleware`.