Add contained home file endpoint

This commit is contained in:
2026-11-07 00:53:15 +00:00
parent f4ba2ab25e
commit bfe89432bb
6 changed files with 225 additions and 1 deletions
+7
View File
@@ -0,0 +1,7 @@
# Files panel
The server's `GET /files?path=...` endpoint serves one regular file for the
client files panel. Paths may be absolute or `~`-prefixed, and are resolved
through the operator home directory; cleaned paths and symlinks are required to
remain inside that home subtree. Directories, special files, and escape paths
are refused. Add `download=1` to request attachment disposition.
+1
View File
@@ -17,6 +17,7 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
- `internal/server/websocket.go` — the `/connect` transport and the request dispatch. Envelope
validation lives here; every command returns its own typed reply.
- `internal/server/home_files.go` — the contained `/files` endpoint for regular files under the operator home.
- `internal/server/runner.go` — run execution: the stage loop, stage outcomes, budgets, retries,
ownership and settlement. This is where a run's state changes.
- `internal/server/runevents.go` — the push hub: subscriptions scoped per workspace, per-run frames,
+5 -1
View File
@@ -442,7 +442,7 @@ func resolveChatDirectory(directory string) (string, error) {
// location. It is resolved through the standard library so it never falls back
// to the process working directory.
func OperatorHomeDirectory() (string, error) {
home, err := os.UserHomeDir()
home, err := operatorHomeDirectory()
if err != nil {
return "", errors.New("resolve operator home directory: " + err.Error())
}
@@ -451,3 +451,7 @@ func OperatorHomeDirectory() (string, error) {
}
return home, nil
}
// operatorHomeDirectory is a seam for tests of filesystem endpoints that are
// rooted at the operator's home directory.
var operatorHomeDirectory = os.UserHomeDir
+123
View File
@@ -0,0 +1,123 @@
package server
import (
"errors"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
)
func serveHomeFile(w http.ResponseWriter, r *http.Request) {
home, err := OperatorHomeDirectory()
if err != nil {
http.NotFound(w, r)
return
}
serveHomeFileFrom(w, r, home)
}
func serveHomeFileFrom(w http.ResponseWriter, r *http.Request, home string) {
home = filepath.Clean(home)
realHome, err := filepath.EvalSymlinks(home)
if err != nil {
http.NotFound(w, r)
return
}
target, err := expandHomePath(home, r.URL.Query().Get("path"))
if err != nil {
http.Error(w, "file not found", http.StatusNotFound)
return
}
_, realTarget, err := resolveInsideHome(realHome, target)
if err != nil {
if strings.Contains(err.Error(), "outside the home directory") {
http.Error(w, "file access denied", http.StatusForbidden)
} else {
http.NotFound(w, r)
}
return
}
info, err := os.Stat(realTarget)
if err != nil {
http.NotFound(w, r)
return
}
if info.IsDir() || !info.Mode().IsRegular() {
http.NotFound(w, r)
return
}
if specialFilesystem(realTarget) {
http.Error(w, "file access denied", http.StatusForbidden)
return
}
file, err := os.Open(realTarget)
if err != nil {
if errors.Is(err, os.ErrPermission) {
http.Error(w, "file access denied", http.StatusForbidden)
} else {
http.NotFound(w, r)
}
return
}
defer file.Close()
w.Header().Set("Cache-Control", "private, no-cache")
w.Header().Set("X-Content-Type-Options", "nosniff")
contentType := mime.TypeByExtension(filepath.Ext(realTarget))
if contentType == "" {
var sample [512]byte
n, readErr := file.Read(sample[:])
if readErr != nil && !errors.Is(readErr, io.EOF) {
http.NotFound(w, r)
return
}
contentType = http.DetectContentType(sample[:n])
if _, err := file.Seek(0, io.SeekStart); err != nil {
http.NotFound(w, r)
return
}
}
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
disposition := "inline"
if r.URL.Query().Get("download") == "1" {
disposition = "attachment"
}
w.Header().Set("Content-Disposition", contentDisposition(disposition, filepath.Base(realTarget)))
http.ServeContent(w, r, filepath.Base(realTarget), info.ModTime(), file)
}
func contentDisposition(kind, filename string) string {
// The ASCII fallback keeps older clients useful; filename* preserves the
// actual name for clients that implement RFC 6266/RFC 5987.
fallback := strings.Map(func(r rune) rune {
if r < 0x20 || r > 0x7e || r == '"' || r == '\\' {
return '_'
}
return r
}, filename)
if fallback == "" {
fallback = "file"
}
return kind + `; filename="` + fallback + `"; filename*=UTF-8''` + rfc5987(filename)
}
func rfc5987(value string) string {
const hex = "0123456789ABCDEF"
var b strings.Builder
for _, c := range []byte(value) {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strings.ContainsRune("!#$&+-.^_`|~", rune(c)) {
b.WriteByte(c)
} else {
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&15])
}
}
return b.String()
}
+88
View File
@@ -0,0 +1,88 @@
package server
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestServeHomeFile(t *testing.T) {
root := t.TempDir()
home := filepath.Join(root, "home")
outside := filepath.Join(root, "outside.txt")
if err := os.Mkdir(home, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(home, "hello.txt"), []byte("hello file contents"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(home, "résumé"), []byte("plain"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(home, "escape")); err != nil {
t.Fatal(err)
}
originalHomeDirectory := operatorHomeDirectory
operatorHomeDirectory = func() (string, error) { return home, nil }
t.Cleanup(func() { operatorHomeDirectory = originalHomeDirectory })
t.Run("operator home seam", func(t *testing.T) {
recorder := httptest.NewRecorder()
serveHomeFile(recorder, httptest.NewRequest(http.MethodGet, "/files?path=~/hello.txt", nil))
if recorder.Code != http.StatusOK || recorder.Body.String() != "hello file contents" {
t.Fatalf("response = %d %q", recorder.Code, recorder.Body.String())
}
})
tests := []struct {
name string
path string
want int
}{
{"happy path", "~/hello.txt", http.StatusOK},
{"directory refused", "~", http.StatusNotFound},
{"dot dot refused", filepath.Join(home, "..", "outside.txt"), http.StatusForbidden},
{"symlink refused", "~/escape", http.StatusForbidden},
{"missing file", "~/missing", http.StatusNotFound},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/files?path="+tc.path, nil)
recorder := httptest.NewRecorder()
serveHomeFileFrom(recorder, req, home)
if recorder.Code != tc.want {
t.Fatalf("status = %d, want %d", recorder.Code, tc.want)
}
})
}
t.Run("download disposition and range", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/files?path=~/hello.txt&download=1", nil)
req.Header.Set("Range", "bytes=0-4")
recorder := httptest.NewRecorder()
serveHomeFileFrom(recorder, req, home)
if recorder.Code != http.StatusPartialContent || recorder.Body.String() != "hello" {
t.Fatalf("response = %d %q, want 206 hello", recorder.Code, recorder.Body.String())
}
if got := recorder.Header().Get("Content-Disposition"); got != `attachment; filename="hello.txt"; filename*=UTF-8''hello.txt` {
t.Fatalf("disposition = %q", got)
}
if recorder.Header().Get("Content-Type") != "text/plain; charset=utf-8" {
t.Fatalf("content type = %q", recorder.Header().Get("Content-Type"))
}
})
t.Run("non ASCII disposition", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/files?path=~/r%C3%A9sum%C3%A9", nil)
recorder := httptest.NewRecorder()
serveHomeFileFrom(recorder, req, home)
if !strings.Contains(recorder.Header().Get("Content-Disposition"), "filename*=UTF-8''r%C3%A9sum%C3%A9") {
t.Fatal(recorder.Header().Get("Content-Disposition"))
}
})
}
+1
View File
@@ -154,6 +154,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}
runs.serveArtifact(w, r)
})
mux.HandleFunc("GET /files", serveHomeFile)
mux.HandleFunc("POST /chat-uploads", serveChatUpload)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")