Add a home-restricted folder picker to the new-chat dialog

Server: list_directory returns a directory_listing (path, home, parent,
entries with is_dir/is_git_repo/hidden, truncated) confined to the server
user's home subtree after cleaning and resolving symlinks, refusing pseudo
filesystems and capping entries at 2000. Documented in docs/cli.md.

App: "Choose folder…" in the create dialog opens a picker (full-screen page
on phones, large dialog on wide windows, Material and Cupertino) with
breadcrumbs, filter, Show hidden, git badges, dimmed files, recent folders,
inline errors and "Start chat here". The probe app gains a folder fixture
for captures.
This commit is contained in:
2026-11-01 21:51:48 +00:00
parent eadd017bdc
commit eed3806efb
25 changed files with 2333 additions and 9 deletions
+26
View File
@@ -0,0 +1,26 @@
//go:build darwin
package server
import "syscall"
// specialFilesystem reports whether path lives on a pseudo filesystem (devfs,
// autofs, fdesc) that a folder picker must never list.
func specialFilesystem(path string) bool {
var stat syscall.Statfs_t
if err := syscall.Statfs(path, &stat); err != nil {
return false
}
name := make([]byte, 0, len(stat.Fstypename))
for _, c := range stat.Fstypename {
if c == 0 {
break
}
name = append(name, byte(c))
}
switch string(name) {
case "devfs", "autofs", "fdesc":
return true
}
return false
}
+31
View File
@@ -0,0 +1,31 @@
//go:build linux
package server
import "syscall"
// Filesystem magic numbers (linux/magic.h) for kernel pseudo filesystems that
// a folder picker must never list.
var specialFilesystemMagic = map[int64]struct{}{
0x9fa0: {}, // proc
0x62656572: {}, // sysfs
0x1cd1: {}, // devpts
0x64626720: {}, // debugfs
0x74726163: {}, // tracefs
0x27e0eb: {}, // cgroup
0x63677270: {}, // cgroup2
0xf97cff8c: {}, // selinuxfs
0x73636673: {}, // securityfs
0xcafe4a11: {}, // bpf
0x65735546: {}, // fuse control
}
// specialFilesystem reports whether path lives on a kernel pseudo filesystem.
func specialFilesystem(path string) bool {
var stat syscall.Statfs_t
if err := syscall.Statfs(path, &stat); err != nil {
return false
}
_, ok := specialFilesystemMagic[int64(stat.Type)]
return ok
}
+6
View File
@@ -0,0 +1,6 @@
//go:build !linux && !darwin
package server
// specialFilesystem has no pseudo-filesystem probe on this platform.
func specialFilesystem(string) bool { return false }
+200
View File
@@ -0,0 +1,200 @@
package server
import (
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// directoryListingScanLimit bounds how many names one list_directory reads
// before sorting, so a huge directory cannot make the server read without end.
// The reply itself is capped at protocol.DirectoryListingMaxEntries.
const directoryListingScanLimit = 5 * protocol.DirectoryListingMaxEntries
// handleDirectoryListing answers list_directory. It returns true when the
// request was a list_directory and has been answered.
func handleDirectoryListing(request protocol.Message, write func(protocol.Message) error) bool {
if request.Type != protocol.ListDirectory {
return false
}
path := ""
if request.ListDirectory != nil {
path = request.ListDirectory.Path
}
home, err := OperatorHomeDirectory()
if err == nil {
var listing protocol.DirectoryListingResult
listing, err = listHomeDirectory(home, path, protocol.DirectoryListingMaxEntries)
if err == nil {
_ = write(protocol.Message{Type: protocol.DirectoryListing, ID: request.ID, DirectoryListing: &listing})
return true
}
}
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return true
}
// listHomeDirectory lists one directory inside home. The requested path is
// cleaned and its symlinks resolved before the containment check, so neither
// ".." nor a symlink can escape home. The listed path is reported under home
// (as the operator sees it) even when home itself is reached through a link.
func listHomeDirectory(home, requested string, maxEntries int) (protocol.DirectoryListingResult, error) {
home = filepath.Clean(home)
realHome, err := filepath.EvalSymlinks(home)
if err != nil {
return protocol.DirectoryListingResult{}, errors.New("resolve home directory: " + err.Error())
}
target, err := expandHomePath(home, requested)
if err != nil {
return protocol.DirectoryListingResult{}, err
}
rel, realTarget, err := resolveInsideHome(realHome, target)
if err != nil {
return protocol.DirectoryListingResult{}, err
}
shown := filepath.Join(home, rel)
info, err := os.Stat(realTarget)
if err != nil {
return protocol.DirectoryListingResult{}, describePathError(shown, err)
}
if !info.IsDir() {
return protocol.DirectoryListingResult{}, errors.New(shown + " is not a directory")
}
if specialFilesystem(realTarget) {
return protocol.DirectoryListingResult{}, errors.New(shown + " is on a special filesystem and cannot be listed")
}
entries, truncated, err := readDirectoryEntries(realHome, realTarget, shown, maxEntries)
if err != nil {
return protocol.DirectoryListingResult{}, err
}
result := protocol.DirectoryListingResult{Path: shown, Home: home, Entries: entries, Truncated: truncated}
if rel != "." {
parent := filepath.Dir(shown)
result.Parent = &parent
}
return result, nil
}
// expandHomePath turns "", "~" and "~/sub" into paths under home and requires
// anything else to be absolute. "~user" forms are refused.
func expandHomePath(home, requested string) (string, error) {
requested = strings.TrimSpace(requested)
switch {
case requested == "" || requested == "~":
return home, nil
case strings.HasPrefix(requested, "~/"):
return filepath.Join(home, requested[2:]), nil
case strings.HasPrefix(requested, "~"):
return "", errors.New("path " + requested + " must be absolute or start with ~/")
case !filepath.IsAbs(requested):
return "", errors.New("path " + requested + " must be absolute or start with ~")
}
return filepath.Clean(requested), nil
}
// resolveInsideHome resolves every symlink in target and returns its path
// relative to realHome, refusing anything outside the home subtree.
func resolveInsideHome(realHome, target string) (string, string, error) {
realTarget, err := filepath.EvalSymlinks(target)
if err != nil {
return "", "", describePathError(target, err)
}
rel, ok := relInside(realHome, realTarget)
if !ok {
return "", "", errors.New("path " + target + " is outside the home directory " + realHome + "; only folders inside home can be listed")
}
return rel, realTarget, nil
}
func relInside(root, path string) (string, bool) {
rel, err := filepath.Rel(root, path)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
return "", false
}
return rel, true
}
func describePathError(path string, err error) error {
switch {
case errors.Is(err, fs.ErrPermission):
return errors.New("permission denied: " + path)
case errors.Is(err, fs.ErrNotExist):
return errors.New(path + " does not exist")
}
return errors.New(path + " is not available: " + err.Error())
}
// readDirectoryEntries reads at most directoryListingScanLimit names, sorts
// directories first then case-insensitively, and caps the result. Only names
// and kinds are read; no file is opened.
func readDirectoryEntries(realHome, realDir, shown string, maxEntries int) ([]protocol.DirectoryEntry, bool, error) {
dir, err := os.Open(realDir)
if err != nil {
return nil, false, describePathError(shown, err)
}
defer dir.Close()
items, err := dir.ReadDir(directoryListingScanLimit + 1)
if err != nil && !errors.Is(err, io.EOF) {
return nil, false, describePathError(shown, err)
}
truncated := len(items) > directoryListingScanLimit
if truncated {
items = items[:directoryListingScanLimit]
}
entries := make([]protocol.DirectoryEntry, 0, len(items))
for _, item := range items {
entries = append(entries, describeEntry(realHome, realDir, shown, item))
}
sort.SliceStable(entries, func(i, j int) bool {
a, b := entries[i], entries[j]
if a.IsDir != b.IsDir {
return a.IsDir
}
la, lb := strings.ToLower(a.Name), strings.ToLower(b.Name)
if la != lb {
return la < lb
}
return a.Name < b.Name
})
if len(entries) > maxEntries {
entries = entries[:maxEntries]
truncated = true
}
return entries, truncated, nil
}
// describeEntry classifies one name. A symlink counts as a directory only when
// it resolves to a directory still inside home; one that escapes is shown as a
// plain, non-selectable name. Devices, sockets and pipes are plain names too.
func describeEntry(realHome, realDir, shown string, item fs.DirEntry) protocol.DirectoryEntry {
name := item.Name()
entry := protocol.DirectoryEntry{Name: name, Path: filepath.Join(shown, name), Hidden: strings.HasPrefix(name, ".")}
full := filepath.Join(realDir, name)
switch {
case item.IsDir():
entry.IsDir = true
case item.Type()&fs.ModeSymlink != 0:
resolved, err := filepath.EvalSymlinks(full)
if err != nil {
break
}
if _, ok := relInside(realHome, resolved); !ok {
break
}
if info, err := os.Stat(resolved); err == nil && info.IsDir() {
entry.IsDir = true
}
}
if entry.IsDir {
if _, err := os.Lstat(filepath.Join(full, ".git")); err == nil {
entry.IsGitRepo = true
}
}
return entry
}
+232
View File
@@ -0,0 +1,232 @@
package server
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/coder/websocket/wsjson"
)
// newListingHome builds a scratch home: folders of mixed case, a hidden folder,
// a git repository, files, and an outside directory next to (not inside) home.
func newListingHome(t *testing.T) (home, outside string) {
t.Helper()
root := t.TempDir()
home = filepath.Join(root, "home")
outside = filepath.Join(root, "outside")
for _, dir := range []string{"zeta", "Alpha", "beta", ".config", "repo/.git", "repo/src"} {
mustMkdir(t, filepath.Join(home, dir))
}
mustMkdir(t, outside)
for _, file := range []string{"Notes.txt", "a.md", ".profile", "repo/README.md"} {
if err := os.WriteFile(filepath.Join(home, file), []byte("secret contents"), 0o644); err != nil {
t.Fatal(err)
}
}
return home, outside
}
func mustMkdir(t *testing.T, path string) {
t.Helper()
if err := os.MkdirAll(path, 0o755); err != nil {
t.Fatal(err)
}
}
func entryNames(entries []protocol.DirectoryEntry) []string {
names := make([]string, 0, len(entries))
for _, entry := range entries {
names = append(names, entry.Name)
}
return names
}
func TestListDirectoryHomeSortsDirectoriesFirstAndMarksHiddenAndRepos(t *testing.T) {
home, _ := newListingHome(t)
for _, requested := range []string{"", "~", home, home + "/"} {
listing, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries)
if err != nil {
t.Fatalf("%q: %v", requested, err)
}
if listing.Path != home || listing.Home != home || listing.Parent != nil || listing.Truncated {
t.Fatalf("%q: header = %+v", requested, listing)
}
got := strings.Join(entryNames(listing.Entries), ",")
if want := ".config,Alpha,beta,repo,zeta,.profile,a.md,Notes.txt"; got != want {
t.Fatalf("%q: order = %s, want %s", requested, got, want)
}
}
listing, _ := listHomeDirectory(home, "~", protocol.DirectoryListingMaxEntries)
byName := map[string]protocol.DirectoryEntry{}
for _, entry := range listing.Entries {
byName[entry.Name] = entry
}
if e := byName[".config"]; !e.Hidden || !e.IsDir || e.IsGitRepo {
t.Fatalf(".config = %+v", e)
}
if e := byName["repo"]; !e.IsDir || !e.IsGitRepo || e.Hidden || e.Path != filepath.Join(home, "repo") {
t.Fatalf("repo = %+v", e)
}
if e := byName["Notes.txt"]; e.IsDir || e.Hidden {
t.Fatalf("Notes.txt = %+v", e)
}
if e := byName[".profile"]; e.IsDir || !e.Hidden {
t.Fatalf(".profile = %+v", e)
}
}
func TestListDirectorySubdirectoryHasParent(t *testing.T) {
home, _ := newListingHome(t)
for _, requested := range []string{"~/repo", filepath.Join(home, "repo"), filepath.Join(home, "beta", "..", "repo")} {
listing, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries)
if err != nil {
t.Fatalf("%q: %v", requested, err)
}
if listing.Path != filepath.Join(home, "repo") || listing.Parent == nil || *listing.Parent != home {
t.Fatalf("%q: header = %+v", requested, listing)
}
if got := strings.Join(entryNames(listing.Entries), ","); got != ".git,src,README.md" {
t.Fatalf("%q: entries = %s", requested, got)
}
}
}
func TestListDirectoryRefusesPathsOutsideHome(t *testing.T) {
home, outside := newListingHome(t)
if err := os.Symlink(outside, filepath.Join(home, "escape")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(home, "repo"), filepath.Join(home, "inside")); err != nil {
t.Fatal(err)
}
for _, requested := range []string{
outside,
filepath.Join(home, ".."),
filepath.Join(home, "..", "outside"),
"~/..",
"~/../outside",
"~/escape",
filepath.Join(home, "escape"),
"/",
} {
_, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries)
if err == nil || !strings.Contains(err.Error(), "outside the home directory") {
t.Fatalf("%q: err = %v, want outside-home refusal", requested, err)
}
}
for _, requested := range []string{"relative/path", "~root", "~/missing"} {
if _, err := listHomeDirectory(home, requested, protocol.DirectoryListingMaxEntries); err == nil {
t.Fatalf("%q listed, want an error", requested)
}
}
if _, err := listHomeDirectory(home, "~/Notes.txt", protocol.DirectoryListingMaxEntries); err == nil || !strings.Contains(err.Error(), "not a directory") {
t.Fatalf("file listed: %v", err)
}
// An escaping link is listed only as a non-selectable name; a link that
// stays inside home is a directory and lists under its home-relative path.
listing, err := listHomeDirectory(home, "~", protocol.DirectoryListingMaxEntries)
if err != nil {
t.Fatal(err)
}
for _, entry := range listing.Entries {
if entry.Name == "escape" && entry.IsDir {
t.Fatalf("escaping link marked as a directory: %+v", entry)
}
if entry.Name == "inside" && (!entry.IsDir || !entry.IsGitRepo) {
t.Fatalf("inside link = %+v", entry)
}
}
inside, err := listHomeDirectory(home, "~/inside", protocol.DirectoryListingMaxEntries)
if err != nil || inside.Path != filepath.Join(home, "repo") {
t.Fatalf("inside link listing = %+v, %v", inside, err)
}
}
func TestListDirectoryPermissionDenied(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root ignores directory permissions")
}
home, _ := newListingHome(t)
locked := filepath.Join(home, "locked")
mustMkdir(t, locked)
if err := os.Chmod(locked, 0); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(locked, 0o755) })
_, err := listHomeDirectory(home, "~/locked", protocol.DirectoryListingMaxEntries)
if err == nil || !strings.Contains(err.Error(), "permission denied") {
t.Fatalf("err = %v, want permission denied", err)
}
}
func TestListDirectoryTruncatesAtTheCap(t *testing.T) {
home, _ := newListingHome(t)
big := filepath.Join(home, "big")
for i := 0; i < 6; i++ {
mustMkdir(t, filepath.Join(big, fmt.Sprintf("d%d", i)))
if err := os.WriteFile(filepath.Join(big, fmt.Sprintf("f%d", i)), nil, 0o644); err != nil {
t.Fatal(err)
}
}
listing, err := listHomeDirectory(home, "~/big", 4)
if err != nil {
t.Fatal(err)
}
if !listing.Truncated || strings.Join(entryNames(listing.Entries), ",") != "d0,d1,d2,d3" {
t.Fatalf("listing = %+v", listing)
}
full, err := listHomeDirectory(home, "~/big", 12)
if err != nil || full.Truncated || len(full.Entries) != 12 {
t.Fatalf("exact-cap listing = %+v, %v", full, err)
}
}
// TestListDirectoryOverWebsocket pins the wire: list_directory replies with a
// directory_listing echoing the request id, and a refusal is an error frame.
func TestListDirectoryOverWebsocket(t *testing.T) {
home, outside := newListingHome(t)
t.Setenv("HOME", home)
ctx, _, conn := dialChatOptions(t, Options{})
request := protocol.Message{Type: protocol.ListDirectory, ID: "l1", ListDirectory: &protocol.DirectoryListRequest{Path: "~/repo"}}
if err := wsjson.Write(ctx, conn, request); err != nil {
t.Fatal(err)
}
var reply protocol.Message
if err := wsjson.Read(ctx, conn, &reply); err != nil {
t.Fatal(err)
}
if reply.Type != protocol.DirectoryListing || reply.ID != "l1" || reply.DirectoryListing == nil {
t.Fatalf("reply = %+v", reply)
}
if got := reply.DirectoryListing; got.Path != filepath.Join(home, "repo") || got.Home != home || got.Parent == nil || *got.Parent != home {
t.Fatalf("listing = %+v", got)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ListDirectory, ID: "l2"}); err != nil {
t.Fatal(err)
}
var raw map[string]any
if err := wsjson.Read(ctx, conn, &raw); err != nil {
t.Fatal(err)
}
body, _ := raw["directory_listing"].(map[string]any)
if raw["id"] != "l2" || body == nil || body["path"] != home {
t.Fatalf("home reply = %+v", raw)
}
if parent, present := body["parent"]; !present || parent != nil {
t.Fatalf("home parent must be an explicit null: %+v", body)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ListDirectory, ID: "l3", ListDirectory: &protocol.DirectoryListRequest{Path: outside}}); err != nil {
t.Fatal(err)
}
var refusal protocol.Message
if err := wsjson.Read(ctx, conn, &refusal); err != nil {
t.Fatal(err)
}
if refusal.Type != protocol.Error || refusal.ID != "l3" || !strings.Contains(refusal.Error, "outside the home directory") {
t.Fatalf("refusal = %+v", refusal)
}
}
+3
View File
@@ -221,6 +221,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
if handleChat(connCtx, request, options.Chat, hub, registry, clientID, write) {
continue
}
if handleDirectoryListing(request, write) {
continue
}
if handleNotificationSettings(ctx, request, settingsStore, write) {
continue
}