Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@ proxy in development. **CORS is not needed at all.**

### H3 — `/proxy/*` has no path allowlist

> **Status: fixed (#308).** `/proxy/*` is now peer-only and forwards `GET` on a
> fixed read-only `/rest` endpoint allowlist; see `docs/authentication.md`
> ("Proxy auth"). The text below, and other mentions of `/proxy/*` in this
> assessment, describe the state at the assessment date.

`routes/proxy.ts` mounts `app.all("/*")` under `/proxy` and forwards
`request.url` minus the prefix **verbatim** to the internal Navidrome base URL,
injecting the bundled Navidrome **admin** credentials (`u+t+s`) into the query.
Expand Down
25 changes: 19 additions & 6 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Poutine has three authentication mechanisms, each scoped to a different API surf
| Admin | `/admin/*` | JWT (cookie + `Authorization: Bearer` header) |
| Subsonic (JSON) | `/rest/*` | Subsonic `u+p` (plaintext / `enc:<hex>`) **or** `u+t+s` (MD5 token+salt) |
| Subsonic (binary) | `/rest/stream`, `/rest/getCoverArt` | Same as Subsonic JSON, but errors use HTTP status codes, not Subsonic envelopes. `/rest/stream(.view)` also accepts a `castToken=` query param (#218) as an alternate auth for non-Subsonic clients (Sonos devices, DLNA renderers) — see "Cast tokens" below |
| Proxy | `/proxy/*` | Unified: Ed25519 (peers) → JWT (SPA) → Subsonic `u+p` / `u+t+s`, tried in order |
| Proxy | `/proxy/*` | Ed25519-signed peers **only** — no JWT, no Subsonic. `GET` on a read-only allowlist |
| Federation | `/federation/*` | Ed25519-signed HTTP (see [federation-api.md](federation-api.md)) |
| Invites | `/api/invites/*`| None — the token in the POST body is the credential (see "User invitations") |
| Health | `/api/health`, `/api/health/live`, `/api/health/ready` | None — orchestrators and Synthetic monitors carry no credentials. Keep internal identifiers and URLs out of these bodies (#277) |
Expand Down Expand Up @@ -195,13 +195,26 @@ Setting a different `POUTINE_OWNER_PASSWORD` in env never overwrites a non-empty

## Proxy auth (`/proxy/*`)

`/proxy/*` is a transparent authenticated proxy to the local Navidrome. Three auth modes tried in order by `hub/src/proxy/auth.ts`:
`/proxy/*` is the peer-facing, read-only window onto the local Navidrome: peer hubs read library metadata and cover art through it. Every forwarded request carries the Navidrome **admin** credentials, so the tier is deliberately narrow on both axes — who may call, and what they may call (#308).

1. **Ed25519** — all four `x-poutine-*` headers present → validated against the in-memory peer registry (DB-backed, sourced from the `instances` table since federation v5; see [federation-api.md](federation-api.md)). `request.proxyAuth.kind = "peer"`. Used by peer hubs during catalog sync and streaming.
2. **JWT** — `Authorization: Bearer`, `access_token` cookie, or `token` query param → verified with `verifyToken`. `request.proxyAuth.kind = "jwt"`. Used internally for any admin-tree proxy calls.
3. **Subsonic `u+p` or `u+t+s`** — same logic as `/rest/*`. `request.proxyAuth.kind = "subsonic"`.
**Who** — `hub/src/proxy/auth.ts`, peers only:

Returns `401` if all three fail. The forwarded request always uses fresh Navidrome `u+t+s` credentials — the incoming auth is consumed at the proxy tier and never forwarded.
- All four `x-poutine-*` signing headers required; missing any → `401`. Validated against the in-memory peer registry (DB-backed, sourced from the `instances` table since federation v5; see [federation-api.md](federation-api.md)). Sets `request.proxyAuth = { kind: "peer", peerId }`.
- **No local-user path.** A JWT (header, cookie, or `token=` query) or Subsonic `u+p` / `u+t+s` is not a credential here → `401`. Local users reach the library through `/rest/*`; nothing in the SPA calls `/proxy/*`.
- Then, in order: version floor (`Poutine-Api-Version` ≥ `MIN_FEDERATION_API_VERSION`, else `403`) and lifecycle gate (non-`active` peer → uniform `403 {"error":"forbidden"}`), both after signature verification. Same policy as `/federation/*` (`federation/peer-auth.ts`) — keep the two in step.
- Signed body hash is always `-`: the tier takes no bodies.

**What** — `hub/src/routes/proxy.ts`, checked in `onRequest` (before auth, before body parsing):

| Check | Rule | Refusal |
|--------|------------------------------------------------------------------------|---------|
| Method | `GET` only (no `HEAD`) | `405` |
| Path | `/proxy/rest/<endpoint>` or `/proxy/rest/<endpoint>.view`, allowlisted | `404` |
| Body | none — `content-length` > 0 or `transfer-encoding` present is refused | `400` |

Allowlist (`PROXY_ALLOWED_ENDPOINTS`) and the peer call site that needs each entry: [hub-internals.md#proxy](hub-internals.md#proxy). A refused request never produces a Navidrome request.

The forwarded request always uses fresh Navidrome `u+t+s` credentials — the incoming auth is consumed at the proxy tier and never forwarded.

## Cast tokens (`/rest/stream.view?castToken=…`)

Expand Down
2 changes: 2 additions & 0 deletions docs/federation-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ All errors return `{ "error": "<message>" }`. The `Poutine-Api-Version` header i

Library metadata and cover art travel through `/proxy/*`, which reuses the same Ed25519 signing scheme. See `docs/hub-internals.md` for the `/proxy/*` contract (Phase 1).

`/proxy/*` is peer-only and serves `GET /proxy/rest/<endpoint>[.view]` for `getArtists`, `getArtist`, `getAlbum`, `getScanStatus`, `getCoverArt` — nothing else (#308). Other method `405`, other path `404`, request body `400`. These are the only proxy calls any v5+ hub issues, so the restriction needed no protocol version bump; a new peer-side proxy call does need its endpoint added on the receiver first.

---

## Invitations & handshake (v5)
Expand Down
29 changes: 19 additions & 10 deletions docs/hub-internals.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Sonos and DLNA are not env-gated — toggles, volume cap, `lan_url`, friendly na
| Surface | Prefix | Auth | Purpose |
|------------|-------------------------------------------------------|------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Subsonic | `/rest/*` | Subsonic `u+p` or `u+t+s` (see [authentication.md](authentication.md)) | Primary client API: browse, stream, art — see [opensubsonic.md](opensubsonic.md) for compatibility |
| Proxy | `/proxy/*` | Ed25519, JWT, or Subsonic `u+p`/`u+t+s` (unified — see below) | Authenticated transparent proxy to Navidrome |
| Proxy | `/proxy/*` | Ed25519-signed peers only (see below) | Peer-only read-only proxy to Navidrome — `GET` on an endpoint allowlist |
| Federation | `/federation/*` | Ed25519-signed (see [federation-api.md](federation-api.md)) | Peer-to-peer only |
| Admin | `/admin/*`, `/api/admin/hub/*`, `/api/admin/player/*` | JWT (see [authentication.md](authentication.md)) | Three partitioned mounts (#226). `/admin/*` is auth-only (refresh cookie path). Hub/Player admin handlers live only at their matching namespace — cross-namespace requests 404. See [system-architecture.md](system-architecture.md#admin-namespaces). |
| Health | `/api/health` | None | `{ status, appVersion, apiVersion, gitSha, navidrome, navidromeStream, recentNavidromeFailures, library }` — always HTTP 200, see note below |
Expand Down Expand Up @@ -99,26 +99,35 @@ JWT signing secret auto-generates on first boot and lives in the `settings` tabl

## /proxy/*

Transparent authenticated proxy to the local Navidrome. Introduced in Phase 1 (issue #50).
Peer-only, read-only proxy to the local Navidrome. Introduced in Phase 1 (issue #50); narrowed to peers + an endpoint allowlist in #308.

**Auth** — unified preHandler in `hub/src/proxy/auth.ts`, tried in order:
**Auth** — preHandler in `hub/src/proxy/auth.ts`: Ed25519-signed peer requests only. All four `x-poutine-*` headers → peer registry lookup → timestamp skew → signature → version floor → lifecycle gate. No JWT, no Subsonic credentials. `401` / `403` per [authentication.md](authentication.md#proxy-auth-proxy).

1. **Ed25519** — all four `x-poutine-*` headers present → validated against the in-memory peer registry (DB-backed, sourced from `instances`). `request.proxyAuth.kind = "peer"`.
2. **JWT** — `Authorization: Bearer`, `access_token` cookie, or `token` query param → verified with `verifyToken`. `request.proxyAuth.kind = "jwt"`.
3. **Subsonic u+p / u+t+s** — `u` + `p` (plaintext or `enc:<hex>`) **or** `u` + `t` + `s` (MD5 token+salt). Verified by AES-decrypting `users.password_enc` and either constant-time comparing the plaintext or recomputing `md5(plaintext + salt)`. `request.proxyAuth.kind = "subsonic"`.
**Surface** — `onRequest` hook in `hub/src/routes/proxy.ts`, ahead of auth and body parsing. Only `GET /proxy/rest/<endpoint>[.view]` for `PROXY_ALLOWED_ENDPOINTS`:

Returns `401` if all three methods fail.
| Endpoint | Peer call site |
|-----------------|------------------------------------------------------------|
| `getArtists` | library sync — `library/sync-instance.ts` (`sync-peer.ts`) |
| `getArtist` | library sync |
| `getAlbum` | library sync |
| `getScanStatus` | auto-sync peer poll — `services/auto-sync.ts` |
| `getCoverArt` | peer cover art — `routes/subsonic/stream.ts` |

- Same five at every supported federation version (v5 floor → current). Peer audio is `/federation/stream/:id`; local sync talks to Navidrome directly. Neither uses the proxy.
- Other method → `405` (`Allow: GET`). Other path → `404`. Declared body → `400`. None reaches Navidrome.
- Path match is exact and undecoded — no normalisation, so encoded or dotted variants miss. Upstream path is rebuilt as `/rest/<endpoint>` from the matched entry; caller path text is never copied into the Navidrome URL.
- Adding an entry: must be a read, must have a peer call site, and `hub/test/proxy.test.ts` pins the list so the change is a visible diff. Every entry runs as Navidrome admin.

**Forwarding** — `hub/src/routes/proxy.ts`:

- Strips incoming Subsonic auth params (`u`, `p`, `t`, `s`) then injects Navidrome credentials via fresh `u+t+s` token per request (salt = `crypto.randomBytes(8)`, token = `MD5(password + salt)`).
- Forwarded request headers: `range`, `accept`, `if-none-match`, `if-modified-since`, `cache-control`, `content-type`, `content-length`. `accept-encoding` is intentionally excluded — the proxy does not transcode; forwarding it causes Navidrome to return compressed bytes while the proxy strips `content-encoding`, leaving callers with undecodable data.
- Strips incoming Subsonic auth params (`u`, `p`, `t`, `s`, `jwt`) then injects Navidrome credentials via fresh `u+t+s` token per request (salt = `crypto.randomBytes(8)`, token = `MD5(password + salt)`).
- Forwarded request headers: `range`, `accept`, `if-none-match`, `if-modified-since`, `cache-control`. No body headers — no body is ever forwarded. `accept-encoding` is intentionally excluded — the proxy does not transcode; forwarding it causes Navidrome to return compressed bytes while the proxy strips `content-encoding`, leaving callers with undecodable data.
- All Navidrome response headers forwarded except `set-cookie` (Navidrome session cookies must not propagate to callers under the hub's domain).
- Response streamed via `reply.hijack()` + `pipeline(upstreamResponse, reply.raw)` — no buffering.
- HTTP agent: `keepAlive: true`, `maxSockets: Infinity` — supports ≥12 concurrent streams.
- Client disconnects (`ERR_STREAM_PREMATURE_CLOSE`) are swallowed as non-fatal.

**Ed25519 signing note:** The signing payload uses `request.url` as seen inside the Fastify plugin — this includes the `/proxy` prefix (e.g. `/proxy/rest/stream?id=...`). Callers must sign the full path, not just the suffix.
**Ed25519 signing note:** The signing payload uses `request.url` as seen inside the Fastify plugin — this includes the `/proxy` prefix (e.g. `/proxy/rest/getAlbum?id=...`). Callers must sign the full path, not just the suffix.

## Album art

Expand Down
2 changes: 2 additions & 0 deletions docs/pitfalls.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ Endpoint coverage detail: [opensubsonic.md](opensubsonic.md).
| Trusting `String(remoteErr)` from a peer in a 502 | #156 | Same as external fetches — never echo upstream error text |
| Changing a `/federation/*` contract without bumping `FEDERATION_API_VERSION` in `hub/src/version.ts` and updating federation-api.md | recurring | Contract is the doc; the doc is the contract. Bump both together |
| Adding a peer-facing gate to `federation/peer-auth.ts` and assuming `/proxy/*` is covered | #244 | `/proxy/*` has its own auth path (`proxy/auth.ts`); every peer-level policy must land in BOTH. Only the federation suite catches the gap |
| Widening `/proxy/*` — a new endpoint, method, body, or caller type — to save writing a route | #308 | Everything it forwards runs as Navidrome **admin**. Peers only (no JWT / Subsonic branch); `GET` only; no body; endpoint must be in `PROXY_ALLOWED_ENDPOINTS` (`routes/proxy.ts`), be a read, and have a peer call site. Local callers use `/rest/*`; anything richer gets a Poutine-owned `/federation/*` route |
| Version-gating peers against `FEDERATION_API_VERSION` instead of the floor | #244 | Compare against `MIN_FEDERATION_API_VERSION` — the current version silently cuts supported older peers off at every bump |
| Exposing the Navidrome native API (`/api/*`) to peers | #252 design | Never proxy it — it is the full, unversioned admin surface (incl. user mutation) and breaks silently across Navidrome releases. Native-API use stays local-only (`services/navidrome-native.ts`); peer-visible data goes through Subsonic or a Poutine-owned `/federation/*` contract |

Expand Down Expand Up @@ -164,3 +165,4 @@ Full flow: [authentication.md](authentication.md).
| `corepack` in the Dockerfile on Node 25+ | #292 | Node 25+ no longer bundles it, so `corepack enable` exits 127. Install pnpm with `npm install -g pnpm@x.y.z`, matching `packageManager` |
| Prebuild-bundling native dep (`better-sqlite3` 13+) | #292 | pnpm ignores `"gypfile": false` and runs an implicit `node-gyp rebuild` if the dep is in `onlyBuiltDependencies`. List it in `ignoredBuiltDependencies` instead |
| Building a test stack under the live image tag | #292/#310 | `docker-compose.yml` defaults the hub image to `ghcr.io/benders/poutine:latest`, the tag live hubs pull. A test `up --build` under that tag retags it, a later `up -d --no-build` on a live hub then runs the test build, and the untagged old image can be garbage-collected even while a container still runs it. `test/federation/run.sh` exports `POUTINE_IMAGE=poutine-federation-test:local` (override: `FEDERATION_TEST_IMAGE`); any new harness that builds from this compose file must set `POUTINE_IMAGE` too. A manual `docker compose up --build` / `pnpm hub:up` still retags `:latest` by design |
| `test:federation` on a host that also runs live hubs | #308 | Three extra hub + Navidrome stacks share the Docker VM's memory with everything else. On a 2 GB VM the kernel OOM-killed a live hub mid-run (exit 137; `unless-stopped` restarted it). Containers have no memory limit, so the victim is arbitrary. Give the VM headroom or run the suite elsewhere; afterwards check `docker events --filter event=oom` |
8 changes: 4 additions & 4 deletions docs/system-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ flowchart TB
sonos --> playerdb
rest -- "audio bytes:<br/>ranked sources, failover" --> fed
fed -- "local source: Subsonic stream" --> navidrome
fed -- "peer source:<br/>signed /proxy/rest/stream" --> peers
fed -- "peer source:<br/>signed /federation/stream/:id" --> peers
```

Navidrome credentials live in env vars, not the DB. SPA + API on one port. Audio is piped, never buffered on the hub — see [Play flow](#play-flow).
Expand All @@ -56,7 +56,7 @@ Navidrome credentials live in env vars, not the DB. SPA + API on one port. Audio
| Client API | SPA + Subsonic `/rest/*` over unified library |
| Sync + merge | `syncLocal` from local Navidrome; `/proxy/rest/*` from peers; merge into unified tables |
| Auto-sync | `AutoSyncService`: trigger on Navidrome scan complete; fan out to peers per `SYNC_INTERVAL_MS` |
| Stream/art | Route to source's Navidrome via `/proxy/*` (local or peer) |
| Stream/art | Route to the source's Navidrome: local direct; peer audio via `/federation/stream/:id`, peer cover art via `/proxy/rest/getCoverArt` |
| External art | `/external-art/*`: fanart.tv (MBID) → Last.fm fallback → `art_cache` |
| Admin | `/api/admin/hub/*` and `/api/admin/player/*` (owner-only). `/admin/*` reserved for auth (refresh-cookie path). `/api/invites/*` is public — invite redemption (#272). |
| Version signal | `GET /api/version` → `{ appVersion, buildId }` (#196). Unauthenticated, deliberately separate from `/api/health`, whose per-call Navidrome ping is too costly for one poll per open tab. |
Expand Down Expand Up @@ -146,7 +146,7 @@ Peers stored in `instances` (DB-authoritative since v0.5.0 / federation v5), aut
| `/federation/handshake` | Signed-invitation peer admission |
| `/federation/peers` | Gossip — verify embedded invitation against named inviter's pubkey |
| `/federation/stream/:id` | Cross-peer audio stream |
| `/proxy/rest/*` | Authenticated proxy to local Navidrome (clients and peers both use it) |
| `/proxy/rest/*` | Peer-only read-only proxy to local Navidrome — metadata + cover art |

Contract: [federation-api.md](federation-api.md). Share IDs resolve locally against synced `instance_*` tables — no RPC. See [hub-internals.md#share-ids](hub-internals.md#share-ids).

Expand Down Expand Up @@ -224,7 +224,7 @@ Transcoding happens on the Navidrome that owns the bytes.
| Session tokens | JWT for `/admin/*`: 15 min access + 7 d refresh |
| Subsonic | `u+p` or `u+t+s` |
| Peer | Ed25519 signature on every `/federation/*` and `/proxy/*` |
| Proxy | Ed25519 (peers) → JWT (admin) → Subsonic `u+p`/`u+t+s` |
| Proxy | Peers only; `GET` on a read-only `/rest` allowlist |
| Navidrome | Env-var creds, internal network only |
| Transport | HTTPS required in prod |

Expand Down
Loading
Loading