mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
os.Root follows symlinks that remain inside the root, so a parent swapped after wsResolveConfined for a link to a denied subtree (traffic/_ca, traffic/_index, traffic/_blobs, archives) was still followed by root.Open/root.RemoveAll, bypassing workspacePathDenied. Apply the same real-directory verification the write path uses: - wsList rejects a final symlink or non-directory, then checks every component of rel with verifyRootRealDir before opening. - wsRead and wsDownload check the parent components and reject a final-component symlink before opening. - wsDelete checks only the parent components, so a final symlink is still unlinked rather than dereferenced, and refuses rel == ".". wsRead no longer stat's then reads by name. It opens once, stats the same descriptor, rejects non-regular entries, and reads through io.LimitReader(maxWorkspaceRead+1), so a swapped-in file cannot bypass the inline-size limit. Opening a FIFO blocks until a writer appears, so both wsRead and wsDownload reject any non-regular entry before opening; a unix-only test plants a FIFO and asserts a fast error instead of a hang. Also add a deterministic case-sensitive tie-breaker to the wsList sort for names that differ only in case. Tests swap a real parent directory for a root-relative symlink to traffic/_ca and archives after wsResolveConfined; list, read, download and delete served/deleted the denied subtree before this change and are refused after it.
731 lines
20 KiB
Go
731 lines
20 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// Workspace file manager — browse / view / edit / download / upload / delete the
|
|
// shared work dir (s.m.dir), where all agents write their artifacts. Every path is
|
|
// confined to the work dir root (traversal via ".." is neutralised). All routes sit
|
|
// behind requireAuth (see Handler()).
|
|
|
|
const (
|
|
maxWorkspaceRead = 2 << 20 // 2 MiB: files bigger than this aren't inlined for view/edit (download instead)
|
|
maxWorkspaceUpload = 512 << 20 // 512 MiB per upload request
|
|
)
|
|
|
|
var errWorkspaceTargetIsDir = errors.New("target is a directory")
|
|
|
|
// wsBeforeWriteHook is an optional test hook invoked after wsResolveConfined
|
|
// succeeds and immediately before the root-anchored write executes, allowing
|
|
// deterministic TOCTOU regression tests (always nil in production).
|
|
var wsBeforeWriteHook func()
|
|
|
|
// wsBeforeIOHook is an optional test hook invoked after wsResolveConfined
|
|
// succeeds and immediately before the root-anchored read/list/delete/download
|
|
// executes, allowing deterministic TOCTOU regression tests (always nil in
|
|
// production).
|
|
var wsBeforeIOHook func()
|
|
|
|
// wsRelToRoot converts an absolute path into a clean name relative to realRoot
|
|
// suitable for os.Root operations. It returns "." when path == realRoot.
|
|
func wsRelToRoot(realRoot, path string) (string, error) {
|
|
rel, err := filepath.Rel(realRoot, path)
|
|
if err != nil {
|
|
return "", errPathEscape
|
|
}
|
|
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
|
|
return "", errPathEscape
|
|
}
|
|
return rel, nil
|
|
}
|
|
|
|
// wsConfinedRel converts cp.realPath into a clean path relative to cp.realRoot
|
|
// suitable for os.Root operations. It returns "." when cp.realPath == cp.realRoot.
|
|
func wsConfinedRel(cp confinedPath) (string, error) {
|
|
return wsRelToRoot(cp.realRoot, cp.realPath)
|
|
}
|
|
|
|
// wsEntryRel converts cp.entryPath into a clean path relative to cp.realRoot.
|
|
// Unlike cp.realPath, entryPath keeps a symlink in the final component, so a
|
|
// delete removes the link itself rather than the target it points at.
|
|
func wsEntryRel(cp confinedPath) (string, error) {
|
|
return wsRelToRoot(cp.realRoot, cp.entryPath)
|
|
}
|
|
|
|
// verifyRootRealDir verifies that every path component of relDir beneath root
|
|
// already exists as a real directory (not a symlink).
|
|
func verifyRootRealDir(root *os.Root, relDir string) error {
|
|
clean := filepath.Clean(relDir)
|
|
if clean == "" || clean == "." {
|
|
return nil
|
|
}
|
|
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) || filepath.IsAbs(clean) {
|
|
return fmt.Errorf("invalid relative directory %q", relDir)
|
|
}
|
|
parts := strings.Split(clean, string(filepath.Separator))
|
|
cur := ""
|
|
for _, part := range parts {
|
|
if part == "" || part == "." {
|
|
continue
|
|
}
|
|
if cur == "" {
|
|
cur = part
|
|
} else {
|
|
cur = filepath.Join(cur, part)
|
|
}
|
|
fi, err := root.Lstat(cur)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
|
|
return fmt.Errorf("path %q is not a real directory", cur)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func wsWriteInRoot(realRoot, rel string, content []byte) error {
|
|
root, err := os.OpenRoot(realRoot)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
if parent := filepath.Dir(rel); parent != "." {
|
|
if err := ensureRootRealDir(root, parent, 0o755); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if fi, err := root.Lstat(rel); err == nil {
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("refusing to write through a symlink")
|
|
}
|
|
if fi.IsDir() {
|
|
return errWorkspaceTargetIsDir
|
|
}
|
|
} else if !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
out, err := root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, writeErr := out.Write(content)
|
|
closeErr := out.Close()
|
|
if writeErr != nil {
|
|
return writeErr
|
|
}
|
|
return closeErr
|
|
}
|
|
|
|
func wsMkdirInRoot(realRoot, rel string) error {
|
|
root, err := os.OpenRoot(realRoot)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
return ensureRootRealDir(root, rel, 0o755)
|
|
}
|
|
|
|
func saveRootUpload(root *os.Root, rel string, hdr *multipart.FileHeader) error {
|
|
if parent := filepath.Dir(rel); parent != "." {
|
|
if err := verifyRootRealDir(root, parent); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if fi, err := root.Lstat(rel); err == nil {
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("refusing to write through a symlink")
|
|
}
|
|
if fi.IsDir() {
|
|
return errWorkspaceTargetIsDir
|
|
}
|
|
} else if !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
src, err := hdr.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer src.Close()
|
|
out, err := root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, copyErr := io.Copy(out, src)
|
|
closeErr := out.Close()
|
|
if copyErr != nil {
|
|
return copyErr
|
|
}
|
|
return closeErr
|
|
}
|
|
|
|
// wsResolveConfined maps a user-supplied relative path to a canonicalized path
|
|
// inside the work dir, resolving symlinks in every component and rejecting any
|
|
// traversal, broken symlink, symlink loop, or target that escapes s.m.dir.
|
|
func (s *Server) wsResolveConfined(rel string) (confinedPath, bool) {
|
|
cp, err := resolveWithinRoot(s.m.dir, rel, true)
|
|
if err != nil {
|
|
return confinedPath{}, false
|
|
}
|
|
if workspacePathDenied(cp.realRoot, cp.realPath) {
|
|
return confinedPath{}, false
|
|
}
|
|
return cp, true
|
|
}
|
|
|
|
// workspaceDeniedPrefixes are platform-internal subtrees under the data dir
|
|
// that the workspace file manager must not expose. traffic/_ca holds the
|
|
// capture proxy CA private key; traffic/_index holds the SQLite exchange index;
|
|
// traffic/_blobs holds the captured bodies the index refers to by hash.
|
|
var workspaceDeniedPrefixes = []string{"traffic/_ca", "traffic/_index", "traffic/_blobs", "archives"}
|
|
|
|
// workspacePathDenied reports whether realPath lands in a platform-internal
|
|
// subtree. It compares the canonicalized path relative to the real root, so a
|
|
// symlink alias cannot reach a denied directory. Segments are lower-cased and
|
|
// trailing dots/spaces are trimmed because Windows resolves those spellings to
|
|
// the same directory.
|
|
func workspacePathDenied(realRoot, realPath string) bool {
|
|
rel, err := filepath.Rel(realRoot, realPath)
|
|
if err != nil {
|
|
return true // fail closed
|
|
}
|
|
rel = filepath.ToSlash(rel)
|
|
if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
|
|
return true // outside the root: fail closed
|
|
}
|
|
segs := strings.Split(rel, "/")
|
|
for i, seg := range segs {
|
|
segs[i] = strings.ToLower(strings.TrimRight(seg, ". "))
|
|
}
|
|
rel = strings.Join(segs, "/")
|
|
for _, prefix := range workspaceDeniedPrefixes {
|
|
if rel == prefix || strings.HasPrefix(rel, prefix+"/") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// workspaceHoldsDenied reports whether a platform-internal subtree lies beneath
|
|
// path, so that removing path would remove it too. Segments are normalised as
|
|
// in workspacePathDenied.
|
|
func workspaceHoldsDenied(realRoot, path string) bool {
|
|
rel, err := filepath.Rel(realRoot, path)
|
|
if err != nil {
|
|
return true // fail closed
|
|
}
|
|
segs := strings.Split(filepath.ToSlash(rel), "/")
|
|
for i, seg := range segs {
|
|
segs[i] = strings.ToLower(strings.TrimRight(seg, ". "))
|
|
}
|
|
rel = strings.Join(segs, "/")
|
|
for _, prefix := range workspaceDeniedPrefixes {
|
|
if strings.HasPrefix(prefix, rel+"/") {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// wsRel renders an absolute path back as a workspace-relative path (forward slashes).
|
|
func (s *Server) wsRel(abs string) string {
|
|
base, err := resolveRealRoot(s.m.dir)
|
|
if err != nil {
|
|
base = filepath.Clean(s.m.dir)
|
|
}
|
|
rel, err := filepath.Rel(base, abs)
|
|
if err != nil || rel == "." {
|
|
return ""
|
|
}
|
|
return filepath.ToSlash(rel)
|
|
}
|
|
|
|
type wsEntry struct {
|
|
Name string `json:"name"`
|
|
Path string `json:"path"`
|
|
Dir bool `json:"dir"`
|
|
Size int64 `json:"size"`
|
|
MTime int64 `json:"mtime"` // unix millis
|
|
}
|
|
|
|
// GET /api/workspace/list?path=<rel>
|
|
func (s *Server) wsList(w http.ResponseWriter, r *http.Request) {
|
|
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
|
if !ok {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
rel, err := wsConfinedRel(cp)
|
|
if err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeIOHook != nil {
|
|
wsBeforeIOHook()
|
|
}
|
|
root, err := os.OpenRoot(cp.realRoot)
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer root.Close()
|
|
fi, err := root.Lstat(rel)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeErr(w, 404, "path does not exist")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if !fi.IsDir() {
|
|
writeErr(w, 400, "not a directory")
|
|
return
|
|
}
|
|
// os.Root follows symlinks that stay inside cp.realRoot, so a parent
|
|
// swapped for a link to a denied subtree after wsResolveConfined would be
|
|
// followed. Require every component of rel to still be a real directory.
|
|
if err := verifyRootRealDir(root, rel); err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
dir, err := root.Open(rel)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeErr(w, 404, "path does not exist")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer dir.Close()
|
|
fi, err = dir.Stat()
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
if !fi.IsDir() {
|
|
writeErr(w, 400, "not a directory")
|
|
return
|
|
}
|
|
ents, err := dir.ReadDir(-1)
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
abs := cp.realPath
|
|
out := make([]wsEntry, 0, len(ents))
|
|
for _, e := range ents {
|
|
info, err := e.Info()
|
|
if err != nil {
|
|
continue
|
|
}
|
|
out = append(out, wsEntry{
|
|
Name: e.Name(),
|
|
Path: s.wsRel(filepath.Join(abs, e.Name())),
|
|
Dir: e.IsDir(),
|
|
Size: info.Size(),
|
|
MTime: info.ModTime().UnixMilli(),
|
|
})
|
|
}
|
|
// Directories first, each sorted by name (case-insensitively, with a
|
|
// deterministic tie-breaker for names that differ only in case).
|
|
sort.Slice(out, func(i, j int) bool {
|
|
if out[i].Dir != out[j].Dir {
|
|
return out[i].Dir
|
|
}
|
|
li, lj := strings.ToLower(out[i].Name), strings.ToLower(out[j].Name)
|
|
if li != lj {
|
|
return li < lj
|
|
}
|
|
return out[i].Name < out[j].Name
|
|
})
|
|
writeJSON(w, 200, map[string]any{"path": s.wsRel(abs), "entries": out})
|
|
}
|
|
|
|
// GET /api/workspace/read?path=<rel> — inline text for view/edit. Binary or oversize
|
|
// files return {binary:true}/{too_large:true} with no content (use download instead).
|
|
func (s *Server) wsRead(w http.ResponseWriter, r *http.Request) {
|
|
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
|
if !ok {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
abs := cp.realPath
|
|
rel, err := wsConfinedRel(cp)
|
|
if err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeIOHook != nil {
|
|
wsBeforeIOHook()
|
|
}
|
|
root, err := os.OpenRoot(cp.realRoot)
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer root.Close()
|
|
// os.Root follows in-root symlinks and opening a FIFO blocks until a writer
|
|
// appears, so reject a raced final symlink, a directory and any other
|
|
// non-regular entry before opening. The parent components must still be real
|
|
// directories: a parent swapped to a denied subtree would otherwise be
|
|
// followed by root.Open.
|
|
fi, err := root.Lstat(rel)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeErr(w, 404, "file does not exist")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if fi.IsDir() {
|
|
writeErr(w, 400, "is a directory, cannot be read as a file")
|
|
return
|
|
}
|
|
if !fi.Mode().IsRegular() {
|
|
writeErr(w, 400, "not a regular file")
|
|
return
|
|
}
|
|
if err := verifyRootRealDir(root, filepath.Dir(rel)); err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
file, err := root.Open(rel)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeErr(w, 404, "file does not exist")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer file.Close()
|
|
// Stat and read from the same descriptor so a file swapped in after the
|
|
// path lookup cannot bypass maxWorkspaceRead.
|
|
fi, err = file.Stat()
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
if !fi.Mode().IsRegular() {
|
|
writeErr(w, 400, "not a regular file")
|
|
return
|
|
}
|
|
if fi.Size() > maxWorkspaceRead {
|
|
writeJSON(w, 200, map[string]any{"path": s.wsRel(abs), "size": fi.Size(), "too_large": true, "binary": true})
|
|
return
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(file, maxWorkspaceRead+1))
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
if len(data) > maxWorkspaceRead {
|
|
writeJSON(w, 200, map[string]any{"path": s.wsRel(abs), "size": fi.Size(), "too_large": true, "binary": true})
|
|
return
|
|
}
|
|
if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {
|
|
writeJSON(w, 200, map[string]any{"path": s.wsRel(abs), "size": fi.Size(), "binary": true})
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"path": s.wsRel(abs), "size": fi.Size(), "binary": false, "content": string(data)})
|
|
}
|
|
|
|
// POST /api/workspace/write {path, content} — create/overwrite a text file.
|
|
func (s *Server) wsWrite(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Path string `json:"path"`
|
|
Content string `json:"content"`
|
|
}
|
|
if err := decode(w, r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
cp, ok := s.wsResolveConfined(req.Path)
|
|
if !ok || cp.realPath == cp.realRoot {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
rel, err := wsConfinedRel(cp)
|
|
if err != nil || rel == "." {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeWriteHook != nil {
|
|
wsBeforeWriteHook()
|
|
}
|
|
if err := wsWriteInRoot(cp.realRoot, rel, []byte(req.Content)); err != nil {
|
|
if errors.Is(err, errWorkspaceTargetIsDir) {
|
|
writeErr(w, 400, "target is a directory")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"ok": true, "path": s.wsRel(cp.realPath)})
|
|
}
|
|
|
|
// POST /api/workspace/mkdir {path}
|
|
func (s *Server) wsMkdir(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Path string `json:"path"`
|
|
}
|
|
if err := decode(w, r, &req); err != nil {
|
|
writeErr(w, 400, err.Error())
|
|
return
|
|
}
|
|
cp, ok := s.wsResolveConfined(req.Path)
|
|
if !ok || cp.realPath == cp.realRoot {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
rel, err := wsConfinedRel(cp)
|
|
if err != nil || rel == "." {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeWriteHook != nil {
|
|
wsBeforeWriteHook()
|
|
}
|
|
if err := wsMkdirInRoot(cp.realRoot, rel); err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"ok": true, "path": s.wsRel(cp.realPath)})
|
|
}
|
|
|
|
// DELETE /api/workspace/delete?path=<rel> — removes a file or a directory tree
|
|
// (confined to the work dir; the root itself can't be deleted).
|
|
func (s *Server) wsDelete(w http.ResponseWriter, r *http.Request) {
|
|
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
|
if !ok {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if cp.realPath == cp.realRoot {
|
|
writeErr(w, 400, "cannot delete the workspace root directory")
|
|
return
|
|
}
|
|
// entryPath is what RemoveAll removes: a symlink is removed as a link, a
|
|
// directory with everything beneath it.
|
|
if workspaceHoldsDenied(cp.realRoot, cp.entryPath) {
|
|
writeErr(w, 400, "cannot delete a directory that holds platform data (the capture CA, index and blob store)")
|
|
return
|
|
}
|
|
if !cp.exists {
|
|
writeErr(w, 404, "path does not exist")
|
|
return
|
|
}
|
|
rel, err := wsEntryRel(cp)
|
|
if err != nil || rel == "." {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeIOHook != nil {
|
|
wsBeforeIOHook()
|
|
}
|
|
root, err := os.OpenRoot(cp.realRoot)
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer root.Close()
|
|
// os.Root.RemoveAll follows in-root symlink parents, so a parent swapped for
|
|
// a link to a denied subtree after wsResolveConfined would be removed. The
|
|
// final component stays unverified: a symlink there is unlinked, never
|
|
// dereferenced.
|
|
if err := verifyRootRealDir(root, filepath.Dir(rel)); err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if err := root.RemoveAll(rel); err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"ok": true})
|
|
}
|
|
|
|
// GET /api/workspace/download?path=<rel> — stream a file as an attachment.
|
|
func (s *Server) wsDownload(w http.ResponseWriter, r *http.Request) {
|
|
cp, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
|
if !ok {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
rel, err := wsConfinedRel(cp)
|
|
if err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeIOHook != nil {
|
|
wsBeforeIOHook()
|
|
}
|
|
root, err := os.OpenRoot(cp.realRoot)
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer root.Close()
|
|
// Reject a raced final symlink, non-regular entries (opening a FIFO blocks
|
|
// until a writer appears) and a parent swapped for a link to a denied
|
|
// subtree before opening the file.
|
|
fi, err := root.Lstat(rel)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeErr(w, 404, "file does not exist")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if !fi.Mode().IsRegular() {
|
|
writeErr(w, 404, "file does not exist")
|
|
return
|
|
}
|
|
if err := verifyRootRealDir(root, filepath.Dir(rel)); err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
file, err := root.Open(rel)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeErr(w, 404, "file does not exist")
|
|
return
|
|
}
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer file.Close()
|
|
fi, err = file.Stat()
|
|
if err != nil || !fi.Mode().IsRegular() {
|
|
writeErr(w, 404, "file does not exist")
|
|
return
|
|
}
|
|
name := filepath.Base(cp.entryPath)
|
|
// RFC 5987 filename* keeps non-ASCII names intact; plain filename is the fallback.
|
|
w.Header().Set("Content-Disposition", "attachment; filename=\""+sanitizeFilename(name)+"\"; filename*=UTF-8''"+url.PathEscape(name))
|
|
http.ServeContent(w, r, name, fi.ModTime(), file)
|
|
}
|
|
|
|
// POST /api/workspace/upload?path=<dir> — multipart form field "file" (one or more).
|
|
func (s *Server) wsUpload(w http.ResponseWriter, r *http.Request) {
|
|
dir, ok := s.wsResolveConfined(r.URL.Query().Get("path"))
|
|
if !ok {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
dirRootRel, err := wsConfinedRel(dir)
|
|
if err != nil {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
root, err := os.OpenRoot(dir.realRoot)
|
|
if err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
defer root.Close()
|
|
if dirRootRel != "." {
|
|
if err := verifyRootRealDir(root, dirRootRel); err != nil {
|
|
writeErr(w, 400, "target directory does not exist")
|
|
return
|
|
}
|
|
} else if fi, err := root.Stat("."); err != nil || !fi.IsDir() {
|
|
writeErr(w, 400, "target directory does not exist")
|
|
return
|
|
}
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxWorkspaceUpload)
|
|
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
|
writeErr(w, 400, "failed to parse upload or size limit exceeded: "+err.Error())
|
|
return
|
|
}
|
|
files := r.MultipartForm.File["file"]
|
|
if len(files) == 0 {
|
|
writeErr(w, 400, "missing upload file (form field file)")
|
|
return
|
|
}
|
|
dirRel := s.wsRel(dir.realPath)
|
|
saved := 0
|
|
for _, hdr := range files {
|
|
name := filepath.Base(hdr.Filename) // strip any path component
|
|
if name == "" || name == "." || name == ".." {
|
|
continue
|
|
}
|
|
destRel := name
|
|
if dirRel != "" {
|
|
destRel = dirRel + "/" + name
|
|
}
|
|
dest, okd := s.wsResolveConfined(destRel)
|
|
if !okd || dest.realPath == dest.realRoot {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
rel, err := wsConfinedRel(dest)
|
|
if err != nil || rel == "." {
|
|
writeErr(w, 400, "invalid path")
|
|
return
|
|
}
|
|
if wsBeforeWriteHook != nil {
|
|
wsBeforeWriteHook()
|
|
}
|
|
if err := saveRootUpload(root, rel, hdr); err != nil {
|
|
writeErr(w, 500, safeFSErr(err))
|
|
return
|
|
}
|
|
saved++
|
|
}
|
|
writeJSON(w, 200, map[string]any{"uploaded": saved})
|
|
}
|
|
|
|
// refuseUploadSymlink rejects a destination that is already a symlink. os.Create
|
|
// follows one, including a dangling link that Stat reports as missing, so an
|
|
// agent that can write the uploads directory could aim the server's write at
|
|
// another path. Lstat sees the link itself.
|
|
func refuseUploadSymlink(dest string) error {
|
|
fi, err := os.Lstat(dest)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
if fi.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("refusing to write through a symlink")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// sanitizeFilename strips characters unsafe for a Content-Disposition filename token.
|
|
func sanitizeFilename(name string) string {
|
|
name = strings.ReplaceAll(name, "\"", "")
|
|
name = strings.ReplaceAll(name, "\\", "")
|
|
name = strings.ReplaceAll(name, "\n", "")
|
|
name = strings.ReplaceAll(name, "\r", "")
|
|
return name
|
|
}
|