feat(api): short-lived signed media tokens for cast (spec 060 T001-T004) #1220

Merged
chris merged 3 commits from feature/060-cast-api into main 2026-10-14 17:33:15 +02:00
Owner

Summary

Backend lane of spec 060 (Android cast to Chromecast): short-lived signed media tokens so Google's Default Media Receiver can fetch media URLs itself — it cannot carry the phone's session cookie. This is a minimal slice of draft spec 035; all other clients stay on cookie auth, no DB migration, no new dependencies.

Token contract (for the Android team)

Mint

POST /api/media/token
Auth: existing session cookie (or API key with media:read scope)
Body: { "mediaItemId": "<uuid>", "rendition": "<name>" }
200:  { "token": "<opaque>", "expiresAt": <unix seconds> }
400:  unknown rendition or invalid body
401:  not authenticated
404:  media item not visible to the caller (no ID probing)

Allowed renditions: original, preview, thumbnail, video_rendition.
For the cast photo URL use rendition preview (the display/fullsize rendition — there is no separate display endpoint; it is GET /api/media/{id}/derived/preview), for video video_rendition (fallback original).

Use

GET /api/media/{mediaItemId}/original?st=<token>          (rendition "original")
GET /api/media/{mediaItemId}/derived/{derivedType}?st=<token>   (rendition = derivedType)
  • Token is bound to exactly one mediaItemId + rendition; any other item/rendition → 403.
  • Expired or tampered token → 403. Missing both cookie and st → 401.
  • Cookie auth is unchanged; either auth succeeding is enough (a valid cookie ignores a garbage st).
  • ?st= outside these two endpoints is ignored → normal auth flow (401 unauthenticated).
  • Stateless verification — no DB round trip; tokens cannot be revoked, they simply expire.

Token properties

  • Format: base64url("mediaItemId|rendition|exp") + "." + base64url(HMAC-SHA256(payload)), exp = unix seconds.
  • Key: derived from the existing MEMORIES_APP_SECRET (already required non-placeholder by setup readiness) with a context prefix — no new secret to provision.
  • TTL: memories.media-token.ttl (MEMORIES_MEDIA_TOKEN_TTL), default 15 min. Mint a fresh token per LOAD; TTL only bounds token leakage, not session length.
  • Leaked URL cannot access other media (per-item binding), but a leaked token lives until expiry — keep TTLs short.

