package server import ( "fmt" "os" "path/filepath" "strings" "testing" "time" "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 TestListDirectoryFileMetadata(t *testing.T) { home, _ := newListingHome(t) file := filepath.Join(home, "Notes.txt") modified := time.Date(2024, time.March, 14, 15, 9, 26, 0, time.UTC) if err := os.Chtimes(file, modified, modified); err != nil { t.Fatal(err) } listing, err := listHomeDirectory(home, "~", protocol.DirectoryListingMaxEntries) if err != nil { t.Fatal(err) } var gotFile, gotDir protocol.DirectoryEntry for _, entry := range listing.Entries { switch entry.Name { case "Notes.txt": gotFile = entry case "repo": gotDir = entry } } if gotFile.Size != int64(len("secret contents")) || gotFile.Modified != modified.Format(time.RFC3339) { t.Fatalf("file metadata = %+v", gotFile) } if gotDir.Size != 0 || gotDir.Modified != "" { t.Fatalf("directory metadata = %+v", gotDir) } } 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) } }