sonda/internal/streaming/streaming.go
tgiachi def20731be fix(streaming): open files through os.Root and tighten token parsing
- fix: open the audio file through os.Root with O_NONBLOCK. A FIFO under a
  stored path used to block the request forever in open(2) before the
  regular-file check could run; now it is refused immediately
- fix: os.Root also removes the gap between checking the path and opening it,
  so a symlink swapped in at the last moment cannot leave the library
  (absolute symlinks are refused even when they point back inside)
- fix(api): only "Authorization: Bearer <token>" is accepted again. The query
  token change had made a bare token in the header pass on every route
- fix(config): library.roots must be absolute paths; a relative root made
  every stream fail and depended on the directory sondad started in
- test: FIFO and symlink-to-FIFO without hanging, bare and non-Bearer headers
  on a normal route and on the stream route, relative roots
2026-11-11 13:00:17 +01:00

161 lines
4.7 KiB
Go

// Package streaming opens audio files for playback.
//
// The only job here is to turn a track id into an open, verified file. The
// stored path is treated as untrusted: it must belong to a configured library
// root, and the file is opened through os.Root so that nothing, not even a
// symlink swapped in at the last moment, can lead outside that root.
package streaming
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
)
// Errors returned by Open. Handlers map them to HTTP statuses.
var (
ErrNotFound = errors.New("no playable file for this track")
ErrFileMissing = errors.New("audio file is missing on disk")
ErrUnsafePath = errors.New("audio path is outside the library")
)
// File is where a track's audio lives: a configured library root plus a path
// relative to it, exactly as the scanner stored them.
type File struct {
Root string
RelPath string // slash-separated
}
// Source finds the file to play for a track.
type Source interface {
// PlayableFile returns ErrNotFound when the track does not exist or every
// file of it is flagged missing.
PlayableFile(ctx context.Context, trackID int64) (File, error)
}
// Stream is an open audio file ready to be served. The caller must Close it.
type Stream struct {
File *os.File
Name string
ModTime time.Time
ContentType string
}
// Close releases the file.
func (s *Stream) Close() error { return s.File.Close() }
// Service opens tracks for playback.
type Service struct {
source Source
roots []string // cleaned; config validation requires them to be absolute
}
// NewService builds a Service. Only files under the given roots can be opened.
func NewService(source Source, roots []string) *Service {
cleaned := make([]string, len(roots))
for i, r := range roots {
cleaned[i] = filepath.Clean(r)
}
return &Service{source: source, roots: cleaned}
}
// Open returns the audio file of a track, after verifying that it is a regular
// file inside one of the configured roots.
//
// The file is opened through an os.Root, which refuses to leave the root at
// open time: a symlink swapped in after any earlier check cannot escape, and
// there is no gap between "check the path" and "open the file".
func (s *Service) Open(ctx context.Context, trackID int64) (*Stream, error) {
f, err := s.source.PlayableFile(ctx, trackID)
if err != nil {
return nil, err
}
rel, err := s.validate(f)
if err != nil {
return nil, err
}
root, err := os.OpenRoot(filepath.Clean(f.Root))
if errors.Is(err, fs.ErrNotExist) {
return nil, ErrFileMissing // volume not mounted
}
if err != nil {
return nil, fmt.Errorf("open library root: %w", err)
}
defer root.Close() // files already opened stay valid
// O_NONBLOCK so that a FIFO cannot hang the request: opening one would
// otherwise block until a writer appears.
file, err := root.OpenFile(rel, os.O_RDONLY|nonBlock, 0)
switch {
case errors.Is(err, fs.ErrNotExist):
return nil, ErrFileMissing
case err != nil && strings.Contains(err.Error(), "path escapes from parent"):
// os.Root has no exported error for this case.
return nil, fmt.Errorf("%w: symlink leaves the library", ErrUnsafePath)
case err != nil:
return nil, fmt.Errorf("open audio file: %w", err)
}
// Check what was actually opened, not what the path looked like earlier.
info, err := file.Stat()
if err != nil {
_ = file.Close()
return nil, fmt.Errorf("stat audio file: %w", err)
}
if !info.Mode().IsRegular() {
_ = file.Close()
return nil, fmt.Errorf("%w: not a regular file", ErrUnsafePath)
}
return &Stream{
File: file,
Name: filepath.Base(rel),
ModTime: info.ModTime(),
ContentType: contentType(rel),
}, nil
}
// validate checks the stored root and relative path and returns the cleaned
// relative path to open under the root.
func (s *Service) validate(f File) (string, error) {
root := filepath.Clean(f.Root)
if !filepath.IsAbs(root) || !s.allowed(root) {
return "", fmt.Errorf("%w: root is not a configured library root", ErrUnsafePath)
}
rel := filepath.FromSlash(f.RelPath)
if rel == "" || filepath.IsAbs(rel) {
return "", fmt.Errorf("%w: bad relative path", ErrUnsafePath)
}
rel = filepath.Clean(rel)
if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", fmt.Errorf("%w: path escapes the root", ErrUnsafePath)
}
return rel, nil
}
func (s *Service) allowed(root string) bool {
for _, r := range s.roots {
if r == root {
return true
}
}
return false
}
func contentType(path string) string {
switch strings.ToLower(filepath.Ext(path)) {
case ".mp3":
return "audio/mpeg"
case ".flac":
return "audio/flac"
default:
return "application/octet-stream"
}
}