mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-01 11:31:51 +08:00
feat(tasks): add read-only task file browser (GITHUB-3)
This commit is contained in:
1 parent
873e3a667b
commit
62ed7db7b2
14 files changed
+1567
-21
No files matched your search
@@ -0,0 +1,38 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func setFileDisposition(w http.ResponseWriter, kind, name string) {
|
||||
w.Header().Set("Content-Disposition", kind+"; filename=\""+sanitizeFilename(name)+"\"; filename*=UTF-8''"+url.PathEscape(name))
|
||||
}
|
||||
|
||||
// Limit the read itself, not just the preceding stat: running agents may append
|
||||
// to a file between stat and read.
|
||||
func writeTextFile(w http.ResponseWriter, path string, r io.Reader, size int64) {
|
||||
result := map[string]any{"path": path, "size": size, "binary": false}
|
||||
if size > maxWorkspaceRead {
|
||||
result["too_large"], result["binary"] = true, true
|
||||
writeJSON(w, 200, result)
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(r, maxWorkspaceRead+1))
|
||||
if err != nil {
|
||||
writeErr(w, 500, "taskFiles.failed")
|
||||
return
|
||||
}
|
||||
result["size"] = len(data)
|
||||
if len(data) > maxWorkspaceRead {
|
||||
result["too_large"], result["binary"] = true, true
|
||||
} else if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {
|
||||
result["binary"] = true
|
||||
} else {
|
||||
result["content"] = string(data)
|
||||
}
|
||||
writeJSON(w, 200, result)
|
||||
}
|
||||
@@ -873,6 +873,12 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/tasks/{id}/intent-assets", s.taskIntentAssets)
|
||||
|
||||
// 工作空间文件管理器(针对 workDir)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files", s.taskFilesList)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/all", s.taskFilesAll)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/read", s.taskFilesServe)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/download", s.taskFilesServe)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/preview", s.taskFilesServe)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/archive", s.taskFilesArchive)
|
||||
mux.HandleFunc("GET /api/workspace/list", s.wsList)
|
||||
mux.HandleFunc("GET /api/workspace/read", s.wsRead)
|
||||
mux.HandleFunc("POST /api/workspace/write", s.wsWrite)
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"container/heap"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxTaskFiles = 2000
|
||||
|
||||
type taskFileEntry struct {
|
||||
wsEntry
|
||||
Symlink bool `json:"symlink"`
|
||||
IntentID int64 `json:"intent_id,omitempty"`
|
||||
IntentTitle string `json:"intent_title,omitempty"`
|
||||
IntentState string `json:"intent_state,omitempty"`
|
||||
}
|
||||
|
||||
type taskFileListing struct {
|
||||
Path string `json:"path"`
|
||||
Entries []taskFileEntry `json:"entries"`
|
||||
Total int `json:"total"`
|
||||
Size int64 `json:"size"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Missing bool `json:"missing"`
|
||||
}
|
||||
|
||||
// Reject nonportable paths as well as traversal, rather than silently cleaning
|
||||
// them. All actual filesystem access goes through os.Root, including traversal.
|
||||
func taskFilePath(raw string) (string, error) {
|
||||
if raw == "" {
|
||||
return ".", nil
|
||||
}
|
||||
if !fs.ValidPath(raw) || strings.ContainsAny(raw, "\\:\x00") || !filepath.IsLocal(raw) {
|
||||
return "", errors.New("invalid path")
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func taskFileError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
writeErr(w, 404, "taskFiles.unavailable")
|
||||
case errors.Is(err, fs.ErrPermission):
|
||||
writeErr(w, 403, "taskFiles.denied")
|
||||
default:
|
||||
writeErr(w, 400, "taskFiles.invalidPath")
|
||||
}
|
||||
}
|
||||
|
||||
// Open the task root through its parent so a task-root symlink cannot escape
|
||||
// the workspace. Never hold a task operation lock while reading or streaming.
|
||||
func (s *Server) openTaskFiles(w http.ResponseWriter, r *http.Request) (*os.Root, *Task, string, bool) {
|
||||
id := r.PathValue("id")
|
||||
n, err := strconv.ParseInt(id, 10, 64)
|
||||
if err != nil || n <= 0 || strconv.FormatInt(n, 10) != id {
|
||||
writeErr(w, 404, "taskFiles.unavailable")
|
||||
return nil, nil, "", false
|
||||
}
|
||||
t, ok := s.m.Task(id)
|
||||
if !ok {
|
||||
writeErr(w, 404, "taskFiles.unavailable")
|
||||
return nil, nil, "", false
|
||||
}
|
||||
rel, err := taskFilePath(r.URL.Query().Get("path"))
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return nil, nil, "", false
|
||||
}
|
||||
base, err := os.OpenRoot(s.m.dir)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return nil, nil, "", false
|
||||
}
|
||||
defer base.Close()
|
||||
name := "tasks/" + id
|
||||
info, err := base.Lstat(name)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, t, rel, true
|
||||
}
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return nil, nil, "", false
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
taskFileError(w, fs.ErrPermission)
|
||||
return nil, nil, "", false
|
||||
}
|
||||
root, err := base.OpenRoot(name)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return nil, nil, "", false
|
||||
}
|
||||
return root, t, rel, true
|
||||
}
|
||||
|
||||
func newTaskFileEntry(name string, info fs.FileInfo) taskFileEntry {
|
||||
return taskFileEntry{wsEntry: wsEntry{Name: path.Base(name), Path: name, Dir: info.IsDir(), Size: info.Size(), MTime: info.ModTime().UnixMilli()}, Symlink: info.Mode()&os.ModeSymlink != 0}
|
||||
}
|
||||
|
||||
func (s *Server) taskFilesList(w http.ResponseWriter, r *http.Request) {
|
||||
root, t, rel, ok := s.openTaskFiles(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out := taskFileListing{Path: rel, Entries: []taskFileEntry{}}
|
||||
if rel == "." {
|
||||
out.Path = ""
|
||||
}
|
||||
if root == nil {
|
||||
if rel != "." {
|
||||
taskFileError(w, fs.ErrNotExist)
|
||||
return
|
||||
}
|
||||
out.Missing = true
|
||||
writeJSON(w, 200, out)
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
dir, err := root.Open(rel)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
defer dir.Close()
|
||||
entries, err := dir.ReadDir(-1)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
info, err := e.Info()
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
entry := newTaskFileEntry(path.Join(rel, e.Name()), info)
|
||||
if rel == "." && entry.Dir && strings.HasPrefix(e.Name(), "i") && t.Store != nil {
|
||||
id, err := strconv.ParseInt(strings.TrimPrefix(e.Name(), "i"), 10, 64)
|
||||
if err == nil {
|
||||
node, err := t.Store.GetNode(id)
|
||||
if err != nil {
|
||||
writeErr(w, 500, "taskFiles.failed")
|
||||
return
|
||||
}
|
||||
if node != nil && node.Kind == "intent" {
|
||||
var payload map[string]any
|
||||
_ = json.Unmarshal(node.Payload, &payload)
|
||||
entry.IntentID, entry.IntentState = id, node.State
|
||||
entry.IntentTitle, _ = payload["summary"].(string)
|
||||
if entry.IntentTitle == "" {
|
||||
entry.IntentTitle, _ = payload["title"].(string)
|
||||
}
|
||||
if entry.IntentTitle == "" {
|
||||
entry.IntentTitle = rawString(node.Payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.Entries = append(out.Entries, entry)
|
||||
}
|
||||
sort.Slice(out.Entries, func(i, j int) bool {
|
||||
a, b := out.Entries[i], out.Entries[j]
|
||||
if a.Dir != b.Dir {
|
||||
return a.Dir
|
||||
}
|
||||
return a.Name < b.Name
|
||||
})
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// A bounded min-heap retains the newest entries over the ENTIRE scan, with a
|
||||
// deterministic path tie-breaker. Counts and bytes always describe all files.
|
||||
type recentTaskFiles []taskFileEntry
|
||||
|
||||
func newerTaskFile(a, b taskFileEntry) bool {
|
||||
return a.MTime > b.MTime || (a.MTime == b.MTime && a.Path < b.Path)
|
||||
}
|
||||
func (h recentTaskFiles) Len() int { return len(h) }
|
||||
func (h recentTaskFiles) Less(i, j int) bool { return newerTaskFile(h[j], h[i]) }
|
||||
func (h recentTaskFiles) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
func (h *recentTaskFiles) Push(x any) { *h = append(*h, x.(taskFileEntry)) }
|
||||
func (h *recentTaskFiles) Pop() any {
|
||||
old := *h
|
||||
n := len(old)
|
||||
x := old[n-1]
|
||||
*h = old[:n-1]
|
||||
return x
|
||||
}
|
||||
|
||||
func scanTaskFiles(r *http.Request, root *os.Root) (taskFileListing, error) {
|
||||
out := taskFileListing{Entries: []taskFileEntry{}}
|
||||
h := recentTaskFiles{}
|
||||
err := fs.WalkDir(root.FS(), ".", func(name string, d fs.DirEntry, err error) error {
|
||||
if r.Context().Err() != nil {
|
||||
return r.Context().Err()
|
||||
}
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
info, err := d.Info()
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
entry := newTaskFileEntry(name, info)
|
||||
out.Total++
|
||||
out.Size += info.Size()
|
||||
if len(h) < maxTaskFiles {
|
||||
heap.Push(&h, entry)
|
||||
} else if newerTaskFile(entry, h[0]) {
|
||||
h[0] = entry
|
||||
heap.Fix(&h, 0)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.Slice(h, func(i, j int) bool { return newerTaskFile(h[i], h[j]) })
|
||||
out.Entries = append(out.Entries, h...)
|
||||
out.Truncated = out.Total > maxTaskFiles
|
||||
return out, err
|
||||
}
|
||||
|
||||
func (s *Server) taskFilesAll(w http.ResponseWriter, r *http.Request) {
|
||||
root, _, _, ok := s.openTaskFiles(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if root == nil {
|
||||
writeJSON(w, 200, taskFileListing{Entries: []taskFileEntry{}, Missing: true})
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
out, err := scanTaskFiles(r, root)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
func (s *Server) taskFilesServe(w http.ResponseWriter, r *http.Request) {
|
||||
root, _, rel, ok := s.openTaskFiles(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if root == nil {
|
||||
taskFileError(w, fs.ErrNotExist)
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
// Inspect before opening to avoid blocking on FIFOs and other special files.
|
||||
info, err := root.Stat(rel)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
writeErr(w, 400, "taskFiles.notFile")
|
||||
return
|
||||
}
|
||||
f, err := root.Open(rel)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
info, err = f.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
writeErr(w, 400, "taskFiles.notFile")
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
switch path.Base(r.URL.Path) {
|
||||
case "read":
|
||||
writeTextFile(w, rel, f, info.Size())
|
||||
case "preview":
|
||||
types := map[string]string{".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif"}
|
||||
want := types[strings.ToLower(path.Ext(rel))]
|
||||
buf := make([]byte, 512)
|
||||
n, err := f.Read(buf)
|
||||
if err != nil && err != io.EOF {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
if want == "" || http.DetectContentType(buf[:n]) != want {
|
||||
writeErr(w, 415, "taskFiles.notImage")
|
||||
return
|
||||
}
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", want)
|
||||
setFileDisposition(w, "inline", path.Base(rel))
|
||||
http.ServeContent(w, r, path.Base(rel), info.ModTime(), f)
|
||||
case "download":
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
setFileDisposition(w, "attachment", path.Base(rel))
|
||||
http.ServeContent(w, r, path.Base(rel), info.ModTime(), f)
|
||||
}
|
||||
}
|
||||
|
||||
// Each directory gets a nested root; symlinks are skipped and every file is
|
||||
// opened through the root. Entries are copied directly into the ZIP stream.
|
||||
func writeTaskFilesZip(r *http.Request, zw *zip.Writer, root *os.Root, prefix string) error {
|
||||
d, err := root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer d.Close()
|
||||
for {
|
||||
entries, err := d.ReadDir(128)
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if err := r.Context().Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
info, err := root.Lstat(e.Name())
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
continue
|
||||
}
|
||||
name := path.Join(prefix, e.Name())
|
||||
// ZIP names must remain relative and portable when extracted on
|
||||
// Windows too, even if the producer ran on a Unix filesystem.
|
||||
if _, err := taskFilePath(name); err != nil {
|
||||
continue
|
||||
}
|
||||
if info.IsDir() {
|
||||
sub, err := root.OpenRoot(e.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = zw.Create(name + "/")
|
||||
if err == nil {
|
||||
err = writeTaskFilesZip(r, zw, sub, name)
|
||||
}
|
||||
sub.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if info.Mode().IsRegular() {
|
||||
f, err := root.Open(e.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header, err := zip.FileInfoHeader(info)
|
||||
if err == nil {
|
||||
header.Name, header.Method = name, zip.Deflate
|
||||
var out io.Writer
|
||||
out, err = zw.CreateHeader(header)
|
||||
if err == nil {
|
||||
_, err = io.Copy(out, f)
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) taskFilesArchive(w http.ResponseWriter, r *http.Request) {
|
||||
root, t, rel, ok := s.openTaskFiles(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if root == nil {
|
||||
taskFileError(w, fs.ErrNotExist)
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
info, err := root.Lstat(rel)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
if !info.IsDir() {
|
||||
writeErr(w, 400, "taskFiles.notDirectory")
|
||||
return
|
||||
}
|
||||
sub, err := root.OpenRoot(rel)
|
||||
if err != nil {
|
||||
taskFileError(w, err)
|
||||
return
|
||||
}
|
||||
defer sub.Close()
|
||||
name := path.Base(rel)
|
||||
if rel == "." {
|
||||
name = fmt.Sprintf("task-%s", t.ID)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
setFileDisposition(w, "attachment", name+".zip")
|
||||
if r.Method == http.MethodHead {
|
||||
return
|
||||
}
|
||||
zw := zip.NewWriter(w)
|
||||
if err := writeTaskFilesZip(r, zw, sub, ""); err != nil {
|
||||
// Never finalize a partial ZIP as a successful download.
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// These tests need no database: the task registry and a temporary run directory
|
||||
// exercise the same filesystem handlers used by the authenticated production mux.
|
||||
func taskFilesFixture(t *testing.T) (*Server, string, func(string, string, string) *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
base := t.TempDir()
|
||||
m := &Manager{dir: base, tasks: map[string]*Task{"313": {ID: "313"}}}
|
||||
s := &Server{m: m}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files", s.taskFilesList)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/all", s.taskFilesAll)
|
||||
for _, action := range []string{"read", "download", "preview"} {
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/"+action, s.taskFilesServe)
|
||||
}
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/archive", s.taskFilesArchive)
|
||||
run := filepath.Join(base, "tasks", "313")
|
||||
request := func(id, action, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
target := "/api/tasks/" + id + "/files"
|
||||
if action != "" {
|
||||
target += "/" + action
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest("GET", target+"?path="+url.QueryEscape(path), nil))
|
||||
return rec
|
||||
}
|
||||
return s, run, request
|
||||
}
|
||||
func taskFileWrite(t *testing.T, base, name string, data []byte) {
|
||||
t.Helper()
|
||||
p := filepath.Join(base, name)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func taskFileListingResult(t *testing.T, rec *httptest.ResponseRecorder) taskFileListing {
|
||||
t.Helper()
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var result taskFileListing
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
func TestTaskFilesValidationAndMissing(t *testing.T) {
|
||||
_, run, get := taskFilesFixture(t)
|
||||
for _, id := range []string{"abc", "-1", "0", "0313", "99999999999999999999", "314"} {
|
||||
if r := get(id, "", ""); r.Code != 404 {
|
||||
t.Errorf("%s status %d", id, r.Code)
|
||||
}
|
||||
}
|
||||
for _, action := range []string{"", "all"} {
|
||||
got := taskFileListingResult(t, get("313", action, ""))
|
||||
if !got.Missing || got.Total != 0 || len(got.Entries) != 0 {
|
||||
t.Fatalf("missing: %+v", got)
|
||||
}
|
||||
}
|
||||
if r := get("313", "read", "missing"); r.Code != 404 {
|
||||
t.Fatal(r.Code)
|
||||
}
|
||||
taskFileWrite(t, run, "ok.txt", []byte("safe"))
|
||||
for _, path := range []string{"../secret", "a/../../secret", "/etc/passwd", "C:/secret", `..\secret`, "a//b", "a/../ok.txt", "a\x00b"} {
|
||||
for _, action := range []string{"", "all", "read", "download", "preview", "archive"} {
|
||||
if r := get("313", action, path); r.Code != 400 {
|
||||
t.Errorf("%s %q status %d", action, path, r.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, action := range []string{"", "read", "download", "archive"} {
|
||||
if r := get("313", action, "missing"); r.Code != 404 {
|
||||
t.Errorf("%s missing %d", action, r.Code)
|
||||
}
|
||||
}
|
||||
if err := os.RemoveAll(run); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := get("313", "download", "ok.txt"); r.Code != 404 {
|
||||
t.Fatal(r.Code)
|
||||
}
|
||||
}
|
||||
func TestTaskFilesSymlinkIsolationAndZip(t *testing.T) {
|
||||
s, run, get := taskFilesFixture(t)
|
||||
taskFileWrite(t, run, "nested/hello.txt", []byte("hello"))
|
||||
taskFileWrite(t, run, ".hidden", []byte("hidden"))
|
||||
taskFileWrite(t, run, `..\unsafe.txt`, []byte("unsafe ZIP name"))
|
||||
outside := t.TempDir()
|
||||
taskFileWrite(t, outside, "secret.txt", []byte("SECRET"))
|
||||
for name, target := range map[string]string{"escape.txt": filepath.Join(outside, "secret.txt"), "escape-dir": outside, "inside": "nested/hello.txt"} {
|
||||
if err := os.Symlink(target, filepath.Join(run, name)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"escape.txt", "escape-dir/secret.txt"} {
|
||||
for _, action := range []string{"read", "download", "preview", "archive"} {
|
||||
if r := get("313", action, name); r.Code == 200 {
|
||||
t.Errorf("escaped %s %s", action, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if r := get("313", "", "escape-dir"); r.Code == 200 {
|
||||
t.Fatal("directory escape")
|
||||
}
|
||||
listing := taskFileListingResult(t, get("313", "", ""))
|
||||
links := 0
|
||||
for _, e := range listing.Entries {
|
||||
if e.Symlink {
|
||||
links++
|
||||
}
|
||||
}
|
||||
if links != 3 {
|
||||
t.Fatalf("links=%d", links)
|
||||
}
|
||||
if r := get("313", "read", "inside"); r.Code != 200 || !strings.Contains(r.Body.String(), "hello") {
|
||||
t.Fatalf("internal link %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
all := taskFileListingResult(t, get("313", "all", ""))
|
||||
if all.Total != 3 || all.Size != 26 {
|
||||
t.Fatalf("all: %+v", all)
|
||||
}
|
||||
for _, dir := range []string{"", "nested"} {
|
||||
rec := get("313", "archive", dir)
|
||||
if rec.Code != 200 || rec.Header().Get("Content-Type") != "application/zip" {
|
||||
t.Fatal(rec.Code)
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(rec.Body.Bytes()), int64(rec.Body.Len()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, entry := range zr.File {
|
||||
if strings.Contains(entry.Name, "escape") || entry.Name == "inside" || strings.Contains(entry.Name, "\\") {
|
||||
t.Fatalf("zipped link %s", entry.Name)
|
||||
}
|
||||
if strings.HasSuffix(entry.Name, "hello.txt") {
|
||||
f, err := entry.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := io.ReadAll(f)
|
||||
f.Close()
|
||||
if err != nil || string(data) != "hello" {
|
||||
t.Fatalf("ZIP contents %q %v", data, err)
|
||||
}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("missing file in zip")
|
||||
}
|
||||
}
|
||||
// A symlink used as the task root must not be followed either.
|
||||
s.m.tasks["314"] = &Task{ID: "314"}
|
||||
if err := os.Symlink(outside, filepath.Join(filepath.Dir(run), "314")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := get("314", "read", "secret.txt"); r.Code == 200 {
|
||||
t.Fatal("task root escaped")
|
||||
}
|
||||
}
|
||||
func TestTaskFilesTextAndPreview(t *testing.T) {
|
||||
_, run, get := taskFilesFixture(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
data []byte
|
||||
binary, large bool
|
||||
}{
|
||||
{"empty", nil, false, false}, {"utf8", []byte("文本\n"), false, false},
|
||||
{"nul", []byte{'a', 0}, true, false}, {"invalid", []byte{0xff}, true, false},
|
||||
{"boundary", bytes.Repeat([]byte{'a'}, maxWorkspaceRead), false, false},
|
||||
{"large", bytes.Repeat([]byte{'a'}, maxWorkspaceRead+1), true, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
taskFileWrite(t, run, tc.name, tc.data)
|
||||
var got struct {
|
||||
Binary bool `json:"binary"`
|
||||
Large bool `json:"too_large"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
rec := get("313", "read", tc.name)
|
||||
if rec.Code != 200 {
|
||||
t.Fatal(rec.Code)
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Binary != tc.binary || got.Large != tc.large || (!tc.binary && got.Content != string(tc.data)) {
|
||||
t.Fatalf("%s flags %v/%v", tc.name, got.Binary, got.Large)
|
||||
}
|
||||
}
|
||||
// Content and extension must agree; HTML/SVG never render inline.
|
||||
for _, name := range []string{"x.html", "x.svg", "spoof.png"} {
|
||||
taskFileWrite(t, run, name, []byte("<html>unsafe</html>"))
|
||||
if r := get("313", "preview", name); r.Code != 415 {
|
||||
t.Fatalf("%s %d", name, r.Code)
|
||||
}
|
||||
}
|
||||
var imageData bytes.Buffer
|
||||
if err := png.Encode(&imageData, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskFileWrite(t, run, "image.png", imageData.Bytes())
|
||||
rec := get("313", "preview", "image.png")
|
||||
if rec.Code != 200 || rec.Header().Get("Content-Type") != "image/png" || rec.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||
t.Fatalf("preview %d %v", rec.Code, rec.Header())
|
||||
}
|
||||
rec = get("313", "download", "spoof.png")
|
||||
if rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Disposition"), "attachment;") || rec.Header().Get("Content-Type") != "application/octet-stream" {
|
||||
t.Fatalf("download %d %v", rec.Code, rec.Header())
|
||||
}
|
||||
// Simulate growth after the stat: the shared reader must still cap allocation.
|
||||
rec = httptest.NewRecorder()
|
||||
writeTextFile(rec, "growing", bytes.NewReader(bytes.Repeat([]byte{'a'}, maxWorkspaceRead+100)), 1)
|
||||
if !strings.Contains(rec.Body.String(), `"too_large":true`) {
|
||||
t.Fatal("growing file not capped")
|
||||
}
|
||||
}
|
||||
func TestTaskFilesRecentTruncation(t *testing.T) {
|
||||
_, run, get := taskFilesFixture(t)
|
||||
stamp := time.Unix(1700000000, 0)
|
||||
for i := 0; i < 2005; i++ {
|
||||
name := fmt.Sprintf("%04d.txt", i)
|
||||
taskFileWrite(t, run, name, []byte("x"))
|
||||
tm := stamp.Add(time.Duration(i) * time.Second)
|
||||
if err := os.Chtimes(filepath.Join(run, name), tm, tm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
all := taskFileListingResult(t, get("313", "all", ""))
|
||||
if !all.Truncated || all.Total != 2005 || all.Size != 2005 || len(all.Entries) != 2000 {
|
||||
t.Fatalf("counts: total=%d entries=%d truncated=%v", all.Total, len(all.Entries), all.Truncated)
|
||||
}
|
||||
if all.Entries[0].Name != "2004.txt" || all.Entries[1999].Name != "0005.txt" {
|
||||
t.Fatal("truncated before sorting")
|
||||
}
|
||||
for i := 1; i < len(all.Entries); i++ {
|
||||
if newerTaskFile(all.Entries[i], all.Entries[i-1]) {
|
||||
t.Fatal("not sorted")
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
root, err := os.OpenRoot(run)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
if _, err := scanTaskFiles(httptest.NewRequest("GET", "/", nil).WithContext(ctx), root); err == nil {
|
||||
t.Fatal("ignored cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskFilesAuthAndHead(t *testing.T) {
|
||||
s, run, _ := taskFilesFixture(t)
|
||||
s.jwtKey = []byte("task-files-test-signing-key")
|
||||
taskFileWrite(t, run, "readme.txt", []byte("read only"))
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files", s.taskFilesList)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/all", s.taskFilesAll)
|
||||
for _, action := range []string{"read", "download", "preview"} {
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/"+action, s.taskFilesServe)
|
||||
}
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/archive", s.taskFilesArchive)
|
||||
handler := s.requireAuth(mux)
|
||||
for _, action := range []string{"", "/all", "/read", "/download", "/preview", "/archive"} {
|
||||
req := httptest.NewRequest("GET", "/api/tasks/313/files"+action+"?path=readme.txt", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != 401 {
|
||||
t.Fatalf("unauthenticated %s: %d", action, rec.Code)
|
||||
}
|
||||
}
|
||||
token, err := signJWT(s.jwtKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, action := range []string{"archive", "download"} {
|
||||
path := "readme.txt"
|
||||
if action == "archive" {
|
||||
path = ""
|
||||
}
|
||||
req := httptest.NewRequest("HEAD", "/api/tasks/313/files/"+action+"?path="+path, nil)
|
||||
req.AddCookie(&http.Cookie{Name: "artex_token", Value: token})
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 || rec.Body.Len() != 0 {
|
||||
t.Fatalf("HEAD %s %d body=%d", action, rec.Code, rec.Body.Len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Opt-in, strictly read-only smoke check against an existing run directory.
|
||||
func TestTaskFilesRealDirectory(t *testing.T) {
|
||||
base := os.Getenv("ARTEX_TASK_FILES_TEST_DIR")
|
||||
if base == "" {
|
||||
t.Skip("set ARTEX_TASK_FILES_TEST_DIR to read an existing task 313 directory")
|
||||
}
|
||||
m := &Manager{dir: base, tasks: map[string]*Task{"313": {ID: "313"}}}
|
||||
s := &Server{m: m}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files", s.taskFilesList)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/all", s.taskFilesAll)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/read", s.taskFilesServe)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/download", s.taskFilesServe)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/preview", s.taskFilesServe)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/files/archive", s.taskFilesArchive)
|
||||
get := func(action, path string) *httptest.ResponseRecorder {
|
||||
target := "/api/tasks/313/files"
|
||||
if action != "" {
|
||||
target += "/" + action
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest("GET", target+"?path="+url.QueryEscape(path), nil))
|
||||
return rec
|
||||
}
|
||||
root := taskFileListingResult(t, get("", ""))
|
||||
all := taskFileListingResult(t, get("all", ""))
|
||||
if len(root.Entries) == 0 || all.Total == 0 {
|
||||
t.Fatal("real directory is empty")
|
||||
}
|
||||
textChecked, imageChecked := false, false
|
||||
for _, entry := range all.Entries {
|
||||
if !textChecked && strings.HasSuffix(entry.Path, ".txt") {
|
||||
if rec := get("read", entry.Path); rec.Code != 200 {
|
||||
t.Fatal("real text preview", rec.Code)
|
||||
}
|
||||
rec := get("download", entry.Path)
|
||||
data, err := os.ReadFile(filepath.Join(base, "tasks", "313", entry.Path))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec.Code != 200 || !bytes.Equal(rec.Body.Bytes(), data) {
|
||||
t.Fatal("real download mismatch")
|
||||
}
|
||||
textChecked = true
|
||||
}
|
||||
if !imageChecked && strings.HasSuffix(entry.Path, ".jpg") {
|
||||
if rec := get("preview", entry.Path); rec.Code == 200 {
|
||||
imageChecked = true
|
||||
}
|
||||
}
|
||||
}
|
||||
rec := get("archive", "")
|
||||
if rec.Code != 200 {
|
||||
t.Fatal("real zip", rec.Code)
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(rec.Body.Bytes()), int64(rec.Body.Len()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count := 0
|
||||
for _, file := range zr.File {
|
||||
if file.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
f, err := file.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = io.Copy(io.Discard, f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count++
|
||||
}
|
||||
if count != all.Total || !textChecked {
|
||||
t.Fatalf("real smoke: zip=%d total=%d text=%v", count, all.Total, textChecked)
|
||||
}
|
||||
t.Logf("read-only task 313: root entries=%d files=%d bytes=%d zip files=%d text/download=%v valid JPEG=%v", len(root.Entries), all.Total, all.Size, count, textChecked, imageChecked)
|
||||
}
|
||||
|
||||
func TestTaskFilesIntentMetadata(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("isolated PostgreSQL required: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
task, err := m.CreateTask("task files metadata", "", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
numericID, _ := strconv.ParseInt(task.ID, 10, 64)
|
||||
defer m.pg.DeleteTask(numericID)
|
||||
id, err := task.Store.AddIntent(map[string]any{"summary": "Readable intent title"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := filepath.Join(m.dir, "tasks", task.ID)
|
||||
taskFileWrite(t, run, fmt.Sprintf("i%d/output.txt", id), []byte("result"))
|
||||
req := httptest.NewRequest("GET", "/api/tasks/"+task.ID+"/files", nil)
|
||||
req.SetPathValue("id", task.ID)
|
||||
rec := httptest.NewRecorder()
|
||||
(&Server{m: m}).taskFilesList(rec, req)
|
||||
listing := taskFileListingResult(t, rec)
|
||||
if len(listing.Entries) != 1 || listing.Entries[0].IntentID != id || listing.Entries[0].IntentTitle != "Readable intent title" || listing.Entries[0].IntentState != "open" {
|
||||
t.Fatalf("intent metadata: %+v", listing.Entries)
|
||||
}
|
||||
}
|
||||
+4
-14
@@ -1,18 +1,15 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Workspace file manager — browse / view / edit / download / upload / delete the
|
||||
@@ -119,20 +116,13 @@ func (s *Server) wsRead(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, "是目录,不能作为文件读取")
|
||||
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 := os.ReadFile(abs)
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
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)})
|
||||
defer f.Close()
|
||||
writeTextFile(w, s.wsRel(abs), f, fi.Size())
|
||||
}
|
||||
|
||||
// POST /api/workspace/write {path, content} — create/overwrite a text file.
|
||||
@@ -223,7 +213,7 @@ func (s *Server) wsDownload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
name := filepath.Base(abs)
|
||||
// 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))
|
||||
setFileDisposition(w, "attachment", name)
|
||||
http.ServeFile(w, r, abs)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user