Security model

  • MediaTokenAuthenticationFilter runs inside the security chain after session auth, so an already-authenticated request (cookie/bearer) is never touched; no permitAll added — /api/** stays deny-by-default.
  • Mint checks the caller may see the item with the same MediaAuthorizationSql predicate the byte endpoints use, so a token is a time-boxed capability minted only for visible items.
  • Token-authenticated serving skips the viewer-permission lookup (no user identity in the token by design); binding is re-checked in the controllers against path variables (defense in depth).

Tests

rtk ./gradlew :apps:api:test → BUILD SUCCESSFUL — 2024 tests, 0 failures, 0 errors (9 pre-existing skips).

  • MediaTokenServiceTest: mint payload format, verify round trip, tampered payload/signature, expiry, item/rendition binding, TTL configuration.
  • MediaTokenAccessTest (MockMvc against the real SecurityFilterChain): valid token 200 on original + derived, expired 403, garbage 403, token-for-A-on-B 403, rendition mismatch 403, missing both 401, cookie regression 200, cookie-wins-over-garbage-st 200, st ignored on non-allowlisted endpoints 401, mint contract 200/400/401/404.
  • Existing security-chain tests (SecurityConfigurationTest, StoragePathsAccessMatrixTest, FirstAdminRemovalContractTest) updated for the new filter bean; contract tests asserting no new permitAll still pass.
## Summary Backend lane of spec 060 (Android cast to Chromecast): short-lived signed media tokens so Google's Default Media Receiver can fetch media URLs itself — it cannot carry the phone's session cookie. This is a minimal slice of draft spec 035; **all other clients stay on cookie auth**, no DB migration, no new dependencies. ## Token contract (for the Android team) ### Mint ``` POST /api/media/token Auth: existing session cookie (or API key with media:read scope) Body: { "mediaItemId": "<uuid>", "rendition": "<name>" } 200: { "token": "<opaque>", "expiresAt": <unix seconds> } 400: unknown rendition or invalid body 401: not authenticated 404: media item not visible to the caller (no ID probing) ``` Allowed renditions: `original`, `preview`, `thumbnail`, `video_rendition`. For the cast photo URL use rendition `preview` (the display/fullsize rendition — there is no separate display endpoint; it is `GET /api/media/{id}/derived/preview`), for video `video_rendition` (fallback `original`). ### Use ``` GET /api/media/{mediaItemId}/original?st=<token> (rendition "original") GET /api/media/{mediaItemId}/derived/{derivedType}?st=<token> (rendition = derivedType) ``` - Token is bound to exactly **one mediaItemId + rendition**; any other item/rendition → **403**. - Expired or tampered token → **403**. Missing both cookie and `st` → **401**. - Cookie auth is unchanged; either auth succeeding is enough (a valid cookie ignores a garbage `st`). - `?st=` outside these two endpoints is ignored → normal auth flow (401 unauthenticated). - Stateless verification — no DB round trip; tokens cannot be revoked, they simply expire. ### Token properties - Format: `base64url("mediaItemId|rendition|exp") + "." + base64url(HMAC-SHA256(payload))`, `exp` = unix seconds. - Key: derived from the existing `MEMORIES_APP_SECRET` (already required non-placeholder by setup readiness) with a context prefix — no new secret to provision. - TTL: `memories.media-token.ttl` (`MEMORIES_MEDIA_TOKEN_TTL`), default **15 min**. Mint a fresh token per `LOAD`; TTL only bounds token leakage, not session length. - Leaked URL cannot access other media (per-item binding), but a leaked token lives until expiry — keep TTLs short. ## Security model - `MediaTokenAuthenticationFilter` runs inside the security chain **after** session auth, so an already-authenticated request (cookie/bearer) is never touched; no permitAll added — `/api/**` stays deny-by-default. - Mint checks the caller may see the item with the same `MediaAuthorizationSql` predicate the byte endpoints use, so a token is a time-boxed capability minted only for visible items. - Token-authenticated serving skips the viewer-permission lookup (no user identity in the token by design); binding is re-checked in the controllers against path variables (defense in depth). ## Tests `rtk ./gradlew :apps:api:test` → **BUILD SUCCESSFUL — 2024 tests, 0 failures, 0 errors** (9 pre-existing skips). - `MediaTokenServiceTest`: mint payload format, verify round trip, tampered payload/signature, expiry, item/rendition binding, TTL configuration. - `MediaTokenAccessTest` (MockMvc against the real `SecurityFilterChain`): valid token 200 on original + derived, expired 403, garbage 403, token-for-A-on-B 403, rendition mismatch 403, missing both 401, cookie regression 200, cookie-wins-over-garbage-st 200, `st` ignored on non-allowlisted endpoints 401, mint contract 200/400/401/404. - Existing security-chain tests (`SecurityConfigurationTest`, `StoragePathsAccessMatrixTest`, `FirstAdminRemovalContractTest`) updated for the new filter bean; contract tests asserting no new `permitAll` still pass.
Chromecast's Default Receiver fetches media URLs itself and cannot carry
the phone's session cookie. Minimal slice of draft spec 035:

- MediaTokenService: HMAC-SHA256 over base64url("mediaItemId|rendition|exp")
  keyed from memories.app-secret (context-prefixed), stateless verification,
  default TTL 15 min (memories.media-token.ttl / MEMORIES_MEDIA_TOKEN_TTL).
- POST /api/media/token mints a token for one item + rendition; requires
  media:read and only mints for items the caller may see (404 otherwise).
- GET /api/media/{id}/original and GET /api/media/{id}/derived/{type} accept
  ?st=<token> as an ALTERNATIVE auth via MediaTokenAuthenticationFilter,
  registered after session auth so a valid cookie always wins. Invalid or
  expired tokens on those paths are answered 403; every other endpoint keeps
  its existing auth behavior (st is ignored outside the two paths).

Cookie/API-key auth paths are unchanged; the viewer-permission predicate is
skipped only for token-authenticated reads (the token is a time-boxed
capability for exactly one item + rendition).
test(api): media token unit + MockMvc security-chain tests (spec 060 T004)
All checks were successful
Wiki Sync / Sync wiki from docs (push) Has been skipped
Build and Deploy / Detect changed services and test scopes (push) Successful in 2s
Build and Deploy / Smoke API and media worker (push) Has been skipped
Build and Deploy / Smoke web (push) Has been skipped
Build and Deploy / Smoke ML worker (push) Has been skipped
Build and Deploy / Smoke people worker (push) Has been skipped
Build and Deploy / Build postgres image (push) Has been skipped
Build and Deploy / Build Android CI image (push) Has been skipped
Build and Deploy / Build plants worker image (push) Has been skipped
Build and Deploy / Build converter worker image (push) Has been skipped
Build and Deploy / Android unit tests and debug APK (push) Has been skipped
Build and Deploy / Deploy postgres (push) Has been skipped
Build and Deploy / Build API image (push) Has been skipped
Build and Deploy / Build media worker image (push) Has been skipped
Build and Deploy / Build ML worker image (push) Has been skipped
Build and Deploy / Build people worker image (push) Has been skipped
Build and Deploy / Build web image (push) Has been skipped
Build and Deploy / Deploy API (push) Has been skipped
Build and Deploy / Deploy web (push) Has been skipped
Build and Deploy / Deploy media worker (push) Has been skipped
Build and Deploy / Deploy ML worker (push) Has been skipped
Build and Deploy / Deploy plants worker (push) Has been skipped
Build and Deploy / Deploy people worker (push) Has been skipped
Build and Deploy / Deploy converter worker (push) Has been skipped
Build and Deploy / Clean Docker build artifacts (push) Has been skipped
Build and Deploy / Run scoped PR tests (push) Successful in 3m19s
ccaabec417
- MediaTokenServiceTest: mint payload format, verify round trip, tampered
  payload/signature rejection, expiry, item/rendition binding, properties TTL.
- MediaTokenAccessTest: valid token 200 (original + derived), expired/garbage
  403, token-for-A-on-B 403, rendition mismatch 403, missing both 401,
  cookie-auth regression for both byte endpoints, cookie wins over garbage st,
  st ignored on non-allowlisted endpoints, mint contract (200/400/401/404).
- media-token-test-schema.sql: H2 schema for the endpoints + auth predicate.
fix(api): suppress servlet auto-registration of media token filter + bearer mint tests (spec 060 review)
All checks were successful
Wiki Sync / Sync wiki from docs (push) Has been skipped
Build and Deploy / Detect changed services and test scopes (push) Successful in 2s
Build and Deploy / Smoke API and media worker (push) Has been skipped
Build and Deploy / Smoke web (push) Has been skipped
Build and Deploy / Smoke ML worker (push) Has been skipped
Build and Deploy / Smoke people worker (push) Has been skipped
Build and Deploy / Build postgres image (push) Has been skipped
Build and Deploy / Build Android CI image (push) Has been skipped
Build and Deploy / Build plants worker image (push) Has been skipped
Build and Deploy / Build converter worker image (push) Has been skipped
Build and Deploy / Android unit tests and debug APK (push) Has been skipped
Build and Deploy / Deploy postgres (push) Has been skipped
Build and Deploy / Build API image (push) Has been skipped
Build and Deploy / Build media worker image (push) Has been skipped
Build and Deploy / Build ML worker image (push) Has been skipped
Build and Deploy / Build people worker image (push) Has been skipped
Build and Deploy / Build web image (push) Has been skipped
Build and Deploy / Deploy API (push) Has been skipped
Build and Deploy / Deploy web (push) Has been skipped
Build and Deploy / Deploy media worker (push) Has been skipped
Build and Deploy / Deploy ML worker (push) Has been skipped
Build and Deploy / Deploy plants worker (push) Has been skipped
Build and Deploy / Deploy people worker (push) Has been skipped
Build and Deploy / Deploy converter worker (push) Has been skipped
Build and Deploy / Clean Docker build artifacts (push) Has been skipped
Build and Deploy / Run scoped PR tests (push) Successful in 2m59s
742dc929fc
chris merged commit 01fbdd3335 into main 2026-10-14 17:33:15 +02:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
chris/memories!1220
No description provided.