diff --git a/internal/jellycompat/audio_selection_test.go b/internal/jellycompat/audio_selection_test.go index 4519df9f4ac..42dabc1b5d0 100644 --- a/internal/jellycompat/audio_selection_test.go +++ b/internal/jellycompat/audio_selection_test.go @@ -21,6 +21,7 @@ type testCompatSessionManager struct { sessions map[string]*playback.Session audioTrackCalls []compatAudioTrackCall progressCalls int + stopCalls []string } type compatAudioTrackCall struct { @@ -67,7 +68,10 @@ func (m *testCompatSessionManager) UpdateAudioTrack(sessionID string, audioTrack return nil } -func (m *testCompatSessionManager) StopSession(string) error { return nil } +func (m *testCompatSessionManager) StopSession(sessionID string) error { + m.stopCalls = append(m.stopCalls, sessionID) + return nil +} func (m *testCompatSessionManager) GetSession(sessionID string) (*playback.Session, error) { if session, ok := m.sessions[sessionID]; ok { diff --git a/internal/jellycompat/router.go b/internal/jellycompat/router.go index 148561786a9..17f74582a44 100644 --- a/internal/jellycompat/router.go +++ b/internal/jellycompat/router.go @@ -202,6 +202,7 @@ func NewRouter(deps Dependencies) chi.Router { r.Post("/Sessions/Playing", playbackHandler.HandleSessionPlaying) r.Post("/Sessions/Playing/Progress", playbackHandler.HandleSessionPlayingProgress) r.Post("/Sessions/Playing/Stopped", playbackHandler.HandleSessionPlayingStopped) + r.Delete("/Videos/ActiveEncodings", playbackHandler.HandleDeleteActiveEncodings) r.Post("/Sessions/Logout", authHandler.HandleLogout) r.Get("/socket", HandleSocket) }) diff --git a/internal/jellycompat/streams.go b/internal/jellycompat/streams.go index f7e6677d542..c78039c4794 100644 --- a/internal/jellycompat/streams.go +++ b/internal/jellycompat/streams.go @@ -672,6 +672,66 @@ func (h *PlaybackHandler) HandleSessionPlayingStopped(w http.ResponseWriter, r * h.handlePlaybackReport(w, r, true) } +// HandleDeleteActiveEncodings handles DELETE /Videos/ActiveEncodings. +// +// Jellyfin clients (e.g. JellyCon) call this endpoint when playback stops to +// signal the server to tear down any running HLS transcode for the session. +// Without it, the transcode process keeps running until the playback session +// TTL expires (default 6 h). We honour the request by stopping the transcode +// identified by the playSessionId query parameter. +func (h *PlaybackHandler) HandleDeleteActiveEncodings(w http.ResponseWriter, r *http.Request) { + session := SessionFromContext(r.Context()) + if session == nil { + w.WriteHeader(http.StatusNoContent) + return + } + q := newCaseInsensitiveQuery(r.URL.Query()) + // DeviceId is intentionally ignored: Silo's playback store is keyed by + // PlaySessionId, clients always send it, and Jellyfin's own teardown matches + // by playSessionId (ignoring deviceId) whenever playSessionId is non-empty. + playSessionID := q.Get("PlaySessionId") + if playSessionID == "" { + w.WriteHeader(http.StatusNoContent) + return + } + + // Ownership guard (mirrors the Stopped report path): only the session's own + // caller may tear it down, and a session with no upstream transcode yet has + // nothing to tear down. The PlaybackSession is created by PlaybackInfo with + // an empty UpstreamSessionID; it is only populated once the first manifest + // request reaches ensureUpstreamPlayback. Deleting it before then would drop + // a live session and 404 the pending manifest, so an unknown, not-owned, or + // not-yet-started PlaySessionId is a uniform idempotent 204 no-op (no + // cross-session teardown, no ownership oracle, no premature deletion). + playSession, ok := h.playbackStore.Get(playSessionID) + if !ok || playSession.CompatToken != session.Token || playSession.UpstreamSessionID == "" { + w.WriteHeader(http.StatusNoContent) + return + } + + h.teardownPlaySession(playSession) + + w.WriteHeader(http.StatusNoContent) +} + +// teardownPlaySession stops the upstream playback session and removes the compat +// play session from the store. Every step is idempotent, so it is safe to call +// from both the explicit ActiveEncodings teardown and a Stopped playback report +// (which may race). It is a no-op-safe teardown for an already-gone session. +func (h *PlaybackHandler) teardownPlaySession(playSession *PlaybackSession) { + transcodeNodeURL := "" + if h.sessionMgr != nil { + if upstreamSession, err := h.sessionMgr.GetSession(playSession.UpstreamSessionID); err == nil { + transcodeNodeURL = upstreamSession.TranscodeNodeURL + } + } + h.closeTranscodeSession(playSession.UpstreamSessionID, transcodeNodeURL) + if h.sessionMgr != nil { + _ = h.sessionMgr.StopSession(playSession.UpstreamSessionID) + } + h.playbackStore.Delete(playSession.ID) +} + func (h *PlaybackHandler) handlePlaybackReport(w http.ResponseWriter, r *http.Request, stop bool) { session := SessionFromContext(r.Context()) if session == nil { @@ -755,17 +815,7 @@ func (h *PlaybackHandler) handlePlaybackReport(w http.ResponseWriter, r *http.Re } } if stop { - transcodeNodeURL := "" - if h.sessionMgr != nil { - if upstreamSession, err := h.sessionMgr.GetSession(playSession.UpstreamSessionID); err == nil { - transcodeNodeURL = upstreamSession.TranscodeNodeURL - } - } - h.closeTranscodeSession(playSession.UpstreamSessionID, transcodeNodeURL) - if h.sessionMgr != nil { - _ = h.sessionMgr.StopSession(playSession.UpstreamSessionID) - } - h.playbackStore.Delete(playSession.ID) + h.teardownPlaySession(playSession) } w.WriteHeader(http.StatusNoContent) diff --git a/internal/jellycompat/streams_test.go b/internal/jellycompat/streams_test.go index dd871338c36..38c7e6e9006 100644 --- a/internal/jellycompat/streams_test.go +++ b/internal/jellycompat/streams_test.go @@ -1,10 +1,22 @@ package jellycompat import ( + "context" + "net/http" + "net/http/httptest" "strings" "testing" + "time" + + "github.com/Silo-Server/silo-server/internal/playback" ) +// withCompatSession attaches a compat session carrying tok to req, so the +// ActiveEncodings ownership guard (CompatToken == session.Token) is satisfied. +func withCompatSession(req *http.Request, tok string) *http.Request { + return req.WithContext(context.WithValue(req.Context(), compatSessionKey, &Session{Token: tok})) +} + func TestAudioSelectionChanged(t *testing.T) { selected := 2 session := &PlaybackSession{ @@ -90,3 +102,173 @@ func TestRewriteManifest_PreservesPlaybackAndMediaSourceIDs(t *testing.T) { t.Fatalf("expected nested manifest to include media and playback session ids, got:\n%s", got) } } + +// newActiveEncodingsHandler builds a PlaybackHandler literal directly (not +// NewPlaybackHandler, which touches the filesystem) with the transcodes map +// initialized — closeTranscodeSession writes/deletes it and would nil-map-panic +// otherwise. +func newActiveEncodingsHandler(mgr *testCompatSessionManager) (*PlaybackHandler, *PlaybackSessionStore) { + store := NewPlaybackSessionStore(time.Hour, nil) + h := &PlaybackHandler{ + playbackStore: store, + sessionMgr: mgr, + transcodes: make(map[string]*playback.TranscodeSession), + } + return h, store +} + +// TestHandleDeleteActiveEncodings_StopsTranscodeAndDeletesSession verifies the +// happy path: the upstream session is stopped and the compat play session is +// removed from the store, returning 204. +func TestHandleDeleteActiveEncodings_StopsTranscodeAndDeletesSession(t *testing.T) { + mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}} + h, store := newActiveEncodingsHandler(mgr) + store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"}) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=ps-1", nil), "tok") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if _, ok := store.Get("ps-1"); ok { + t.Fatal("play session should be deleted") + } + if len(mgr.stopCalls) != 1 || mgr.stopCalls[0] != "upstream-1" { + t.Fatalf("expected StopSession(upstream-1); got %v", mgr.stopCalls) + } +} + +// TestHandleDeleteActiveEncodings_MissingPlaySessionIdReturns204 verifies a +// request with no PlaySessionId is a 204 no-op (no teardown). +func TestHandleDeleteActiveEncodings_MissingPlaySessionIdReturns204(t *testing.T) { + mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}} + h, store := newActiveEncodingsHandler(mgr) + store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"}) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings", nil), "tok") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if _, ok := store.Get("ps-1"); !ok { + t.Fatal("unrelated play session must not be torn down") + } + if len(mgr.stopCalls) != 0 { + t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls) + } +} + +// TestHandleDeleteActiveEncodings_UnknownPlaySessionReturns204 verifies an +// unknown PlaySessionId is a 204 no-op (idempotent "already gone" semantics). +func TestHandleDeleteActiveEncodings_UnknownPlaySessionReturns204(t *testing.T) { + mgr := &testCompatSessionManager{} + h, _ := newActiveEncodingsHandler(mgr) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=does-not-exist", nil), "tok") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if len(mgr.stopCalls) != 0 { + t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls) + } +} + +// TestHandleDeleteActiveEncodings_CaseInsensitivePlaySessionId verifies a +// lowercase playSessionId key (as Wholphin sends) still resolves and tears down +// the session — the reason newCaseInsensitiveQuery is used. +func TestHandleDeleteActiveEncodings_CaseInsensitivePlaySessionId(t *testing.T) { + mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}} + h, store := newActiveEncodingsHandler(mgr) + store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"}) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?playSessionId=ps-1", nil), "tok") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if _, ok := store.Get("ps-1"); ok { + t.Fatal("lowercase playSessionId should still resolve and delete the session") + } +} + +// TestHandleDeleteActiveEncodings_ForeignPlaySessionNotTornDown proves the +// ownership guard: a caller whose token differs from the play session's +// CompatToken gets a uniform 204 no-op and does NOT tear down the foreign +// session (no cross-session IDOR teardown). +func TestHandleDeleteActiveEncodings_ForeignPlaySessionNotTornDown(t *testing.T) { + mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}} + h, store := newActiveEncodingsHandler(mgr) + store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "owner"}) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=ps-1", nil), "attacker") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if _, ok := store.Get("ps-1"); !ok { + t.Fatal("foreign play session must not be torn down") + } + if len(mgr.stopCalls) != 0 { + t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls) + } +} + +// TestHandleDeleteActiveEncodings_RealClientShape exercises the dominant real +// JellyCon call shape (DeviceId present alongside PlaySessionId): with a +// matching-token session the session is still torn down (DeviceId ignored). +func TestHandleDeleteActiveEncodings_RealClientShape(t *testing.T) { + mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}} + h, store := newActiveEncodingsHandler(mgr) + store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"}) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?DeviceId=dev1&PlaySessionId=ps-1", nil), "tok") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if _, ok := store.Get("ps-1"); ok { + t.Fatal("play session should be torn down when DeviceId accompanies a matching PlaySessionId") + } + if len(mgr.stopCalls) != 1 || mgr.stopCalls[0] != "upstream-1" { + t.Fatalf("expected StopSession(upstream-1); got %v", mgr.stopCalls) + } +} + +// TestHandleDeleteActiveEncodings_NotYetStartedNotTornDown guards the early +// window between PlaybackInfo and the first manifest request, when the play +// session exists but UpstreamSessionID is still empty. A DELETE that lands then +// must be a 204 no-op that leaves the session in the store, so the pending +// manifest request still resolves (mirrors the Stopped report path). Removing +// the UpstreamSessionID == "" guard makes this test fail. +func TestHandleDeleteActiveEncodings_NotYetStartedNotTornDown(t *testing.T) { + mgr := &testCompatSessionManager{} + h, store := newActiveEncodingsHandler(mgr) + store.Put(PlaybackSession{ID: "ps-1", CompatToken: "tok"}) + + req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=ps-1", nil), "tok") + rec := httptest.NewRecorder() + h.HandleDeleteActiveEncodings(rec, req) + + if rec.Code != 204 { + t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String()) + } + if _, ok := store.Get("ps-1"); !ok { + t.Fatal("not-yet-started play session must survive teardown so the pending manifest still resolves") + } + if len(mgr.stopCalls) != 0 { + t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls) + } +}