Files
shared/backend/files/files.go
T

110 lines
3.9 KiB
Go

// Package files holds the path-safety helpers for serving files from configured media roots:
// relative-path checks, root containment (including symlink escapes), and range-aware file serving.
package files
import (
"encoding/json"
"errors"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
)
// SafeRelative reports whether value is a relative path with no `..`
// traversal or absolute-path escape (Windows drive letters included).
func SafeRelative(value string) bool {
value = strings.TrimSpace(value)
windowsAbsolute := len(value) >= 2 && value[1] == ':'
return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`)
}
// WithinRoot reports whether candidate is (non-strictly) inside root.
func WithinRoot(root, candidate string) bool {
rel, err := filepath.Rel(root, candidate)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
}
// SameRealRoot reports whether candidate's symlink-resolved real path is
// still inside root's symlink-resolved real path (guards against a symlink
// planted inside root pointing outside it).
func SameRealRoot(root, candidate string) bool {
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return false
}
realCandidate, err := filepath.EvalSymlinks(candidate)
if err != nil {
return false
}
realRoot, err = filepath.Abs(realRoot)
if err != nil {
return false
}
realCandidate, err = filepath.Abs(realCandidate)
return err == nil && WithinRoot(realRoot, realCandidate)
}
// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative
// path) against each of roots in order, returning the first root it
// actually exists under as a real file (not a directory, and not merely a
// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root
// matches.
func ResolveUnderRoots(value string, roots []string) (string, error) {
value = strings.TrimSpace(strings.TrimPrefix(value, "/media/"))
value = strings.TrimPrefix(value, "/")
if value == "" || strings.ContainsRune(value, 0) {
return "", errors.New("empty path")
}
for _, root := range roots {
rootAbs, err := filepath.Abs(root)
if err != nil {
continue
}
candidate := value
if !filepath.IsAbs(candidate) {
candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate))
}
candidate, err = filepath.Abs(candidate)
if err != nil || !WithinRoot(rootAbs, candidate) {
continue
}
info, err := os.Stat(candidate)
if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) {
return candidate, nil
}
}
return "", os.ErrNotExist
}
// ServeFile serves fullPath (an already-resolved, already-safety-checked
// path) with the correct Content-Type and range-request support.
func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) {
file, err := os.Open(fullPath)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
writeError(w, http.StatusNotFound, "file not found")
return
}
if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" {
w.Header().Set("Content-Type", contentType)
}
http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}