Vellum/internal/playback/handlers.go
mithral ac1bd04df3 Phase 1: one item-access seam, and architecture rules that fail the build
Motivation, from the evidence rather than from taste. Five packages each
implemented "load an item, then check the caller may read it": media, comics,
games, jellyfin (with its own dbItem type and its own SQL), and subsonic. Five
copies of one authorization rule means four can drift, and the failure mode is
not a crash — it is silently serving somebody a library they were never granted.
One implementation is one thing to review.

internal/catalog now owns item and file access, and the access check.

  LoadUnchecked(ctx, db, id)        -- no access check; jobs and tests only
  LoadFor(ctx, db, u, id)           -- load AND enforce the grant, in one call
  Files / FilesFor / FileByID / FirstFile / FileCount

The unchecked variant is deliberately named so that reaching for it by accident
is hard: it is the dangerous call, so it should not have the friendlier name.
This came from the interface-design rule that a good interface makes the right
thing easy and the wrong thing hard.

The security property is tested, not asserted: a forbidden item and an absent
item return byte-identical errors, so no handler can leak the existence of
another user's library through a 403. That is now enforced in one place.

Migrated all five surfaces onto it. media, comics, games and ebooks went from
four duplicate loaders to zero. jellyfin's dbItem and loadDBItem are gone.
subsonic's per-item authorization moved while its album/artist aggregate
projections stayed put, because grouping items into albums is a presentation
concern, not a data-access one. The remaining raw SQL everywhere is browse and
aggregate queries; no per-item load decides access any more.

internal/arch enforces the layering instead of documenting it. Five rules, each
proven able to fail by deliberately breaking it:
  - no upward imports across six explicit layers
  - internal/core may depend only on migrations
  - internal/catalog must not know about HTTP, or it stops being reusable
  - modules must not import each other
  - every package must be placed in a layer, so the map cannot go stale

A test that only ever passes is decoration, so each rule was verified by
introducing the violation and confirming the failure.

Verified: gofmt clean, go build ./... exit 0, go vet exit 0, 20 packages pass,
svelte-check 0/0. End to end against a running server: the vellum API serves
item detail with codec facts, an unknown item 404s, Jellyfin AuthenticateByName
mints a token and /Items browses, and Subsonic ping returns status ok. The
subsonic migration was additionally A/B'd byte-identical against the previous
implementation across ~15 endpoints, and Jellyfin/Subsonic both still return the
same error for a forbidden item as for an absent one.

Known follow-ups, recorded rather than silently skipped:
  - internal/jellyfin has no test files at all. Its wire contract is the most
    client-visible surface in the tree and is now verified only by hand.
  - catalog is item-centric, but Subsonic addresses songs file-first (mf-<id>),
    so it resolves file to item through its own projection. A catalog lookup
    that takes a file id would close that.
  - subsonic loadAlbum now scopes the projection to the item's own library
    rather than all visible audio libraries. Equivalent by construction, since
    an item's kind tracks its library's kind, but a hand-edited mismatch would
    differ.
2026-10-11 15:47:18 -04:00

104 lines
3.7 KiB
Go

// Package playback exposes the server side of direct-play selection: the list
// of playback engines and the decision of whether a particular item can be
// direct-played by the engines a client declares.
//
// Vellum does not transcode. The server reports what is in each file (codec
// facts written by the scanner) and matches it against the client's declared
// engines; the client is the only party that knows its own hardware. The web
// app declares "html5"; a native client declares "mpv"/"vlc"/"mdk" as well.
package playback
import (
"database/sql"
"errors"
"log/slog"
"net/http"
"github.com/mithral/vellum/internal/auth"
"github.com/mithral/vellum/internal/catalog"
"github.com/mithral/vellum/internal/engine"
"github.com/mithral/vellum/internal/httpx"
)
// Handlers serves the playback selection endpoints.
type Handlers struct {
db *sql.DB
log *slog.Logger
auth *auth.Authenticator
}
// NewHandlers builds the playback HTTP layer.
func NewHandlers(db *sql.DB, log *slog.Logger, a *auth.Authenticator) *Handlers {
return &Handlers{db: db, log: log, auth: a}
}
// Register mounts the routes. Both require an authenticated user; the resolve
// endpoint additionally scopes to items the caller may read.
func (h *Handlers) Register(mux *http.ServeMux) {
mux.Handle("GET /api/v1/playback/engines", h.auth.Require(h.handleEngines))
mux.Handle("POST /api/v1/playback/resolve", h.auth.Require(h.handleResolve))
}
// handleEngines lists every engine the server knows about. A client uses this to
// show what it could offer and to name engines in a resolve request.
func (h *Handlers) handleEngines(w http.ResponseWriter, r *http.Request, u auth.User) {
httpx.WriteJSON(w, http.StatusOK, map[string]any{"engines": engine.All()})
}
// handleResolve answers whether the caller's client can direct-play an item.
//
// The body is {"item_id":N,"engines":["html5",...]}. The item's codec facts
// (container, vcodec, acodec) are read from the database and handed to
// engine.Resolve together with the client's declared engines.
func (h *Handlers) handleResolve(w http.ResponseWriter, r *http.Request, u auth.User) {
var req struct {
ItemID int64 `json:"item_id"`
Engines []string `json:"engines"`
}
if err := httpx.DecodeJSON(r, &req); err != nil {
httpx.WriteError(w, http.StatusBadRequest, err.Error())
return
}
if req.ItemID <= 0 {
httpx.WriteError(w, http.StatusBadRequest, "invalid item_id")
return
}
// catalog.LoadFor is the shared access-control chokepoint: it reads the
// item and confirms the caller may read its library, returning the same
// ErrNotFound for a missing item and an unreadable one. That keeps an
// inaccessible item a 404, never a 403, so its existence is not disclosed.
if _, err := catalog.LoadFor(r.Context(), h.db, u, req.ItemID); err != nil {
if errors.Is(err, catalog.ErrNotFound) {
httpx.WriteError(w, http.StatusNotFound, "item not found")
return
}
h.fail(w, "load item", err)
return
}
// The first file carries the codec facts the player will try. An item with
// no file cannot be played, but is still a 200 with a resolution so the UI
// has one shape to render.
f, err := catalog.FirstFile(r.Context(), h.db, req.ItemID)
if errors.Is(err, catalog.ErrNotFound) {
httpx.WriteJSON(w, http.StatusOK, engine.Resolution{
Playable: false,
Reason: "nofile",
Message: "This item has no file to play.",
})
return
}
if err != nil {
h.fail(w, "load file facts", err)
return
}
res := engine.Resolve(engine.Facts(f.Container, f.VCodec, f.ACodec), req.Engines)
httpx.WriteJSON(w, http.StatusOK, res)
}
func (h *Handlers) fail(w http.ResponseWriter, what string, err error) {
h.log.Error(what, "err", err)
httpx.WriteError(w, http.StatusInternalServerError, "internal server error")
}