From a060d177f1f2dc52a7c9aee36c31a36d8275f64c Mon Sep 17 00:00:00 2001 From: Nic Benders Date: Wed, 11 Nov 2026 16:54:50 -0800 Subject: [PATCH 1/3] fix(proxy): restrict /proxy/* to signed peers and a read-only allowlist (#308) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /proxy/* exists so peer hubs can read library metadata and cover art from the local Navidrome. Narrow it to that job: - proxy/auth.ts accepts Ed25519-signed peers only; the JWT and Subsonic credential branches are removed. Lifecycle gate and version-floor check are unchanged. - routes/proxy.ts forwards only GET /proxy/rest/[.view] for the endpoints peer sync, auto-sync and peer cover art call (getArtists, getArtist, getAlbum, getScanStatus, getCoverArt). Other methods get 405, other paths 404, a request with a body 400 — all decided in onRequest, before auth and body parsing, so none reaches Navidrome. - The upstream path is rebuilt from the matched allowlist entry instead of copied from the caller; body headers are no longer forwarded; a caller `jwt` query param is stripped alongside u/p/t/s. Tests: every allowlisted endpoint passes for a signed active peer (with and without .view); non-GET, off-list endpoints, non-/rest paths, bodies, JWT-only and Subsonic-only callers, disabled and tombstoned peers are all refused without an upstream request. Co-Authored-By: Claude Fable 5.2 --- hub/src/proxy/auth.ts | 229 ++++--------- hub/src/routes/proxy.ts | 303 ++++++++++------- hub/test/proxy.test.ts | 730 ++++++++++++++++++++++------------------ 3 files changed, 652 insertions(+), 610 deletions(-) diff --git a/hub/src/proxy/auth.ts b/hub/src/proxy/auth.ts index 63e9c5c..4c5edf4 100644 --- a/hub/src/proxy/auth.ts +++ b/hub/src/proxy/auth.ts @@ -1,30 +1,28 @@ /** - * Unified auth middleware for /proxy/* endpoints. + * Auth middleware for /proxy/* endpoints — peers only. * - * Accepts any one of: - * 1. Ed25519-signed request from a registered peer (reuses federation peer-auth) - * 2. Valid JWT access token (Authorization header → cookie → `token` query param) - * 3. Valid Subsonic credentials: u+p (plaintext or enc:) or u+t+s (token+salt) + * Accepts exactly one kind of caller: an Ed25519-signed request from a + * registered, active peer at or above the federation API floor. There is no + * local-user path (no JWT, no Subsonic credentials): /proxy/* forwards with + * the Navidrome admin credentials, and local users reach the library through + * /rest/* instead. + * + * /proxy/* requests never carry a body (routes/proxy.ts rejects them before + * this runs), so the signed body hash is always "-". * * On success: sets request.proxyAuth and returns. - * On failure: sends 401 and returns (Fastify reply is already sent). + * On failure: sends 401 / 403 and returns (Fastify reply is already sent). */ -import crypto from "node:crypto"; import type { FastifyRequest, FastifyReply } from "fastify"; import { canonicalSigningPayload, verifyRequest } from "../federation/signing.js"; import { MIN_FEDERATION_API_VERSION } from "../federation/peer-auth.js"; -import { verifyToken } from "../auth/jwt.js"; -import { verifyPassword, getStoredPassword } from "../auth/passwords.js"; import type { PeerRegistry } from "../federation/peers.js"; export interface ProxyAuthInfo { - kind: "peer" | "jwt" | "subsonic"; - /** For peer auth: the peer's instance ID */ - peerId?: string; - /** For JWT/subsonic auth: the local user ID */ - userId?: string; - username?: string; + kind: "peer"; + /** The calling peer's instance ID */ + peerId: string; } declare module "fastify" { @@ -33,16 +31,8 @@ declare module "fastify" { } } -/** - * Extract a JWT from the request (Authorization header → cookie → `token` query param). - */ -function extractJwt(request: FastifyRequest): string | undefined { - const auth = request.headers.authorization; - if (auth?.startsWith("Bearer ")) return auth.slice(7); - if (request.cookies?.access_token) return request.cookies.access_token; - const q = request.query as Record; - if (q?.token) return q.token; - return undefined; +function single(value: string | string[] | undefined): string | undefined { + return Array.isArray(value) ? value[0] : value; } export function createRequireProxyAuth(deps: { @@ -55,160 +45,73 @@ export function createRequireProxyAuth(deps: { request: FastifyRequest, reply: FastifyReply, ): Promise { - // ── 1. Ed25519 peer auth ────────────────────────────────────────────────── - const instanceHeader = request.headers["x-poutine-instance"]; - const userHeader = request.headers["x-poutine-user"]; - const timestampHeader = request.headers["x-poutine-timestamp"]; - const signatureHeader = request.headers["x-poutine-signature"]; - - if (instanceHeader && userHeader && timestampHeader && signatureHeader) { - const instanceId = Array.isArray(instanceHeader) ? instanceHeader[0] : instanceHeader; - const userAssertion = Array.isArray(userHeader) ? userHeader[0] : userHeader; - const timestamp = Array.isArray(timestampHeader) ? timestampHeader[0] : timestampHeader; - const signature = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader; - - const peer = deps.registry.peers.get(instanceId); - if (!peer) { - reply.code(401).send({ error: `Unknown peer: ${instanceId}` }); - return; - } - - const ts = parseInt(timestamp, 10); - if (isNaN(ts) || Math.abs(Date.now() - ts) > maxSkewMs) { - reply.code(401).send({ error: "Request timestamp out of acceptable range" }); - return; - } - - // Compute body hash from raw body if available, else "-" - const rawBody = (request.body != null && Buffer.isBuffer(request.body)) - ? request.body - : null; - const bodyHash = rawBody - ? crypto.createHash("sha256").update(rawBody).digest("hex") - : "-"; - - const payload = canonicalSigningPayload({ - method: request.method, - path: request.url, - bodyHash, - timestamp, - instanceId, - userAssertion, - }); - - if (!verifyRequest(peer.publicKey, payload, signature)) { - reply.code(401).send({ error: "Invalid signature" }); - return; - } - - // Enforce the minimum federation API version — the FLOOR, not the - // current version. Comparing against FEDERATION_API_VERSION here would - // cut older-but-supported peers off from /proxy/* on every protocol - // bump (a v6 peer must keep streaming from a v7 hub while the floor - // stays 5). Mirrors MIN_FEDERATION_API_VERSION in federation/peer-auth.ts. - const versionCheckEnabled = process.env.POUTINE_DISABLE_VERSION_CHECK !== "true"; - if (versionCheckEnabled) { - const apiVersionHeader = request.headers["poutine-api-version"]; - const rawVersion = Array.isArray(apiVersionHeader) - ? apiVersionHeader[0] - : apiVersionHeader; - const peerApiVersion = rawVersion !== undefined ? parseInt(String(rawVersion), 10) : NaN; - - if (isNaN(peerApiVersion) || peerApiVersion < MIN_FEDERATION_API_VERSION) { - const gotVersion = isNaN(peerApiVersion) ? "(none)" : String(peerApiVersion); - reply.code(403).send({ - error: `Peer ${instanceId} apiVersion ${gotVersion} is below minimum required ${MIN_FEDERATION_API_VERSION}`, - }); - return; - } - } - - // #244: locally disabled/tombstoned peers are refused here too — the - // matching gate for /federation/* lives in federation/peer-auth.ts. - // Deliberately AFTER signature verification (only the key holder - // learns it is non-active) with the same uniform 403 body, so the - // caller cannot distinguish "disabled" from "tombstoned". - if (peer.lifecycle !== "active") { - reply.code(403).send({ error: "forbidden" }); - return; - } - - request.proxyAuth = { kind: "peer", peerId: instanceId }; + const instanceId = single(request.headers["x-poutine-instance"]); + const userAssertion = single(request.headers["x-poutine-user"]); + const timestamp = single(request.headers["x-poutine-timestamp"]); + const signature = single(request.headers["x-poutine-signature"]); + + // No fallback: a request without the full set of signing headers is + // unauthenticated, whatever other credentials it carries. + if (!instanceId || !userAssertion || !timestamp || !signature) { + reply.code(401).send({ error: "Authentication required" }); return; } - const app = request.server; - const db = app.db; - const q = request.query as Record; - - // ── 2. JWT auth ─────────────────────────────────────────────────────────── - const jwt = extractJwt(request); - if (jwt) { - try { - const { userId } = await verifyToken(jwt, app.config); - const user = db - .prepare("SELECT id, username FROM users WHERE id = ?") - .get(userId) as { id: string; username: string } | undefined; - - if (user) { - request.proxyAuth = { kind: "jwt", userId: user.id, username: user.username }; - return; - } - } catch { - // invalid/expired JWT — fall through to Subsonic param auth - } + const peer = deps.registry.peers.get(instanceId); + if (!peer) { + reply.code(401).send({ error: `Unknown peer: ${instanceId}` }); + return; } - // ── 3. Subsonic param auth (u+p or u+t+s) ──────────────────────────────── - const username = q.u; - if (!username) { - reply.code(401).send({ error: "Authentication required" }); + const ts = parseInt(timestamp, 10); + if (isNaN(ts) || Math.abs(Date.now() - ts) > maxSkewMs) { + reply.code(401).send({ error: "Request timestamp out of acceptable range" }); return; } - const hasPlaintext = typeof q.p === "string" && q.p.length > 0; - const hasToken = typeof q.t === "string" && typeof q.s === "string"; - if (!hasPlaintext && !hasToken) { - reply.code(401).send({ error: "Authentication required" }); + const payload = canonicalSigningPayload({ + method: request.method, + path: request.url, + bodyHash: "-", + timestamp, + instanceId, + userAssertion, + }); + + if (!verifyRequest(peer.publicKey, payload, signature)) { + reply.code(401).send({ error: "Invalid signature" }); return; } - const user = db - .prepare("SELECT id, username, password_enc FROM users WHERE username = ?") - .get(username) as { id: string; username: string; password_enc: string } | undefined; - - let valid = false; - if (user) { - if (hasPlaintext) { - let password = q.p; - if (password.startsWith("enc:")) { - password = Buffer.from(password.slice(4), "hex").toString("utf8"); - } - valid = verifyPassword(user.password_enc, password, app.passwordKey); - } else if (hasToken) { - // Subsonic spec requires salt ≥ 6 chars; reject short salts. - if (q.s.length < 6) { - reply.code(401).send({ error: "Salt too short (minimum 6 characters)" }); - return; - } - const stored = getStoredPassword(user.password_enc, app.passwordKey); - if (stored !== null) { - const expected = crypto - .createHash("md5") - .update(stored + q.s) - .digest("hex"); - const a = Buffer.from(expected, "utf8"); - const b = Buffer.from(q.t.toLowerCase(), "utf8"); - valid = a.length === b.length && crypto.timingSafeEqual(a, b); - } + // Enforce the minimum federation API version — the FLOOR, not the + // current version. Comparing against FEDERATION_API_VERSION here would + // cut older-but-supported peers off from /proxy/* on every protocol + // bump (a v6 peer must keep syncing from a v7 hub while the floor + // stays 5). Mirrors MIN_FEDERATION_API_VERSION in federation/peer-auth.ts. + const versionCheckEnabled = process.env.POUTINE_DISABLE_VERSION_CHECK !== "true"; + if (versionCheckEnabled) { + const rawVersion = single(request.headers["poutine-api-version"]); + const peerApiVersion = rawVersion !== undefined ? parseInt(String(rawVersion), 10) : NaN; + + if (isNaN(peerApiVersion) || peerApiVersion < MIN_FEDERATION_API_VERSION) { + const gotVersion = isNaN(peerApiVersion) ? "(none)" : String(peerApiVersion); + reply.code(403).send({ + error: `Peer ${instanceId} apiVersion ${gotVersion} is below minimum required ${MIN_FEDERATION_API_VERSION}`, + }); + return; } } - if (!user || !valid) { - reply.code(401).send({ error: "Wrong username or password" }); + // #244: locally disabled/tombstoned peers are refused here too — the + // matching gate for /federation/* lives in federation/peer-auth.ts. + // Deliberately AFTER signature verification (only the key holder + // learns it is non-active) with the same uniform 403 body, so the + // caller cannot distinguish "disabled" from "tombstoned". + if (peer.lifecycle !== "active") { + reply.code(403).send({ error: "forbidden" }); return; } - request.proxyAuth = { kind: "subsonic", userId: user.id, username: user.username }; + request.proxyAuth = { kind: "peer", peerId: instanceId }; }; } diff --git a/hub/src/routes/proxy.ts b/hub/src/routes/proxy.ts index 26e87ca..9a47a71 100644 --- a/hub/src/routes/proxy.ts +++ b/hub/src/routes/proxy.ts @@ -1,7 +1,10 @@ /** - * /proxy/* route tree — transparent HTTP proxy to local Navidrome. + * /proxy/* route tree — peer-only, read-only window onto local Navidrome. * - * Auth: Ed25519 peer signature, JWT access token, or Subsonic u+p credentials. + * Auth: Ed25519 peer signature only (proxy/auth.ts). No local-user auth. + * Surface: GET on PROXY_ALLOWED_ENDPOINTS under /proxy/rest/, nothing else. + * Method, path and body are checked in onRequest — before auth and before + * any body parsing — so a refused request never reaches Navidrome. * Streaming: response is piped directly — no buffering. * Concurrency: node:http agent with keepAlive + unlimited sockets. */ @@ -10,11 +13,91 @@ import crypto from "node:crypto"; import http from "node:http"; import https from "node:https"; import { pipeline } from "node:stream/promises"; -import type { FastifyPluginAsync } from "fastify"; +import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from "fastify"; import type { PeerRegistry } from "../federation/peers.js"; import { createRequireProxyAuth } from "../proxy/auth.js"; import { FEDERATION_API_VERSION } from "../version.js"; +// ── Surface allowlist ───────────────────────────────────────────────────────── + +/** + * The only Subsonic endpoints reachable through /proxy/rest/. Every forwarded + * request carries the Navidrome ADMIN credentials, so this list is the whole + * of what a peer can do to the local Navidrome: keep it read-only and keep it + * to what peers actually call. + * + * getArtists, getArtist, getAlbum — peer library sync (library/sync-instance.ts) + * getScanStatus — peer auto-sync poll (services/auto-sync.ts) + * getCoverArt — peer cover art (routes/subsonic/stream.ts) + * + * Unchanged since federation API v5 (the floor), so every supported peer + * stays inside it. Peer audio is /federation/stream/:id, never the proxy. + * Adding an endpoint: it must be a read, and a peer call site must need it. + */ +export const PROXY_ALLOWED_ENDPOINTS: readonly string[] = [ + "getArtists", + "getArtist", + "getAlbum", + "getScanStatus", + "getCoverArt", +]; + +const PROXY_REST_PREFIX = "/proxy/rest/"; +const VIEW_SUFFIX = ".view"; +const allowedEndpoints = new Set(PROXY_ALLOWED_ENDPOINTS); + +/** + * Map a raw request URL to the Navidrome path it may be forwarded to, or + * null. Exact string match on the undecoded path: no normalisation, so + * encoded separators, dot segments, doubled slashes and trailing slashes all + * miss. The optional Subsonic `.view` suffix is accepted and dropped. + */ +export function resolveProxyTarget( + rawUrl: string, +): { upstreamPath: string; search: string } | null { + const q = rawUrl.indexOf("?"); + const path = q === -1 ? rawUrl : rawUrl.slice(0, q); + if (!path.startsWith(PROXY_REST_PREFIX)) return null; + let endpoint = path.slice(PROXY_REST_PREFIX.length); + if (endpoint.endsWith(VIEW_SUFFIX)) { + endpoint = endpoint.slice(0, -VIEW_SUFFIX.length); + } + if (!allowedEndpoints.has(endpoint)) return null; + return { + upstreamPath: `/rest/${endpoint}`, + search: q === -1 ? "" : rawUrl.slice(q + 1), + }; +} + +/** True if the request declares a body (either framing). */ +function declaresBody(request: FastifyRequest): boolean { + if (request.headers["transfer-encoding"] !== undefined) return true; + const len = request.headers["content-length"]; + return len !== undefined && len !== "0"; +} + +/** + * onRequest gate: method, path, body. Runs before auth and before Fastify + * parses anything, with fixed responses that say nothing about the caller. + */ +async function enforceProxySurface( + request: FastifyRequest, + reply: FastifyReply, +): Promise { + if (request.method !== "GET") { + reply.code(405).header("allow", "GET").send({ error: "Method not allowed" }); + return; + } + if (!resolveProxyTarget(request.url)) { + reply.code(404).send({ error: "Not found" }); + return; + } + if (declaresBody(request)) { + reply.code(400).send({ error: "Request body not allowed" }); + return; + } +} + // ── Constants ───────────────────────────────────────────────────────────────── /** Request headers forwarded from the client to Navidrome. */ @@ -28,8 +111,7 @@ const ALLOWED_REQUEST_HEADERS = new Set([ "if-none-match", "if-modified-since", "cache-control", - "content-type", - "content-length", + // No content-type / content-length: /proxy/* never forwards a body. ]); /** Response headers from Navidrome that must NOT be forwarded to the caller. */ @@ -65,126 +147,109 @@ export const proxyRoutes: FastifyPluginAsync = async ( ) => { const requireProxyAuth = createRequireProxyAuth({ registry: opts.registry }); - // Match any method + any path under /proxy/* - app.all("/*", { preHandler: requireProxyAuth }, async (request, reply) => { - const config = app.config; - - // In Fastify, request.url inside a prefixed plugin retains the full URL including - // the plugin prefix. Strip the /proxy prefix before forwarding to Navidrome. - const PROXY_PREFIX = "/proxy"; - const suffix = request.url.startsWith(PROXY_PREFIX) - ? request.url.slice(PROXY_PREFIX.length) || "/" - : request.url; // e.g. "/rest/stream?id=..." - - // Build the target URL: Navidrome base + suffix - const targetBase = config.navidromeUrl.replace(/\/+$/, ""); - const targetUrl = new URL(`${targetBase}${suffix}`); - - // Strip any Subsonic auth params from the incoming request before injecting - // the proxy's own credentials. If the caller used u+p auth, the `p` param - // would remain in the URL and confuse Navidrome's auth (it would see both - // plaintext `p` and token `t+s` and fail). u/t/s are overwritten by set() - // below but p must be explicitly removed. - for (const param of ["u", "p", "t", "s"]) { - targetUrl.searchParams.delete(param); - } - - // Inject Navidrome credentials via Subsonic token auth (u+t+s). - // Fresh salt per request so credentials can't be replayed. - const salt = crypto.randomBytes(8).toString("hex"); - const token = crypto - .createHash("md5") - .update(config.navidromePassword + salt) - .digest("hex"); - - targetUrl.searchParams.set("u", config.navidromeUsername); - targetUrl.searchParams.set("t", token); - targetUrl.searchParams.set("s", salt); - targetUrl.searchParams.set("v", "1.16.1"); - // The proxy overwrites the caller's `c` and drops its User-Agent, so this - // client name is the player identity that PEERS' syncs see in local - // Navidrome. Its reportRealPath is provisioned at runtime by the - // navidrome-native service (services/navidrome-native.ts). - targetUrl.searchParams.set("c", "poutine-proxy"); - - // ── Collect allowed request headers ────────────────────────────────────── - const forwardHeaders: Record = {}; - for (const [key, val] of Object.entries(request.headers)) { - if (ALLOWED_REQUEST_HEADERS.has(key.toLowerCase()) && val !== undefined) { - forwardHeaders[key.toLowerCase()] = Array.isArray(val) - ? val.join(", ") - : val; + // Every method and path lands here so the refusals are explicit (405 / 404 / + // 400) rather than left to the router; only allowlisted GETs get past + // enforceProxySurface. + app.all( + "/*", + { onRequest: enforceProxySurface, preHandler: requireProxyAuth }, + async (request, reply) => { + const config = app.config; + + // request.url inside a prefixed plugin keeps the /proxy prefix. The + // upstream path is rebuilt from the matched allowlist entry — caller + // path text is never copied into the Navidrome URL. Re-checked here so + // the handler cannot forward anything if the hook is ever detached. + const target = resolveProxyTarget(request.url); + if (!target || request.method !== "GET") { + return reply.code(404).send({ error: "Not found" }); + } + + const targetBase = config.navidromeUrl.replace(/\/+$/, ""); + const targetUrl = new URL(`${targetBase}${target.upstreamPath}`); + targetUrl.search = target.search; + + // Strip any Subsonic auth params the caller sent before injecting the + // proxy's own credentials: Navidrome must authenticate the request with + // the injected u+t+s and nothing else. u/t/s are overwritten by set() + // below; p and jwt must be explicitly removed. + for (const param of ["u", "p", "t", "s", "jwt"]) { + targetUrl.searchParams.delete(param); + } + + // Inject Navidrome credentials via Subsonic token auth (u+t+s). + // Fresh salt per request so credentials can't be replayed. + const salt = crypto.randomBytes(8).toString("hex"); + const token = crypto + .createHash("md5") + .update(config.navidromePassword + salt) + .digest("hex"); + + targetUrl.searchParams.set("u", config.navidromeUsername); + targetUrl.searchParams.set("t", token); + targetUrl.searchParams.set("s", salt); + targetUrl.searchParams.set("v", "1.16.1"); + // The proxy overwrites the caller's `c` and drops its User-Agent, so this + // client name is the player identity that PEERS' syncs see in local + // Navidrome. Its reportRealPath is provisioned at runtime by the + // navidrome-native service (services/navidrome-native.ts). + targetUrl.searchParams.set("c", "poutine-proxy"); + + // ── Collect allowed request headers ──────────────────────────────────── + const forwardHeaders: Record = {}; + for (const [key, val] of Object.entries(request.headers)) { + if (ALLOWED_REQUEST_HEADERS.has(key.toLowerCase()) && val !== undefined) { + forwardHeaders[key.toLowerCase()] = Array.isArray(val) + ? val.join(", ") + : val; + } } - } - - // ── Determine if there's a body to forward ──────────────────────────────── - const methodHasBody = - request.method !== "GET" && - request.method !== "HEAD" && - request.method !== "DELETE"; - - // ── Make the upstream request ───────────────────────────────────────────── - const isHttps = targetUrl.protocol === "https:"; - const agent = isHttps ? httpsAgent : httpAgent; - - const upstreamResponse = await new Promise( - (resolve, reject) => { - const options: http.RequestOptions = { - hostname: targetUrl.hostname, - port: targetUrl.port || (isHttps ? 443 : 80), - path: `${targetUrl.pathname}${targetUrl.search}`, - method: request.method, - headers: forwardHeaders, - agent, - }; - - const req = (isHttps ? https : http).request(options, resolve); - req.on("error", reject); - - if (methodHasBody) { - // Fastify has already consumed and parsed the body if content-type - // was application/json. For raw bytes (audio/image POSTs) it's a - // Buffer on request.body. For others, pipe the raw stream. - const rawBody = request.body; - if (Buffer.isBuffer(rawBody)) { - req.end(rawBody); - } else if (typeof rawBody === "string") { - req.end(rawBody); - } else if (rawBody != null) { - req.end(JSON.stringify(rawBody)); - } else { - // No parsed body — stream the raw request - request.raw.pipe(req); - } - } else { + + // ── Make the upstream request (always a bodyless GET) ────────────────── + const isHttps = targetUrl.protocol === "https:"; + const agent = isHttps ? httpsAgent : httpAgent; + + const upstreamResponse = await new Promise( + (resolve, reject) => { + const options: http.RequestOptions = { + hostname: targetUrl.hostname, + port: targetUrl.port || (isHttps ? 443 : 80), + path: `${targetUrl.pathname}${targetUrl.search}`, + method: "GET", + headers: forwardHeaders, + agent, + }; + + const req = (isHttps ? https : http).request(options, resolve); + req.on("error", reject); req.end(); + }, + ); + + // ── Forward response status + headers (minus blocked) + stream body ──── + const responseHeaders: Record = {}; + for (const [key, val] of Object.entries(upstreamResponse.headers)) { + if (!BLOCKED_RESPONSE_HEADERS.has(key.toLowerCase()) && val !== undefined) { + responseHeaders[key.toLowerCase()] = Array.isArray(val) + ? val.join(", ") + : val; } - }, - ); - - // ── Forward response status + headers (minus blocked) + stream body ───────── - const responseHeaders: Record = {}; - for (const [key, val] of Object.entries(upstreamResponse.headers)) { - if (!BLOCKED_RESPONSE_HEADERS.has(key.toLowerCase()) && val !== undefined) { - responseHeaders[key.toLowerCase()] = Array.isArray(val) - ? val.join(", ") - : val; } - } - responseHeaders["poutine-api-version"] = String(FEDERATION_API_VERSION); + responseHeaders["poutine-api-version"] = String(FEDERATION_API_VERSION); - reply.hijack(); - const raw = reply.raw; - raw.writeHead(upstreamResponse.statusCode ?? 502, responseHeaders); + reply.hijack(); + const raw = reply.raw; + raw.writeHead(upstreamResponse.statusCode ?? 502, responseHeaders); - try { - await pipeline(upstreamResponse, raw); - } catch (err: unknown) { - const nodeErr = err as NodeJS.ErrnoException; - if (nodeErr.code !== "ERR_STREAM_PREMATURE_CLOSE") { - app.log.error(err, "proxy pipeline error"); + try { + await pipeline(upstreamResponse, raw); + } catch (err: unknown) { + const nodeErr = err as NodeJS.ErrnoException; + if (nodeErr.code !== "ERR_STREAM_PREMATURE_CLOSE") { + app.log.error(err, "proxy pipeline error"); + } } - } - }); + }, + ); }; diff --git a/hub/test/proxy.test.ts b/hub/test/proxy.test.ts index 340cfcc..96d621f 100644 --- a/hub/test/proxy.test.ts +++ b/hub/test/proxy.test.ts @@ -1,14 +1,19 @@ /** - * Tests for /proxy/* — authenticating Navidrome proxy tier. + * Tests for /proxy/* — peer-only, read-only Navidrome proxy tier. * * Covers: - * - All three auth modes accept valid credentials (Ed25519, JWT, Subsonic u+p) - * - All three auth modes reject invalid/missing credentials - * - Streaming passthrough: response body piped without buffering - * - 12 concurrent streams do not block (smoke test) + * - Ed25519 peer auth accepts a signed, active peer at or above the floor + * - Every allowlisted endpoint (with and without `.view`) is forwarded + * - Surface gate: non-GET, non-allowlisted endpoint, non-/rest path and + * request bodies are refused and never reach Navidrome + * - Local-user credentials (JWT, Subsonic) are not accepted + * - Lifecycle gate: disabled / tombstoned peers refused + * - Passthrough: response bytes piped, credentials injected, headers filtered + * - 12 concurrent requests do not block (smoke test) */ import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import crypto from "node:crypto"; import http from "node:http"; import os from "node:os"; import path from "node:path"; @@ -23,6 +28,10 @@ import { canonicalSigningPayload, signRequest, } from "../src/federation/signing.js"; +import { + PROXY_ALLOWED_ENDPOINTS, + resolveProxyTarget, +} from "../src/routes/proxy.js"; import { FEDERATION_API_VERSION } from "../src/version.js"; import { seedPeer } from "./helpers/seed-peer.js"; import type { KeyObject } from "node:crypto"; @@ -37,27 +46,41 @@ function tmpPath(suffix = "") { ); } -/** Minimal MP3 header bytes */ -const FAKE_AUDIO = Buffer.from([0xff, 0xfb, 0x90, 0x00, 0xde, 0xad, 0xbe, 0xef]); +/** Minimal MP3 header bytes — stands in for any binary payload (cover art). */ +const FAKE_BYTES = Buffer.from([0xff, 0xfb, 0x90, 0x00, 0xde, 0xad, 0xbe, 0xef]); + +interface UpstreamRequest { + method: string; + url: string; + headers: http.IncomingHttpHeaders; +} /** - * Start a fake Navidrome that returns a fixed audio buffer on any request. - * Records all received request paths for assertion. + * Start a fake Navidrome that returns a fixed buffer on any request and + * records everything it receives. `delayMs` holds each response open so + * concurrent requests overlap. */ -function startFakeNavidrome(response = FAKE_AUDIO): Promise<{ +function startFakeNavidrome(delayMs = 0): Promise<{ server: http.Server; port: number; - requests: string[]; + requests: UpstreamRequest[]; }> { - const requests: string[] = []; + const requests: UpstreamRequest[] = []; return new Promise((resolve) => { const server = http.createServer((req, res) => { - requests.push(req.url ?? ""); - res.writeHead(200, { - "content-type": "audio/mpeg", - "content-length": String(response.length), + requests.push({ + method: req.method ?? "", + url: req.url ?? "", + headers: req.headers, }); - res.end(response); + setTimeout(() => { + res.writeHead(200, { + "content-type": "audio/mpeg", + "content-length": String(FAKE_BYTES.length), + "set-cookie": "nd-session=abc", + }); + res.end(FAKE_BYTES); + }, delayMs); }); server.listen(0, "127.0.0.1", () => { resolve({ server, port: (server.address() as AddressInfo).port, requests }); @@ -84,10 +107,11 @@ function makePeerHeaders(opts: { privateKey: KeyObject; instanceId: string; url: string; + method?: string; }): Record { const ts = String(Date.now()); const payload = canonicalSigningPayload({ - method: "GET", + method: opts.method ?? "GET", path: opts.url, bodyHash: "-", timestamp: ts, @@ -109,15 +133,13 @@ function makePeerHeaders(opts: { interface TestSetup { app: FastifyInstance; navidrome: http.Server; - navidromePort: number; - navidromeRequests: string[]; + navidromeRequests: UpstreamRequest[]; keyPathA: string; // peer A (the caller) keyPathApp: string; // the hub under test privKeyA: KeyObject; - pubKeyBase64A: string; } -async function buildTestSetup(): Promise { +async function buildTestSetup(navidromeDelayMs = 0): Promise { const keyPathA = tmpPath("key-a.pem"); const keyPathApp = tmpPath("key-app.pem"); @@ -125,7 +147,7 @@ async function buildTestSetup(): Promise { loadOrCreatePrivateKey(keyPathA); const { server: navidrome, port: navidromePort, requests: navidromeRequests } = - await startFakeNavidrome(); + await startFakeNavidrome(navidromeDelayMs); const config: Partial = { databasePath: ":memory:", @@ -147,16 +169,7 @@ async function buildTestSetup(): Promise { publicKeySpec: `ed25519:${pubKeyBase64A}`, }); - return { - app, - navidrome, - navidromePort, - navidromeRequests, - keyPathA, - keyPathApp, - privKeyA, - pubKeyBase64A, - }; + return { app, navidrome, navidromeRequests, keyPathA, keyPathApp, privKeyA }; } async function teardown(setup: TestSetup) { @@ -167,7 +180,37 @@ async function teardown(setup: TestSetup) { } } -// ── Auth accept tests ────────────────────────────────────────────────────────── +/** Inject a request validly signed by the active peer "peer-a". */ +function signedRequest( + setup: TestSetup, + url: string, + opts: { + method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"; + headers?: Record; + payload?: string; + } = {}, +) { + const method = opts.method ?? "GET"; + return setup.app.inject({ + method, + url, + headers: { + ...makePeerHeaders({ + privateKey: setup.privKeyA, + instanceId: "peer-a", + url, + method, + }), + ...opts.headers, + }, + payload: opts.payload, + }); +} + +/** The read every sync starts with — a known-allowlisted URL. */ +const ALLOWED_URL = "/proxy/rest/getArtists?f=json"; + +// ── Peer auth ───────────────────────────────────────────────────────────────── describe("proxy — auth accept: Ed25519 peer signature", () => { let setup: TestSetup; @@ -183,44 +226,41 @@ describe("proxy — auth accept: Ed25519 peer signature", () => { it("allows a request with valid Ed25519 signature from a known peer", async () => { // request.url inside a Fastify prefixed plugin retains the full path // including the /proxy prefix. The signing payload must use it. - const url = "/proxy/rest/ping?f=json"; - const headers = makePeerHeaders({ - privateKey: setup.privKeyA, - instanceId: "peer-a", - url, // sign the full path as the middleware sees it - }); - - const res = await setup.app.inject({ - method: "GET", - url, - headers, - }); + const res = await signedRequest(setup, ALLOWED_URL); - // Navidrome stub returns 200 regardless — we just care auth passed (not 401) expect(res.statusCode).toBe(200); + expect(setup.navidromeRequests).toHaveLength(1); }); it("accepts a peer at the version floor, not just the current version (v5 vs v7)", async () => { // Regression for the #244 bump: the check must compare against // MIN_FEDERATION_API_VERSION (5), or every protocol bump cuts // older-but-supported peers off from /proxy/*. - const url = "/proxy/rest/ping?f=json"; - const headers = { - ...makePeerHeaders({ privateKey: setup.privKeyA, instanceId: "peer-a", url }), - "poutine-api-version": "5", - }; - const res = await setup.app.inject({ method: "GET", url, headers }); + const res = await signedRequest(setup, ALLOWED_URL, { + headers: { "poutine-api-version": "5" }, + }); expect(res.statusCode).toBe(200); }); it("rejects a peer below the version floor", async () => { - const url = "/proxy/rest/ping?f=json"; - const headers = { - ...makePeerHeaders({ privateKey: setup.privKeyA, instanceId: "peer-a", url }), - "poutine-api-version": "4", - }; + const res = await signedRequest(setup, ALLOWED_URL, { + headers: { "poutine-api-version": "4" }, + }); + expect(res.statusCode).toBe(403); + expect(setup.navidromeRequests).toHaveLength(0); + }); + + it("rejects a signed peer that sends no api version", async () => { + const url = ALLOWED_URL; + const headers = makePeerHeaders({ + privateKey: setup.privKeyA, + instanceId: "peer-a", + url, + }); + delete headers["poutine-api-version"]; const res = await setup.app.inject({ method: "GET", url, headers }); expect(res.statusCode).toBe(403); + expect(setup.navidromeRequests).toHaveLength(0); }); }); @@ -235,25 +275,16 @@ describe("proxy — lifecycle gate on peer auth (#244)", () => { await teardown(setup); }); - function signedPing() { - const url = "/proxy/rest/ping?f=json"; - const headers = makePeerHeaders({ - privateKey: setup.privKeyA, - instanceId: "peer-a", - url, - }); - return setup.app.inject({ method: "GET", url, headers }); - } - it("refuses a disabled peer's validly signed request with a uniform 403", async () => { setup.app.db .prepare("UPDATE instances SET lifecycle = 'disabled' WHERE id = 'peer-a'") .run(); setup.app.peerRegistry.reload(); - const res = await signedPing(); + const res = await signedRequest(setup, ALLOWED_URL); expect(res.statusCode).toBe(403); expect(res.json()).toEqual({ error: "forbidden" }); + expect(setup.navidromeRequests).toHaveLength(0); }); it("refuses a tombstoned peer with the identical 403 body as disabled", async () => { @@ -262,13 +293,189 @@ describe("proxy — lifecycle gate on peer auth (#244)", () => { .run(); setup.app.peerRegistry.reload(); - const res = await signedPing(); + const res = await signedRequest(setup, ALLOWED_URL); expect(res.statusCode).toBe(403); expect(res.json()).toEqual({ error: "forbidden" }); + expect(setup.navidromeRequests).toHaveLength(0); }); }); -describe("proxy — auth accept: JWT", () => { +// ── Endpoint allowlist ──────────────────────────────────────────────────────── + +describe("proxy — endpoint allowlist", () => { + let setup: TestSetup; + + beforeEach(async () => { + setup = await buildTestSetup(); + }); + + afterEach(async () => { + await teardown(setup); + }); + + it("is exactly the set of reads peer sync, auto-sync and cover art issue", () => { + // Pinned on purpose: widening the peer-facing surface must be a visible, + // reviewed diff here as well as in routes/proxy.ts. + expect([...PROXY_ALLOWED_ENDPOINTS].sort()).toEqual([ + "getAlbum", + "getArtist", + "getArtists", + "getCoverArt", + "getScanStatus", + ]); + }); + + it.each(PROXY_ALLOWED_ENDPOINTS.map((e) => [e]))( + "forwards GET /proxy/rest/%s for a signed active peer", + async (endpoint) => { + const res = await signedRequest(setup, `/proxy/rest/${endpoint}?id=x1&f=json`); + + expect(res.statusCode).toBe(200); + expect(setup.navidromeRequests).toHaveLength(1); + const upstream = new URL(setup.navidromeRequests[0].url, "http://nd"); + expect(setup.navidromeRequests[0].method).toBe("GET"); + expect(upstream.pathname).toBe(`/rest/${endpoint}`); + expect(upstream.searchParams.get("id")).toBe("x1"); + }, + ); + + it.each(PROXY_ALLOWED_ENDPOINTS.map((e) => [e]))( + "forwards GET /proxy/rest/%s.view to the same upstream endpoint", + async (endpoint) => { + const res = await signedRequest(setup, `/proxy/rest/${endpoint}.view?id=x1`); + + expect(res.statusCode).toBe(200); + expect(setup.navidromeRequests).toHaveLength(1); + const upstream = new URL(setup.navidromeRequests[0].url, "http://nd"); + expect(upstream.pathname).toBe(`/rest/${endpoint}`); + }, + ); + + it.each([ + ["HEAD"], + ["POST"], + ["PUT"], + ["PATCH"], + ["DELETE"], + ] as const)( + "rejects %s on an allowlisted endpoint with 405", + async (method) => { + const res = await signedRequest(setup, ALLOWED_URL, { method }); + + expect(res.statusCode).toBe(405); + expect(res.headers.allow).toBe("GET"); + expect(setup.navidromeRequests).toHaveLength(0); + }, + ); + + it("never forwards OPTIONS (answered by the CORS layer, not the proxy)", async () => { + await signedRequest(setup, ALLOWED_URL, { method: "OPTIONS" }); + await signedRequest(setup, ALLOWED_URL, { + method: "OPTIONS", + headers: { origin: "http://example.test", "access-control-request-method": "POST" }, + }); + + expect(setup.navidromeRequests).toHaveLength(0); + }); + + it.each([ + // Subsonic endpoints outside the allowlist — reads and writes alike. + ["/proxy/rest/ping?f=json"], + ["/proxy/rest/stream?id=trk-1"], + ["/proxy/rest/getAlbumList2?type=newest"], + ["/proxy/rest/startScan"], + ["/proxy/rest/startScan.view"], + // Near-misses of an allowlisted name: the match is exact and undecoded. + ["/proxy/rest/getartists"], + ["/proxy/rest/getArtists/"], + ["/proxy/rest/getArtists.view.view"], + ["/proxy/rest/getArtists.json"], + ["/proxy/rest/getArtists/../startScan"], + ["/proxy/rest/getArtists%2F..%2FstartScan"], + ["/proxy/rest/%67etArtists"], + ["/proxy/rest//getArtists"], + ["/proxy//rest/getArtists"], + ["/proxy/rest/getArtists;x=1"], + ])("rejects non-allowlisted endpoint %s with 404", async (url) => { + const res = await signedRequest(setup, url); + + expect(res.statusCode).toBe(404); + expect(setup.navidromeRequests).toHaveLength(0); + }); + + it.each([ + ["/proxy/"], + ["/proxy/rest"], + ["/proxy/rest/"], + ["/proxy/auth/login"], + ["/proxy/api/song"], + ["/proxy/app/"], + ["/proxy/share/abc"], + ["/proxy/getArtists"], + ["/proxy/x/rest/getArtists"], + ])("rejects non-/rest path %s with 404", async (url) => { + const res = await signedRequest(setup, url); + + expect(res.statusCode).toBe(404); + expect(setup.navidromeRequests).toHaveLength(0); + }); + + it("rejects a GET that carries a body with 400", async () => { + const res = await signedRequest(setup, ALLOWED_URL, { + headers: { "content-type": "application/json" }, + payload: JSON.stringify({ a: 1 }), + }); + + expect(res.statusCode).toBe(400); + expect(setup.navidromeRequests).toHaveLength(0); + }); + + it("rejects a GET that declares a chunked body with 400", async () => { + const res = await signedRequest(setup, ALLOWED_URL, { + headers: { "transfer-encoding": "chunked" }, + }); + + expect(res.statusCode).toBe(400); + expect(setup.navidromeRequests).toHaveLength(0); + }); + + it("refuses off-surface requests before auth, with no credentials at all", async () => { + const post = await setup.app.inject({ method: "POST", url: ALLOWED_URL }); + const offList = await setup.app.inject({ method: "GET", url: "/proxy/rest/ping" }); + + expect(post.statusCode).toBe(405); + expect(offList.statusCode).toBe(404); + expect(setup.navidromeRequests).toHaveLength(0); + }); +}); + +describe("resolveProxyTarget", () => { + it("maps an allowlisted URL to its upstream path and raw query", () => { + expect(resolveProxyTarget("/proxy/rest/getAlbum?id=a%201&f=json")).toEqual({ + upstreamPath: "/rest/getAlbum", + search: "id=a%201&f=json", + }); + expect(resolveProxyTarget("/proxy/rest/getArtists.view")).toEqual({ + upstreamPath: "/rest/getArtists", + search: "", + }); + }); + + it("does not let the query string satisfy the path match", () => { + expect(resolveProxyTarget("/proxy/rest/ping?x=/proxy/rest/getArtists")).toBeNull(); + expect(resolveProxyTarget("/proxy/auth/login?/proxy/rest/getArtists")).toBeNull(); + }); + + it("returns null for absolute-form and prefix-less URLs", () => { + expect(resolveProxyTarget("http://hub/proxy/rest/getArtists")).toBeNull(); + expect(resolveProxyTarget("/rest/getArtists")).toBeNull(); + expect(resolveProxyTarget("")).toBeNull(); + }); +}); + +// ── Auth reject ─────────────────────────────────────────────────────────────── + +describe("proxy — auth reject: local-user credentials are not accepted", () => { let setup: TestSetup; let userId: string; @@ -281,93 +488,91 @@ describe("proxy — auth accept: JWT", () => { await teardown(setup); }); - it("allows a request with valid JWT in Authorization header", async () => { + it("rejects a valid JWT in the Authorization header", async () => { const token = await createAccessToken(userId, setup.app.config); const res = await setup.app.inject({ method: "GET", - url: "/proxy/rest/ping?f=json", + url: ALLOWED_URL, headers: { authorization: `Bearer ${token}` }, }); - expect(res.statusCode).toBe(200); + expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("allows a request with valid JWT in access_token cookie", async () => { + it("rejects a valid JWT in the access_token cookie", async () => { const token = await createAccessToken(userId, setup.app.config); const res = await setup.app.inject({ method: "GET", - url: "/proxy/rest/ping?f=json", + url: ALLOWED_URL, cookies: { access_token: token }, }); - expect(res.statusCode).toBe(200); + expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("allows a request with valid JWT in token query param", async () => { + it("rejects a valid JWT in the token query param", async () => { const token = await createAccessToken(userId, setup.app.config); const res = await setup.app.inject({ method: "GET", - url: `/proxy/rest/ping?f=json&token=${token}`, + url: `${ALLOWED_URL}&token=${token}`, }); - expect(res.statusCode).toBe(200); - }); -}); - -describe("proxy — auth accept: Subsonic u+p", () => { - let setup: TestSetup; - - beforeEach(async () => { - setup = await buildTestSetup(); - seedUser(setup.app); - }); - - afterEach(async () => { - await teardown(setup); + expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("allows a request with valid u+p credentials", async () => { + it("rejects valid Subsonic u+p credentials", async () => { const res = await setup.app.inject({ method: "GET", - url: "/proxy/rest/ping?u=tester&p=secret&f=json", + url: `${ALLOWED_URL}&u=tester&p=secret`, }); - expect(res.statusCode).toBe(200); + expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("allows a request with enc: encoded password", async () => { + it("rejects valid Subsonic u+p with an enc: password", async () => { const hexPassword = Buffer.from("secret", "utf8").toString("hex"); const res = await setup.app.inject({ method: "GET", - url: `/proxy/rest/ping?u=tester&p=enc:${hexPassword}&f=json`, + url: `${ALLOWED_URL}&u=tester&p=enc:${hexPassword}`, }); - expect(res.statusCode).toBe(200); + expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("allows a request with valid u+t+s (#106)", async () => { - const { createHash } = await import("node:crypto"); + it("rejects valid Subsonic u+t+s credentials", async () => { const salt = "deadbeef"; - const token = createHash("md5").update("secret" + salt).digest("hex"); + const token = crypto.createHash("md5").update("secret" + salt).digest("hex"); const res = await setup.app.inject({ method: "GET", - url: `/proxy/rest/ping?u=tester&t=${token}&s=${salt}&f=json`, + url: `${ALLOWED_URL}&u=tester&t=${token}&s=${salt}`, }); - expect(res.statusCode).toBe(200); + expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("rejects u+t+s with wrong token (#106)", async () => { + it("rejects a local user who also sends an incomplete set of peer headers", async () => { + const token = await createAccessToken(userId, setup.app.config); + const headers = makePeerHeaders({ + privateKey: setup.privKeyA, + instanceId: "peer-a", + url: ALLOWED_URL, + }); + delete headers["x-poutine-signature"]; const res = await setup.app.inject({ method: "GET", - url: `/proxy/rest/ping?u=tester&t=${"0".repeat(32)}&s=any&f=json`, + url: ALLOWED_URL, + headers: { ...headers, authorization: `Bearer ${token}` }, }); expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); }); -// ── Auth reject tests ────────────────────────────────────────────────────────── - -describe("proxy — auth reject", () => { +describe("proxy — auth reject: peer signature", () => { let setup: TestSetup; beforeEach(async () => { setup = await buildTestSetup(); - seedUser(setup.app); }); afterEach(async () => { @@ -375,83 +580,55 @@ describe("proxy — auth reject", () => { }); it("rejects with 401 when no auth provided", async () => { - const res = await setup.app.inject({ - method: "GET", - url: "/proxy/rest/ping?f=json", - }); - expect(res.statusCode).toBe(401); - }); - - it("rejects with 401 when JWT is invalid/expired", async () => { - const res = await setup.app.inject({ - method: "GET", - url: "/proxy/rest/ping?f=json", - headers: { authorization: "Bearer not-a-real-token" }, - }); - // Falls through to Subsonic param auth, which also fails (no u param) - expect(res.statusCode).toBe(401); - }); - - it("rejects with 401 when Subsonic password is wrong", async () => { - const res = await setup.app.inject({ - method: "GET", - url: "/proxy/rest/ping?u=tester&p=wrongpassword&f=json", - }); + const res = await setup.app.inject({ method: "GET", url: ALLOWED_URL }); expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("rejects with 401 when Subsonic username is unknown", async () => { - const res = await setup.app.inject({ - method: "GET", - url: "/proxy/rest/ping?u=nobody&p=secret&f=json", + it("rejects with 401 when Ed25519 signature is tampered", async () => { + const res = await signedRequest(setup, ALLOWED_URL, { + headers: { + "x-poutine-signature": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", + }, }); expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); - it("rejects with 401 when Ed25519 signature is tampered", async () => { - const url = "/proxy/rest/ping?f=json"; + it("rejects with 401 when the signature covers a different endpoint", async () => { const headers = makePeerHeaders({ privateKey: setup.privKeyA, instanceId: "peer-a", - url, + url: "/proxy/rest/getArtist?id=1", }); - // Corrupt the signature - headers["x-poutine-signature"] = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; - const res = await setup.app.inject({ method: "GET", - url, + url: "/proxy/rest/getAlbum?id=1", headers, }); expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); it("rejects with 401 when Ed25519 instance ID is not a known peer", async () => { - const url = "/proxy/rest/ping?f=json"; const headers = makePeerHeaders({ privateKey: setup.privKeyA, instanceId: "unknown-peer", - url, - }); - - const res = await setup.app.inject({ - method: "GET", - url, - headers, + url: ALLOWED_URL, }); + const res = await setup.app.inject({ method: "GET", url: ALLOWED_URL, headers }); expect(res.statusCode).toBe(401); + expect(setup.navidromeRequests).toHaveLength(0); }); }); -// ── Streaming passthrough ────────────────────────────────────────────────────── +// ── Passthrough ─────────────────────────────────────────────────────────────── -describe("proxy — streaming passthrough", () => { +describe("proxy — passthrough", () => { let setup: TestSetup; - let userId: string; beforeEach(async () => { setup = await buildTestSetup(); - ({ id: userId } = seedUser(setup.app)); }); afterEach(async () => { @@ -459,122 +636,77 @@ describe("proxy — streaming passthrough", () => { }); it("forwards exact response bytes and content-type from Navidrome", async () => { - const token = await createAccessToken(userId, setup.app.config); - const res = await setup.app.inject({ - method: "GET", - url: "/proxy/rest/stream?id=trk-1", - headers: { authorization: `Bearer ${token}` }, - }); + const res = await signedRequest(setup, "/proxy/rest/getCoverArt?id=al-1&size=300"); expect(res.statusCode).toBe(200); expect(res.headers["content-type"]).toMatch(/audio\/mpeg/); - expect(Buffer.from(res.rawPayload)).toEqual(FAKE_AUDIO); + expect(res.headers["poutine-api-version"]).toBe(String(FEDERATION_API_VERSION)); + expect(Buffer.from(res.rawPayload)).toEqual(FAKE_BYTES); }); - it("forwards Navidrome credentials to upstream (u+t+s in query)", async () => { - const token = await createAccessToken(userId, setup.app.config); - await setup.app.inject({ - method: "GET", - url: "/proxy/rest/stream?id=trk-1", - headers: { authorization: `Bearer ${token}` }, - }); - - // Navidrome should have received a request with injected proxy credentials. - // The path must not contain /proxy, and caller's u+p must be stripped. - expect(setup.navidromeRequests.length).toBeGreaterThan(0); - const receivedUrl = setup.navidromeRequests[0]; - expect(receivedUrl).not.toContain("/proxy"); - expect(receivedUrl).toContain("/rest/stream"); - expect(receivedUrl).toContain("u=nav-admin"); - expect(receivedUrl).toContain("t="); - expect(receivedUrl).toContain("s="); - // Caller's plaintext password must not be forwarded to Navidrome - expect(receivedUrl).not.toMatch(/[?&]p=/); - }); - - it("strips caller u+p params and injects proxy credentials when Subsonic auth used", async () => { - // Caller authenticates with u+p; those params must not reach Navidrome - await setup.app.inject({ - method: "GET", - url: "/proxy/rest/stream?id=trk-1&u=tester&p=secret", - }); + it("does not relay Navidrome's set-cookie to the caller", async () => { + const res = await signedRequest(setup, "/proxy/rest/getCoverArt?id=al-1"); - expect(setup.navidromeRequests.length).toBeGreaterThan(0); - const receivedUrl = setup.navidromeRequests[0]; - expect(receivedUrl).not.toMatch(/[?&]p=/); - expect(receivedUrl).not.toContain("u=tester"); - expect(receivedUrl).toContain("u=nav-admin"); - expect(receivedUrl).toContain("t="); - expect(receivedUrl).toContain("s="); + expect(res.statusCode).toBe(200); + expect(res.headers["set-cookie"]).toBeUndefined(); + }); + + it("injects Navidrome credentials upstream (u+t+s in query, no /proxy prefix)", async () => { + await signedRequest(setup, "/proxy/rest/getCoverArt?id=al-1&size=300"); + + expect(setup.navidromeRequests).toHaveLength(1); + const upstream = new URL(setup.navidromeRequests[0].url, "http://nd"); + expect(upstream.pathname).toBe("/rest/getCoverArt"); + expect(upstream.searchParams.get("id")).toBe("al-1"); + expect(upstream.searchParams.get("size")).toBe("300"); + expect(upstream.searchParams.get("u")).toBe("nav-admin"); + expect(upstream.searchParams.get("c")).toBe("poutine-proxy"); + const salt = upstream.searchParams.get("s") ?? ""; + expect(upstream.searchParams.get("t")).toBe( + crypto.createHash("md5").update("nav-pass" + salt).digest("hex"), + ); }); - it("passes Range header through to Navidrome", async () => { - const token = await createAccessToken(userId, setup.app.config); - const res = await setup.app.inject({ - method: "GET", - url: "/proxy/rest/stream?id=trk-1", + it("strips caller-supplied Subsonic auth params before injecting its own", async () => { + await signedRequest( + setup, + "/proxy/rest/getCoverArt?id=al-1&u=someone&p=pw&t=tok&s=salt&jwt=abc&c=other", + ); + + expect(setup.navidromeRequests).toHaveLength(1); + const upstream = new URL(setup.navidromeRequests[0].url, "http://nd"); + expect(upstream.searchParams.getAll("u")).toEqual(["nav-admin"]); + expect(upstream.searchParams.getAll("c")).toEqual(["poutine-proxy"]); + expect(upstream.searchParams.has("p")).toBe(false); + expect(upstream.searchParams.has("jwt")).toBe(false); + expect(upstream.searchParams.getAll("t")).not.toContain("tok"); + expect(upstream.searchParams.getAll("s")).not.toContain("salt"); + }); + + it("forwards only allowlisted request headers to Navidrome", async () => { + // accept-encoding: if it reached Navidrome it may respond with gzip, and + // the caller would get compressed bytes it was never told to decompress. + // authorization / cookie / signing headers: none of Navidrome's business. + const res = await signedRequest(setup, "/proxy/rest/getCoverArt?id=al-1", { headers: { - authorization: `Bearer ${token}`, range: "bytes=0-1023", + "if-none-match": '"etag-1"', + "accept-encoding": "gzip, deflate, br", + authorization: "Bearer whatever", + cookie: "access_token=whatever", }, }); - // Fake Navidrome returns 200 regardless, but the request headers should pass expect(res.statusCode).toBe(200); - }); - - it("does not forward accept-encoding to Navidrome", async () => { - // If accept-encoding reaches Navidrome, it may respond with gzip. The proxy - // strips content-encoding from responses, leaving the caller with raw compressed - // bytes that fail JSON parsing. - const receivedHeaders: Record = {}; - const headerCapture = await new Promise<{ server: http.Server; port: number }>( - (resolve) => { - const server = http.createServer((req, res) => { - for (const [k, v] of Object.entries(req.headers)) { - receivedHeaders[k] = Array.isArray(v) ? v.join(", ") : (v ?? ""); - } - res.writeHead(200, { "content-type": "application/json", "content-length": "2" }); - res.end("{}"); - }); - server.listen(0, "127.0.0.1", () => - resolve({ server, port: (server.address() as AddressInfo).port }), - ); - }, - ); - - const keyPathLocal = tmpPath("key-enc.pem"); - - const { buildApp: buildAppLocal } = await import("../src/server.js"); - const appLocal = await buildAppLocal({ - databasePath: ":memory:", - jwtSecret: "enc-test", - poutinePrivateKeyPath: keyPathLocal, - poutineInstanceId: "enc-test", - navidromeUrl: `http://127.0.0.1:${headerCapture.port}`, - navidromeUsername: "admin", - navidromePassword: "admin", - }); - await appLocal.ready(); - const { id: uid } = seedUser(appLocal, "enc-user", "enc-pass"); - const jwt = await createAccessToken(uid, appLocal.config); - - try { - await appLocal.inject({ - method: "GET", - url: "/proxy/rest/ping?f=json", - headers: { - authorization: `Bearer ${jwt}`, - "accept-encoding": "gzip, deflate, br", - }, - }); - - expect(receivedHeaders["accept-encoding"]).toBeUndefined(); - } finally { - await appLocal.close(); - await new Promise((r) => headerCapture.server.close(() => r())); - if (fs.existsSync(keyPathLocal)) fs.unlinkSync(keyPathLocal); - } + const received = setup.navidromeRequests[0].headers; + expect(received.range).toBe("bytes=0-1023"); + expect(received["if-none-match"]).toBe('"etag-1"'); + expect(received["accept-encoding"]).toBeUndefined(); + expect(received.authorization).toBeUndefined(); + expect(received.cookie).toBeUndefined(); + expect(received["content-type"]).toBeUndefined(); + expect(received["content-length"]).toBeUndefined(); + expect(received["x-poutine-signature"]).toBeUndefined(); }); }); @@ -582,93 +714,35 @@ describe("proxy — streaming passthrough", () => { describe("proxy — concurrency smoke test", () => { let setup: TestSetup; - let userId: string; beforeEach(async () => { - // Use a fake Navidrome that intentionally delays each response by 50ms - // so concurrent requests actually overlap in flight. - const requests: string[] = []; - const navidrome = await new Promise<{ server: http.Server; port: number; requests: string[] }>( - (resolve) => { - const server = http.createServer((_req, res) => { - requests.push(_req.url ?? ""); - // Delay response to ensure overlap - setTimeout(() => { - res.writeHead(200, { - "content-type": "audio/mpeg", - "content-length": String(FAKE_AUDIO.length), - }); - res.end(FAKE_AUDIO); - }, 50); - }); - server.listen(0, "127.0.0.1", () => { - resolve({ server, port: (server.address() as AddressInfo).port, requests }); - }); - }, - ); - - const keyPathApp = tmpPath("key-app-conc.pem"); - - const config: Partial = { - databasePath: ":memory:", - jwtSecret: "concurrency-test-secret", - poutinePrivateKeyPath: keyPathApp, - poutineInstanceId: "hub-concurrency-test", - navidromeUrl: `http://127.0.0.1:${navidrome.port}`, - navidromeUsername: "admin", - navidromePassword: "admin", - }; - - const app = await buildApp(config); - await app.ready(); - - // Reuse setup slot — override navidrome to the delaying one - setup = { - app, - navidrome: navidrome.server, - navidromePort: navidrome.port, - navidromeRequests: navidrome.requests, - keyPathA: "", - keyPathApp, - privKeyA: {} as KeyObject, - pubKeyBase64A: "", - }; - - ({ id: userId } = seedUser(app)); + // Each upstream response is held 50ms so concurrent requests actually + // overlap in flight. + setup = await buildTestSetup(50); }); afterEach(async () => { - await setup.app.close(); - await new Promise((resolve) => setup.navidrome.close(() => resolve())); - if (fs.existsSync(setup.keyPathApp)) fs.unlinkSync(setup.keyPathApp); + await teardown(setup); }); - it("handles 12 concurrent in-flight streams without blocking", async () => { - const token = await createAccessToken(userId, setup.app.config); - + it("handles 12 concurrent in-flight requests without blocking", async () => { const start = Date.now(); - // Fire 12 requests in parallel - const promises = Array.from({ length: 12 }, (_, i) => - setup.app.inject({ - method: "GET", - url: `/proxy/rest/stream?id=trk-${i}`, - headers: { authorization: `Bearer ${token}` }, - }), + const results = await Promise.all( + Array.from({ length: 12 }, (_, i) => + signedRequest(setup, `/proxy/rest/getCoverArt?id=al-${i}`), + ), ); - - const results = await Promise.all(promises); const elapsed = Date.now() - start; - // All should succeed for (const res of results) { expect(res.statusCode).toBe(200); } + expect(setup.navidromeRequests).toHaveLength(12); - // If streams were serialized (blocking), total time would be 12 × 50ms = 600ms+. - // With true concurrency they all overlap and finish in ~50ms + overhead. - // Allow generous budget (500ms) to account for slow CI, but serialized - // would take much longer. + // If requests were serialized (blocking), total time would be 12 × 50ms = + // 600ms+. With true concurrency they overlap and finish in ~50ms + + // overhead; the budget is generous for slow CI. expect(elapsed).toBeLessThan(1000); }); }); From 13f5882b58e81dc73445708ef96e0e479edd3a36 Mon Sep 17 00:00:00 2001 From: Nic Benders Date: Wed, 11 Nov 2026 16:57:28 -0800 Subject: [PATCH 2/3] docs: /proxy/* is peer-only with a read-only endpoint allowlist (#308) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - authentication.md: surface table + "Proxy auth" rewritten (who / what, refusal codes). - hub-internals.md: proxy contract — allowlist with the peer call site for each entry, match rules, forwarded headers. - system-architecture.md: auth table, federation route table, and the stream/art rows (peer audio is /federation/stream/:id, not the proxy). - pitfalls.md: rule against widening the proxy. - federation-api.md: peer-facing proxy surface; no version bump needed. - SECURITY.md: status note on the matching assessment finding. Co-Authored-By: Claude Fable 5.2 --- SECURITY.md | 5 +++++ docs/authentication.md | 25 +++++++++++++++++++------ docs/federation-api.md | 2 ++ docs/hub-internals.md | 29 +++++++++++++++++++---------- docs/pitfalls.md | 1 + docs/system-architecture.md | 8 ++++---- 6 files changed, 50 insertions(+), 20 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index c61dd1c..6e62175 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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. diff --git a/docs/authentication.md b/docs/authentication.md index 321f61b..8ca6567 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -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:`) **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) | @@ -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/` or `/proxy/rest/.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=…`) diff --git a/docs/federation-api.md b/docs/federation-api.md index 2bd2f2f..b8d9603 100644 --- a/docs/federation-api.md +++ b/docs/federation-api.md @@ -82,6 +82,8 @@ All errors return `{ "error": "" }`. 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/[.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) diff --git a/docs/hub-internals.md b/docs/hub-internals.md index 27e6297..029ca3a 100644 --- a/docs/hub-internals.md +++ b/docs/hub-internals.md @@ -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 | @@ -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:`) **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/[.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/` 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 diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 1786f42..4ce7d94 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -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 | diff --git a/docs/system-architecture.md b/docs/system-architecture.md index dccfa0a..9cd2ffe 100644 --- a/docs/system-architecture.md +++ b/docs/system-architecture.md @@ -36,7 +36,7 @@ flowchart TB sonos --> playerdb rest -- "audio bytes:
ranked sources, failover" --> fed fed -- "local source: Subsonic stream" --> navidrome - fed -- "peer source:
signed /proxy/rest/stream" --> peers + fed -- "peer source:
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). @@ -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. | @@ -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). @@ -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 | From 03d0e98974dfc064e252252e11601c39ed8daa84 Mon Sep 17 00:00:00 2001 From: Nic Benders Date: Wed, 11 Nov 2026 16:58:38 -0800 Subject: [PATCH 3/3] docs(pitfalls): federation suite can OOM a co-hosted live hub (#308) Observed while running the gate for this branch: the Docker VM ran out of memory with three test stacks up and the kernel killed a live hub. Co-Authored-By: Claude Fable 5.2 --- docs/pitfalls.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 4ce7d94..42643f1 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -165,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` |