sonda/internal/api/http/handlers_stream.go
tgiachi 49f1051b3f feat(streaming): stream tracks with HTTP Range support
- feat(streaming): open a track's file only after checking it against the
  configured library roots: relative paths only, no "..", symlinks resolved on
  both sides so none can leave the root, regular files only
- feat(api): GET and HEAD /api/v1/tracks/{id}/stream via http.ServeContent
  (206, 416, Content-Length, conditional requests), MIME type from the
  extension, nosniff, no-referrer and private caching headers
- feat(api): the stream route also accepts the access token as access_token in
  the query string, because an audio element cannot send headers; no other
  route does, and the query string is never logged
- feat(storage): PlayableFile picks the oldest file of a track that is not
  flagged missing
- fix(api): internal errors set by handlers are now written to the request log
- test: range variants, HEAD, conditional requests, auth variants, traversal,
  symlink escape, symlinked root, missing file, directory instead of file
2026-11-11 12:56:20 +01:00

51 lines
1.6 KiB
Go

package httpapi
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"codeberg.org/squidd/sonda/internal/streaming"
)
type streamHandlers struct{ svc streamService }
// stream serves a track's original file. http.ServeContent does the protocol
// work: Range (206, 416), HEAD, Content-Length, conditional requests, and it
// stops copying when the client goes away.
func (h *streamHandlers) stream(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
st, err := h.svc.Open(c.Request.Context(), id)
switch {
case errors.Is(err, streaming.ErrNotFound):
writeError(c, http.StatusNotFound, "track_not_found", "no playable file for this track")
return
case errors.Is(err, streaming.ErrFileMissing):
writeError(c, http.StatusNotFound, "file_missing", "the audio file is not available")
return
case errors.Is(err, streaming.ErrUnsafePath):
// A stored path that leaves the library is a data problem, not the
// client's: log it, but say no more than "not available".
_ = c.Error(err)
writeError(c, http.StatusNotFound, "file_missing", "the audio file is not available")
return
case err != nil:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
defer st.Close()
hdr := c.Writer.Header()
hdr.Set("Content-Type", st.ContentType)
hdr.Set("X-Content-Type-Options", "nosniff")
// The URL may carry the access token: never leak it through Referer.
hdr.Set("Referrer-Policy", "no-referrer")
hdr.Set("Cache-Control", "private, no-cache")
http.ServeContent(c.Writer, c.Request, st.Name, st.ModTime, st.File)
}