refactor(backend): rename mediacore package to media
This commit is contained in:
1 parent
e8cb7c6c68
commit
75c08beec6
34 files changed
+837
-656
No files matched your search
@@ -0,0 +1,109 @@
|
||||
// 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})
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package files
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSafeRelativeRejectsTraversalAndAbsolutePaths(t *testing.T) {
|
||||
for _, value := range []string{"", ".", "..", "../x", "a/../../x", "sub/../a.mp4x", "/etc/passwd", `\etc\passwd`, `C:\x`, "a\x00b"} {
|
||||
if SafeRelative(value) {
|
||||
t.Errorf("SafeRelative(%q) = true, want false", value)
|
||||
}
|
||||
}
|
||||
for _, value := range []string{"a.mp4", "sub/b.mp4", "v1..2/clip.mp4"} {
|
||||
if !SafeRelative(value) {
|
||||
t.Errorf("SafeRelative(%q) = false, want true", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "a.mp4"), []byte("a"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "sub", "b.mp4"), []byte("b"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(t.TempDir(), "secret.txt")
|
||||
if err := os.WriteFile(outside, []byte("s"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.Symlink(outside, filepath.Join(root, "link.txt"))
|
||||
|
||||
for value, want := range map[string]string{
|
||||
"a.mp4": filepath.Join(root, "a.mp4"),
|
||||
"/media/a.mp4": filepath.Join(root, "a.mp4"),
|
||||
"sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
|
||||
"/media/sub/b.mp4": filepath.Join(root, "sub", "b.mp4"),
|
||||
} {
|
||||
got, err := ResolveUnderRoots(value, []string{root})
|
||||
if err != nil || got != want {
|
||||
t.Errorf("ResolveUnderRoots(%q) = %q, %v; want %q", value, got, err, want)
|
||||
}
|
||||
}
|
||||
|
||||
for _, value := range []string{"../secret.txt", "sub", "missing.mp4", "link.txt", "", "a\x00b"} {
|
||||
if _, err := ResolveUnderRoots(value, []string{root}); err == nil {
|
||||
t.Errorf("ResolveUnderRoots(%q) resolved, want an error", value)
|
||||
}
|
||||
}
|
||||
if _, err := ResolveUnderRoots("missing.mp4", []string{root}); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("missing file error = %v, want os.ErrNotExist", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user