package api import ( "encoding/json" "errors" "io" "log/slog" "net/http" "strconv" "strings" "time" "drmdecryption/apps/streamd/internal/auth" "drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/deps" "drmdecryption/apps/streamd/internal/httpx" ) type Supervisor interface { Start(id int64) error Stop(id int64) error Restart(id int64) error } // CaptureRequester asks connected agents to refresh a stream's credentials // now, rather than on their next poll. Implemented by the websocket hub. type CaptureRequester interface { RequestCapture(st db.Stream, reason string) int } // Viewers reports the live client count per stream, from the HLS gate. type Viewers interface { ViewersFor(streamName string) int } // Notifier pushes change notifications to dashboards and agents. type Notifier interface { NotifyStreamChanged(name, reason string) } // Scheduler exposes the upcoming schedule for the dashboard. type Scheduler interface { Upcoming(limit int) any } type Handler struct { Store *db.Store Auth *auth.Store Trust httpx.Trust Supervisor Supervisor Capture CaptureRequester Viewers Viewers Notifier Notifier Scheduler Scheduler StartedAt time.Time Deps deps.Status WWWRoot string // data/www — used to report variant playlist health LogRoot string // data/logs — source for the log tail endpoints Log *slog.Logger } func (h *Handler) Mount(mux *http.ServeMux) { mux.HandleFunc("/api/health", h.health) mux.HandleFunc("/api/streams", h.streams) mux.HandleFunc("/api/streams/", h.streamAction) mux.HandleFunc("/api/overview", h.overview) h.MountControl(mux) mux.HandleFunc("/api/apps", h.apps) mux.HandleFunc("/api/modules", h.modules) mux.HandleFunc("/api/modules/", h.modules) } func (h *Handler) logger() *slog.Logger { if h.Log != nil { return h.Log } return slog.Default() } // audit records a mutating request against the caller. func (h *Handler) audit(r *http.Request, p *auth.Principal, status int, note string) { if h.Auth == nil { return } h.Auth.AuditRequest(p, h.Trust, r, status, note) } // health is the one route that stays readable without a principal: a reverse // proxy and a container orchestrator both need it for liveness checks. It // deliberately reveals nothing but liveness and whether the media tools are // present — no stream names, no paths. func (h *Handler) health(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { writeErr(w, http.StatusMethodNotAllowed, "method not allowed") return } out := map[string]any{ "ok": true, "service": "streamd", "uptime_s": time.Since(h.StartedAt).Seconds(), "started_at": h.StartedAt.UTC().Format(time.RFC3339), } // Tool paths are filesystem layout, so only an authenticated caller gets // them. Anonymous callers still get a usable liveness answer. if p := auth.From(r); p != nil { out["deps"] = h.Deps out["role"] = string(p.Role) } else { out["deps"] = h.Deps.Public() } writeJSON(w, http.StatusOK, out) } func (h *Handler) streams(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: // Reading the stream list now requires a principal. It used to be // open, and it carries manifest URLs and (before redaction) keys. if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { return } list, err := h.Store.ListStreams() if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } if list == nil { list = []db.Stream{} } for i := range list { h.enrich(&list[i]) // The list is never a place for credentials, whatever the role: // it is the response the agent polls and the dashboard renders. list[i].Redact() } writeJSON(w, http.StatusOK, map[string]any{"streams": list}) case http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } var in db.CreateStream if err := readJSON(r, &in); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } st, err := h.Store.CreateStream(in) if err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } h.audit(r, p, http.StatusCreated, "created stream "+st.Name) h.logger().Info("stream created", "stream", st.Name, "by", p.Actor()) h.enrich(&st) h.notify(st.Name, "created") writeJSON(w, http.StatusCreated, st.Redacted()) default: writeErr(w, http.StatusMethodNotAllowed, "method not allowed") } } func (h *Handler) streamAction(w http.ResponseWriter, r *http.Request) { path := strings.TrimPrefix(r.URL.Path, "/api/streams/") path = strings.Trim(path, "/") if path == "" { h.streams(w, r) return } parts := strings.Split(path, "/") id, err := strconv.ParseInt(parts[0], 10, 64) if err != nil { writeErr(w, http.StatusBadRequest, "invalid id") return } action := "" if len(parts) > 1 { action = parts[1] } sub := "" if len(parts) > 2 { sub = parts[2] } switch { case action == "events" && r.Method == http.MethodPost: h.postEvent(w, r, id) return case action == "events" && r.Method == http.MethodGet: h.listEvents(w, r, id) return case action == "metrics" && r.Method == http.MethodGet: h.listMetrics(w, r, id) return case action == "logs" && sub == "stream" && r.Method == http.MethodGet: h.streamLogsSSE(w, r, id) return case action == "logs" && r.Method == http.MethodGet: h.streamLogs(w, r, id) return case action == "schedules": h.streamSchedules(w, r, id) return case action == "duplicate" && r.Method == http.MethodPost: h.duplicate(w, r, id) return case action == "probe" && r.Method == http.MethodPost: h.probe(w, r, id) return } switch { case action == "" && r.Method == http.MethodGet: p, ok := auth.Guard(w, r, auth.RoleViewer) if !ok { return } st, err := h.Store.GetStream(id) if err != nil { writeErr(w, http.StatusNotFound, "not found") return } h.enrich(&st) // Credentials come back only for an operator who explicitly asks, and // asking is recorded. reveal := truthy(r.URL.Query().Get("reveal")) if reveal && p.Role.AtLeast(auth.RoleOperator) { h.audit(r, p, http.StatusOK, "revealed credentials for stream "+st.Name) h.logger().Info("credentials revealed", "stream", st.Name, "by", p.Actor()) writeJSON(w, http.StatusOK, st) return } if reveal { // Say so rather than silently returning a blank key. writeErr(w, http.StatusForbidden, "role "+string(p.Role)+" cannot reveal credentials (needs operator)") return } writeJSON(w, http.StatusOK, st.Redacted()) case action == "" && (r.Method == http.MethodPatch || r.Method == http.MethodPut): p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } var in db.PatchStream if err := readJSON(r, &in); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } before, _ := h.Store.GetStream(id) st, err := h.Store.PatchStream(id, in) if err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } h.audit(r, p, http.StatusOK, "edited stream "+st.Name+changeNote(before, st, in)) // Editing mpd/key/headers/variants must tear down the live media worker // and bring up a fresh instance with the new credentials. if h.Supervisor != nil && credentialsChanged(before, st, in) { if st.Enabled { _ = h.Supervisor.Restart(id) } else { _ = h.Supervisor.Stop(id) } st, _ = h.Store.GetStream(id) } h.enrich(&st) h.notify(st.Name, "patched") writeJSON(w, http.StatusOK, st.Redacted()) case action == "" && r.Method == http.MethodDelete: p, ok := auth.Guard(w, r, auth.RoleAdmin) if !ok { return } before, _ := h.Store.GetStream(id) if h.Supervisor != nil { _ = h.Supervisor.Stop(id) } if err := h.Store.DeleteStream(id); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } h.audit(r, p, http.StatusOK, "deleted stream "+before.Name) h.logger().Info("stream deleted", "stream", before.Name, "by", p.Actor()) h.notify(before.Name, "deleted") writeJSON(w, http.StatusOK, map[string]any{"ok": true}) case action == "start" && r.Method == http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } st, err := h.Store.SetEnabled(id, true) if err != nil { writeErr(w, http.StatusNotFound, err.Error()) return } h.audit(r, p, http.StatusOK, "started stream "+st.Name) if h.Supervisor != nil { if err := h.Supervisor.Start(id); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } st, _ = h.Store.GetStream(id) } h.enrich(&st) h.notify(st.Name, "started") writeJSON(w, http.StatusOK, st.Redacted()) case action == "stop" && r.Method == http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } if h.Supervisor != nil { _ = h.Supervisor.Stop(id) } st, err := h.Store.SetEnabled(id, false) if err != nil { writeErr(w, http.StatusNotFound, err.Error()) return } h.audit(r, p, http.StatusOK, "stopped stream "+st.Name) h.enrich(&st) h.notify(st.Name, "stopped") writeJSON(w, http.StatusOK, st.Redacted()) case action == "restart" && r.Method == http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } st, err := h.Store.SetEnabled(id, true) if err != nil { writeErr(w, http.StatusNotFound, err.Error()) return } h.audit(r, p, http.StatusOK, "restarted stream "+st.Name) if h.Supervisor != nil { if err := h.Supervisor.Restart(id); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } st, _ = h.Store.GetStream(id) } h.enrich(&st) h.notify(st.Name, "restarted") writeJSON(w, http.StatusOK, st.Redacted()) case action == "capture" && r.Method == http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } st, err := h.Store.GetStream(id) if err != nil { writeErr(w, http.StatusNotFound, "not found") return } if h.Capture == nil { writeErr(w, http.StatusServiceUnavailable, "capture push is not available") return } n := h.Capture.RequestCapture(st, "manual") h.audit(r, p, http.StatusOK, "requested capture for stream "+st.Name) h.logger().Info("capture requested", "stream", st.Name, "by", p.Actor(), "agents", n) if n > 0 { h.Store.Eventf(st.ID, db.EventCaptureStarted, db.SevInfo, "manual capture requested (%d agent(s))", n) } else { h.Store.Eventf(st.ID, db.EventCaptureFailed, db.SevWarn, "manual capture requested but no agents are connected") } h.notify(st.Name, "capture") writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "stream": st.Name, "agents_notified": n, }) case action == "credentials" && r.Method == http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } var cred db.Credentials if err := readJSON(r, &cred); err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } st, err := h.Store.SetCredentials(id, cred) if err != nil { writeErr(w, http.StatusBadRequest, err.Error()) return } // Never log the credential itself, only that it arrived. h.audit(r, p, http.StatusOK, "set credentials for stream "+st.Name+credNote(st)) h.logger().Info("credentials updated", "stream", st.Name, "by", p.Actor(), "has_key", st.HasKey, "key_valid", st.KeyValid) _ = h.Store.ReleaseClaim(id, "") // Always kill the old media worker; start a fresh one when enabled. if h.Supervisor != nil { if st.Enabled { _ = h.Supervisor.Restart(id) } else { _ = h.Supervisor.Stop(id) } st, _ = h.Store.GetStream(id) } h.enrich(&st) h.notify(st.Name, "credentials") writeJSON(w, http.StatusOK, st.Redacted()) case action == "claim" && sub == "" && r.Method == http.MethodPost: p, ok := auth.Guard(w, r, auth.RoleOperator) if !ok { return } var body struct { AgentID string `json:"agent_id"` TTLSec int `json:"ttl_sec"` } _ = readJSON(r, &body) ttl := time.Duration(body.TTLSec) * time.Second st, err := h.Store.Claim(id, body.AgentID, ttl) if err != nil { if err.Error() == "claimed" { writeErr(w, http.StatusConflict, "already claimed") return } writeErr(w, http.StatusBadRequest, err.Error()) return } _ = p // A claim is high-volume agent bookkeeping, so it is not audited; the // capture events that follow it are. h.enrich(&st) writeJSON(w, http.StatusOK, st.Redacted()) case action == "claim" && sub == "release" && r.Method == http.MethodPost: if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok { return } var body struct { AgentID string `json:"agent_id"` } _ = readJSON(r, &body) if err := h.Store.ReleaseClaim(id, body.AgentID); err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"ok": true}) default: writeErr(w, http.StatusNotFound, "not found") } } // enrich fills the response-only fields: per-output health, publish links and // the live viewer count. func (h *Handler) enrich(st *db.Stream) { h.enrichVariantHealth(st) h.enrichLinks(st) if h.Viewers != nil { st.Viewers = h.Viewers.ViewersFor(st.Name) } } // notify pushes a stream change to every connected dashboard and agent so // they do not wait for the next poll. func (h *Handler) notify(name, reason string) { if h.Notifier == nil || strings.TrimSpace(name) == "" { return } h.Notifier.NotifyStreamChanged(name, reason) } // truthy accepts the spellings a query string realistically carries. func truthy(s string) bool { switch strings.ToLower(strings.TrimSpace(s)) { case "1", "true", "yes", "on": return true } return false } func readJSON(r *http.Request, dst any) error { defer r.Body.Close() b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { return err } if len(b) == 0 { return errors.New("empty body") } return json.Unmarshal(b, dst) } func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) enc := json.NewEncoder(w) enc.SetIndent("", " ") _ = enc.Encode(v) } func writeErr(w http.ResponseWriter, code int, msg string) { writeJSON(w, code, map[string]any{"error": msg}) } // credNote summarises a credential update for the audit trail without // recording any part of the secret. func credNote(st db.Stream) string { switch { case !st.HasKey: return " (clear, no key)" case st.KeyValid: return " (key ok)" default: return " (key present but unparseable)" } } // changeNote lists which fields a patch actually touched, for the audit row. func changeNote(before, after db.Stream, in db.PatchStream) string { var changed []string add := func(name string, differs bool) { if differs { changed = append(changed, name) } } add("mpd", in.MPD != nil && before.MPD != after.MPD) // Record that the key changed, never what it changed to. add("key", in.Key != nil && before.Key != after.Key) add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON) add("proxy", in.Proxy != nil && before.Proxy != after.Proxy) add("variants", before.VariantsJSON != after.VariantsJSON) add("outputs", before.OutputsJSON != after.OutputsJSON) add("settings", before.SettingsJSON != after.SettingsJSON) add("enabled", before.Enabled != after.Enabled) add("on_demand", before.OnDemand != after.OnDemand) add("public", before.Public != after.Public) add("drm_mode", before.DRMMode != after.DRMMode) add("title", in.Title != nil && before.Title != after.Title) add("tags", in.Tags != nil && before.Tags != after.Tags) if len(changed) == 0 { return " (no effective change)" } return " [" + strings.Join(changed, ",") + "]" } // credentialsChanged is true when the patch touched mpd, key, headers, proxy, // variants, outputs or packager settings that the live NRE/ffmpeg worker is // already using. func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { if in.MPD != nil && strings.TrimSpace(before.MPD) != strings.TrimSpace(after.MPD) { return true } if in.Key != nil && strings.TrimSpace(before.Key) != strings.TrimSpace(after.Key) { return true } if in.HeadersJSON != nil && strings.TrimSpace(before.HeadersJSON) != strings.TrimSpace(after.HeadersJSON) { return true } if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) { return true } if in.VariantsJSON != nil || len(in.Variants) > 0 { if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) { return true } } // The output set and the packager knobs are both baked into the ffmpeg // command line, so changing either needs a fresh packager. if in.OutputsJSON != nil || len(in.Outputs) > 0 { if strings.TrimSpace(before.OutputsJSON) != strings.TrimSpace(after.OutputsJSON) { return true } } if in.SettingsJSON != nil && strings.TrimSpace(before.SettingsJSON) != strings.TrimSpace(after.SettingsJSON) { return true } return false }