package hlsgate import ( "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "sync" "sync/atomic" "testing" "time" "drmdecryption/apps/streamd/internal/auth" "drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/tsfanout" ) // fakeSup records what the gate asked for, and can pretend a stream comes up. type fakeSup struct { mu sync.Mutex starts int32 stops int32 running map[int64]bool onStart func(id int64) startErr error } func newFakeSup() *fakeSup { return &fakeSup{running: map[int64]bool{}} } func (f *fakeSup) Start(id int64) error { atomic.AddInt32(&f.starts, 1) if f.startErr != nil { return f.startErr } f.mu.Lock() f.running[id] = true cb := f.onStart f.mu.Unlock() if cb != nil { cb(id) } return nil } func (f *fakeSup) Stop(id int64) error { atomic.AddInt32(&f.stops, 1) f.mu.Lock() f.running[id] = false f.mu.Unlock() return nil } func (f *fakeSup) Running(id int64) bool { f.mu.Lock() defer f.mu.Unlock() return f.running[id] } type fakeCapture struct{ n int32 } func (c *fakeCapture) RequestCapture(st db.Stream, reason string) int { atomic.AddInt32(&c.n, 1) return 1 } func newTestGate(t *testing.T) (*Gate, *db.Store, *fakeSup, string) { t.Helper() dir := t.TempDir() store, err := db.Open(filepath.Join(dir, "db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = store.Close() }) www := filepath.Join(dir, "www") if err := os.MkdirAll(www, 0o755); err != nil { t.Fatal(err) } sup := newFakeSup() g := New(Config{ Store: store, WWWRoot: www, Sup: sup, Fanout: tsfanout.NewSet(1 << 16), Wait: 2 * time.Second, }) return g, store, sup, www } func mkStream(t *testing.T, store *db.Store, in db.CreateStream) db.Stream { t.Helper() st, err := store.CreateStream(in) if err != nil { t.Fatal(err) } return st } func writeFile(t *testing.T, path, body string) { t.Helper() if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte(body), 0o644); err != nil { t.Fatal(err) } } const livePlaylist = "#EXTM3U\n#EXT-X-VERSION:3\n#EXTINF:4.0,\nseg_00001.ts\n" // ---------- path resolution ---------- // A stream name may contain a dash, so "city-news-hd" must resolve as the // "hd" rung of "city-news", while "city-news" resolves as its own source rung. func TestResolveStreamNamesContainingDashes(t *testing.T) { g, store, _, _ := newTestGate(t) variants, err := db.EncodeVariantsJSON([]db.VariantSpec{ {ID: db.SourceVariantID, Enabled: true}, {ID: "hd", Enabled: true, Height: 720}, }) if err != nil { t.Fatal(err) } mkStream(t, store, db.CreateStream{Name: "city-news", VariantsJSON: variants}) mkStream(t, store, db.CreateStream{Name: "city", VariantsJSON: variants}) // A stream whose literal name ends in -hd must win over being read as a // rung of another stream. mkStream(t, store, db.CreateStream{Name: "sport-hd"}) cases := []struct { dir string wantStream string wantVariant string }{ {"city-news", "city-news", db.SourceVariantID}, {"city-news-hd", "city-news", "hd"}, {"city", "city", db.SourceVariantID}, {"city-hd", "city", "hd"}, {"sport-hd", "sport-hd", db.SourceVariantID}, } for _, c := range cases { st, v, err := g.resolve(c.dir) if err != nil { t.Errorf("resolve(%q) failed: %v", c.dir, err) continue } if st.Name != c.wantStream || v.ID != c.wantVariant { t.Errorf("resolve(%q) = %s/%s, want %s/%s", c.dir, st.Name, v.ID, c.wantStream, c.wantVariant) } } for _, bad := range []string{"", "nope", "city-news-4k", "city-news-hd-extra"} { if _, _, err := g.resolve(bad); err == nil { t.Errorf("resolve(%q) should have failed", bad) } } } // ---------- traversal ---------- func TestPathTraversalRejected(t *testing.T) { g, store, _, www := newTestGate(t) mkStream(t, store, db.CreateStream{Name: "news"}) // A secret outside the media root, as a credible target. writeFile(t, filepath.Join(filepath.Dir(www), "streamd.db"), "SECRET") writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) srv := httptest.NewServer(http.HandlerFunc(g.serveHLS)) defer srv.Close() for _, p := range []string{ "/hls/news/../../streamd.db", "/hls/news/..%2f..%2fstreamd.db", "/hls/news/%2e%2e/%2e%2e/streamd.db", "/hls/news/....//....//streamd.db", "/hls/../streamd.db", } { req, err := http.NewRequest(http.MethodGet, srv.URL+p, nil) if err != nil { t.Fatal(err) } resp, err := http.DefaultTransport.RoundTrip(req) if err != nil { continue } body := make([]byte, 64) n, _ := resp.Body.Read(body) _ = resp.Body.Close() if resp.StatusCode == http.StatusOK && string(body[:n]) == "SECRET" { t.Errorf("traversal succeeded for %q", p) } } } func TestDirectoryListingRefused(t *testing.T) { g, store, _, www := newTestGate(t) mkStream(t, store, db.CreateStream{Name: "news"}) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) for _, p := range []string{"/hls/", "/hls/news/", "/hls/news"} { rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, p, nil)) if rec.Code == http.StatusOK { t.Errorf("%s returned 200; a listing would enumerate every stream", p) } } } // ---------- serving ---------- func TestServesExistingPlaylistWithCacheHeaders(t *testing.T) { g, store, _, www := newTestGate(t) mkStream(t, store, db.CreateStream{Name: "news"}) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) writeFile(t, filepath.Join(www, "news", "seg_00001.ts"), "mediabytes") rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)) if rec.Code != http.StatusOK { t.Fatalf("playlist: %d %s", rec.Code, rec.Body.String()) } if ct := rec.Header().Get("Content-Type"); ct != "application/vnd.apple.mpegurl" { t.Errorf("playlist content type = %q", ct) } // A live playlist must not be cached, or viewers stick on a stale window. if cc := rec.Header().Get("Cache-Control"); cc == "" || !contains(cc, "no-cache") { t.Errorf("playlist cache-control = %q, want no-cache", cc) } rec = httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00001.ts", nil)) if rec.Code != http.StatusOK { t.Fatalf("segment: %d", rec.Code) } // A segment never changes under its name, so it is cacheable forever. if cc := rec.Header().Get("Cache-Control"); !contains(cc, "immutable") { t.Errorf("segment cache-control = %q, want immutable", cc) } } func contains(h, needle string) bool { return len(h) >= len(needle) && (h == needle || indexOf(h, needle) >= 0) } func indexOf(h, needle string) int { for i := 0; i+len(needle) <= len(h); i++ { if h[i:i+len(needle)] == needle { return i } } return -1 } // ---------- on-demand wake ---------- func TestWakeStartsStreamAndServesOnceReady(t *testing.T) { g, store, sup, www := newTestGate(t) on := true st := mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, }) // The supervisor "starts" by producing a playlist, as the real one does. sup.onStart = func(id int64) { go func() { time.Sleep(150 * time.Millisecond) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) }() } rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)) if rec.Code != http.StatusOK { t.Fatalf("want the request held until ready, got %d %s", rec.Code, rec.Body.String()) } if got := atomic.LoadInt32(&sup.starts); got != 1 { t.Errorf("starts = %d, want 1", got) } // The wake must be on the stream's timeline. _ = store.FlushHistory() events, err := store.ListEvents(st.ID, 20, db.EventOnDemandWake, "") if err != nil || len(events) == 0 { t.Errorf("expected an ondemand_wake event, got %v (%v)", events, err) } } // Twenty viewers arriving together must produce one start, not twenty. func TestWakeIsSingleFlight(t *testing.T) { g, store, sup, www := newTestGate(t) on := true mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, }) var once sync.Once sup.onStart = func(id int64) { once.Do(func() { go func() { time.Sleep(200 * time.Millisecond) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) }() }) } const clients = 20 var wg sync.WaitGroup codes := make([]int, clients) for i := 0; i < clients; i++ { wg.Add(1) go func(i int) { defer wg.Done() rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil) // Distinct client addresses, so the per-IP wake limiter does not // mask the single-flight behaviour being tested. req.RemoteAddr = fmt.Sprintf("10.0.0.%d:1234", i+1) g.serveHLS(rec, req) codes[i] = rec.Code }(i) } wg.Wait() if got := atomic.LoadInt32(&sup.starts); got != 1 { t.Errorf("concurrent wakes started the stream %d times, want exactly 1", got) } for i, c := range codes { if c != http.StatusOK { t.Errorf("client %d got %d, want 200", i, c) } } } func TestWakeTimesOutWithRetryAfter(t *testing.T) { g, store, sup, _ := newTestGate(t) g.Wait = 300 * time.Millisecond on := true mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, }) // Starts, but never produces media. sup.onStart = func(id int64) {} rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)) if rec.Code != http.StatusServiceUnavailable { t.Errorf("want 503 when the stream does not come up, got %d", rec.Code) } if ra := rec.Header().Get("Retry-After"); ra == "" { t.Error("a 503 should carry Retry-After so players back off sensibly") } } // A stream that is not marked on-demand must never be started by a request. func TestNonOnDemandStreamIsNotWoken(t *testing.T) { g, store, sup, _ := newTestGate(t) yes := true no := false mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &no, Enabled: &yes, }) rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)) if rec.Code != http.StatusNotFound { t.Errorf("want 404, got %d", rec.Code) } if got := atomic.LoadInt32(&sup.starts); got != 0 { t.Errorf("a non-on-demand stream was started %d times", got) } } // Only a playlist may wake a stream. Starting one to serve a specific old // segment would not produce that segment anyway. func TestSegmentRequestDoesNotWake(t *testing.T) { g, store, sup, _ := newTestGate(t) on := true mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, }) rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/seg_00042.ts", nil)) if rec.Code != http.StatusNotFound { t.Errorf("want 404 for a segment on a stopped stream, got %d", rec.Code) } if got := atomic.LoadInt32(&sup.starts); got != 0 { t.Errorf("a segment request woke the stream %d times", got) } } // An empty playlist makes a player give up, so the gate must keep waiting // until a segment is listed. func TestWakeWaitsForASegmentNotJustAFile(t *testing.T) { g, store, sup, www := newTestGate(t) g.Wait = 2 * time.Second on := true mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, }) sup.onStart = func(id int64) { go func() { // First an empty playlist, as ffmpeg briefly writes... writeFile(t, filepath.Join(www, "news", "index.m3u8"), "#EXTM3U\n#EXT-X-VERSION:3\n") time.Sleep(300 * time.Millisecond) // ...then one with a segment. writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) }() } start := time.Now() rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)) if rec.Code != http.StatusOK { t.Fatalf("got %d", rec.Code) } if time.Since(start) < 250*time.Millisecond { t.Error("served an empty playlist instead of waiting for a segment") } if !contains(rec.Body.String(), "#EXTINF") { t.Error("served playlist has no segment") } } // A woken stream with stale credentials must trigger a capture push, not wait // for the agent's next poll. func TestWakeRequestsCaptureWhenCredentialsAreStale(t *testing.T) { g, store, sup, _ := newTestGate(t) capReq := &fakeCapture{} g.Capture = capReq g.Wait = 200 * time.Millisecond // needs_capture switches the gate to the longer CaptureWait deadline, so // that is the one this test has to shorten. g.CaptureWait = 300 * time.Millisecond on := true // Enabled, on-demand, DRM required but no key: needs_capture is true. mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, DRMMode: db.DRMYes, }) sup.onStart = func(id int64) {} rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil)) if got := atomic.LoadInt32(&capReq.n); got != 1 { t.Errorf("capture requests = %d, want 1", got) } _ = rec } // ---------- access control ---------- func TestPrivateStreamNeedsAPrincipal(t *testing.T) { g, store, _, www := newTestGate(t) no := false mkStream(t, store, db.CreateStream{Name: "internal", Public: &no}) writeFile(t, filepath.Join(www, "internal", "index.m3u8"), livePlaylist) rec := httptest.NewRecorder() g.serveHLS(rec, httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil)) if rec.Code != http.StatusUnauthorized { t.Errorf("a private stream should need auth, got %d", rec.Code) } // With a principal attached it is served. req := httptest.NewRequest(http.MethodGet, "/hls/internal/index.m3u8", nil) req = req.WithContext(auth.WithPrincipal(req.Context(), &auth.Principal{Kind: auth.ActorUser, Role: auth.RoleViewer, Name: "op"})) rec = httptest.NewRecorder() g.serveHLS(rec, req) if rec.Code != http.StatusOK { t.Errorf("an authenticated request should be served, got %d", rec.Code) } } // ---------- viewers ---------- func TestViewerCountIsDistinctClientsNotRequests(t *testing.T) { g, store, _, www := newTestGate(t) mkStream(t, store, db.CreateStream{Name: "news"}) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) // One client, many requests: still one viewer. for i := 0; i < 10; i++ { req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil) req.RemoteAddr = "198.51.100.7:4000" g.serveHLS(httptest.NewRecorder(), req) } if got := g.ViewersFor("news"); got != 1 { t.Errorf("viewers = %d after 10 requests from one client, want 1", got) } // Three clients: three viewers. for _, ip := range []string{"198.51.100.8:1", "198.51.100.9:1"} { req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil) req.RemoteAddr = ip g.serveHLS(httptest.NewRecorder(), req) } if got := g.ViewersFor("news"); got != 3 { t.Errorf("viewers = %d, want 3", got) } if got := g.ViewersFor("nosuchstream"); got != 0 { t.Errorf("unknown stream viewers = %d, want 0", got) } } // ---------- idle stop ---------- func TestIdleSweepStopsUnwatchedOnDemandStream(t *testing.T) { g, store, sup, www := newTestGate(t) on := true idle := 1 // one second st := mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle, }) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) sup.running[st.ID] = true // A viewer arrives, so it is not idle yet. req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil) req.RemoteAddr = "203.0.113.5:9" g.serveHLS(httptest.NewRecorder(), req) g.sweepIdle() if got := atomic.LoadInt32(&sup.stops); got != 0 { t.Fatalf("stopped a stream that was just requested (%d stops)", got) } // Let the idle window pass. time.Sleep(1100 * time.Millisecond) g.sweepIdle() if got := atomic.LoadInt32(&sup.stops); got != 1 { t.Errorf("stops = %d, want 1 after the idle window", got) } _ = store.FlushHistory() events, _ := store.ListEvents(st.ID, 20, db.EventIdleStop, "") if len(events) == 0 { t.Error("expected an idle_stop event on the timeline") } } // A stream started by hand or by a schedule must not be stopped by the idle // sweep just because nobody has pulled it through the gate. func TestIdleSweepLeavesManuallyStartedStreams(t *testing.T) { g, store, sup, _ := newTestGate(t) on := true idle := 1 st := mkStream(t, store, db.CreateStream{ Name: "council", MPD: "https://origin.test/a.mpd", OnDemand: &on, Enabled: &on, IdleTimeoutS: &idle, }) sup.running[st.ID] = true time.Sleep(1100 * time.Millisecond) g.sweepIdle() if got := atomic.LoadInt32(&sup.stops); got != 0 { t.Errorf("stopped a stream that was never requested through the gate (%d stops)", got) } } // An always-on stream is never stopped for being idle. func TestIdleSweepIgnoresAlwaysOnStreams(t *testing.T) { g, store, sup, www := newTestGate(t) yes := true no := false idle := 1 st := mkStream(t, store, db.CreateStream{ Name: "news", MPD: "https://origin.test/a.mpd", OnDemand: &no, Enabled: &yes, IdleTimeoutS: &idle, }) writeFile(t, filepath.Join(www, "news", "index.m3u8"), livePlaylist) sup.running[st.ID] = true req := httptest.NewRequest(http.MethodGet, "/hls/news/index.m3u8", nil) req.RemoteAddr = "203.0.113.6:9" g.serveHLS(httptest.NewRecorder(), req) time.Sleep(1100 * time.Millisecond) g.sweepIdle() if got := atomic.LoadInt32(&sup.stops); got != 0 { t.Errorf("an always-on stream was idle-stopped (%d stops)", got) } } // ---------- progressive TS ---------- func TestLiveTSRequiresTheOutputToBeEnabled(t *testing.T) { g, store, _, _ := newTestGate(t) // Default outputs are HLS only, so /live/ must refuse. mkStream(t, store, db.CreateStream{Name: "news"}) rec := httptest.NewRecorder() g.serveLive(rec, httptest.NewRequest(http.MethodGet, "/live/news.ts", nil)) if rec.Code != http.StatusNotFound { t.Errorf("want 404 when the TS output is off, got %d", rec.Code) } } func TestLiveTSServesFromTheRing(t *testing.T) { g, store, _, _ := newTestGate(t) outputs, err := db.EncodeOutputsJSON([]db.OutputSpec{ {ID: "hls", Format: db.FormatHLS, Enabled: true}, {ID: "ts", Format: db.FormatTS, Enabled: true}, }) if err != nil { t.Fatal(err) } mkStream(t, store, db.CreateStream{Name: "news", OutputsJSON: outputs}) ring := g.Fanout.Create("news") // A PAT packet so a joining reader has a decodable starting point. pkt := make([]byte, 188) pkt[0] = 0x47 pkt[3] = 0x10 for i := 4; i < 188; i++ { pkt[i] = 0xAB } _, _ = ring.Write(pkt) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/live/news.ts", nil) // Close the ring shortly so the handler returns rather than streaming // forever. go func() { time.Sleep(100 * time.Millisecond) _ = ring.Close() }() g.serveLive(rec, req) if rec.Code != http.StatusOK { t.Fatalf("got %d: %s", rec.Code, rec.Body.String()) } if ct := rec.Header().Get("Content-Type"); ct != "video/mp2t" { t.Errorf("content type = %q, want video/mp2t", ct) } if rec.Body.Len() == 0 { t.Error("no media was written to the client") } } func TestLiveTSRejectsOddPaths(t *testing.T) { g, store, _, _ := newTestGate(t) mkStream(t, store, db.CreateStream{Name: "news"}) for _, p := range []string{"/live/", "/live/news", "/live/news.m3u8", "/live/../x.ts", "/live/a/b.ts"} { rec := httptest.NewRecorder() g.serveLive(rec, httptest.NewRequest(http.MethodGet, p, nil)) if rec.Code == http.StatusOK { t.Errorf("%s returned 200", p) } } }