Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 59 additions & 15 deletions pkgs/mcpx/internal/source/source.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
package source

import (
"errors"
"fmt"
"io/fs"
"os"
Expand Down Expand Up @@ -142,24 +143,67 @@ func readDir(dir string, opt Options, explicit bool) (Resolved, error) {
"name a file, or set plumbing.sourceDirAllowed", dir)
}
var files []string
walk := func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if path == dir || opt.Recursive {
return nil
rootInfo, err := os.Stat(dir)
if err != nil {
return Resolved{}, fmt.Errorf("reading %s: %w", dir, err)
}
if rootInfo.IsDir() {
var walk func(string, []os.FileInfo) error
walk = func(path string, ancestors []os.FileInfo) error {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("reading %s: %w", path, err)
}
for _, ancestor := range ancestors {
if os.SameFile(info, ancestor) {
return nil
}
}
ancestors = append(ancestors, info)

entries, err := os.ReadDir(path)
if err != nil {
return fmt.Errorf("reading %s: %w", path, err)
}
for _, entry := range entries {
entryPath := filepath.Join(path, entry.Name())
entryInfo, err := entry.Info()
if err != nil {
return fmt.Errorf("reading %s: %w", entryPath, err)
}
if entryInfo.Mode()&fs.ModeSymlink != 0 {
entryInfo, err = os.Stat(entryPath)
if err != nil {
Comment on lines +174 to +176

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve extension filtering for unrelated symlinks

With Extensions: []string{".ts"} and nonrecursive traversal, a directory containing regular.ts and a self-referencing loop.txt symlink now fails with ELOOP instead of reading the TypeScript file. The new os.Stat runs before extension filtering and makes errors from excluded links fatal; inaccessible targets cause the same regression. This scenario succeeds against the parent commit and fails against this commit. Avoid rejecting excluded links whose targets do not need to be traversed.

Useful? React with 👍 / 👎.

if errors.Is(err, fs.ErrNotExist) {
// A dangling link has no regular target to read.
continue
}
return fmt.Errorf("reading %s: %w", entryPath, err)
}
}

if entryInfo.IsDir() {
if opt.Recursive {
if err := walk(entryPath, ancestors); err != nil {
return err
}
}
continue
}
if !entryInfo.Mode().IsRegular() || !wanted(entryPath, opt.Extensions) {
continue
}
files = append(files, entryPath)
}
return fs.SkipDir
}
if !wanted(path, opt.Extensions) {
return nil
}
files = append(files, path)
return nil
}
if err := filepath.WalkDir(dir, walk); err != nil {
return Resolved{}, fmt.Errorf("reading %s: %w", dir, err)
if err := walk(dir, nil); err != nil {
return Resolved{}, err
}
} else if rootInfo.Mode().IsRegular() && wanted(dir, opt.Extensions) {
// Preserve the existing behavior for an explicit @dir: path that names
// a regular file rather than a directory.
files = append(files, dir)
}
if len(files) == 0 {
return Resolved{}, fmt.Errorf("%s holds no files to read", dir)
Expand Down
116 changes: 116 additions & 0 deletions pkgs/mcpx/internal/source/source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,122 @@ func TestShallowByDefaultAndRecursiveWhenAsked(t *testing.T) {
}
}

func TestDirectoryReadsSymlinkToRegularFileUsingLinkPath(t *testing.T) {
dir := t.TempDir()
target := filepath.Join(dir, "target.data")
link := filepath.Join(dir, "alias.ts")
if err := os.WriteFile(target, []byte("from target"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(target, link); err != nil {
t.Skipf("symlinks are unavailable: %v", err)
}

o := opts(dir)
o.Extensions = []string{".ts"}
got, err := source.Resolve("@dir:"+dir, o)
if err != nil {
t.Fatal(err)
}
if len(got.Files) != 1 || got.Files[0] != link {
t.Fatalf("files should contain the matching link path %q, got %v", link, got.Files)
}
if !strings.Contains(got.Text, "from target") {
t.Errorf("symlink target contents were not read: %q", got.Text)
}
}

func TestDirectorySymlinkTraversalIsRecursiveAndCycleSafe(t *testing.T) {
dir := t.TempDir()
write := func(path, contents string) {
t.Helper()
if err := os.WriteFile(path, []byte(contents), 0o644); err != nil {
t.Fatal(err)
}
}
top := filepath.Join(dir, "top.ts")
sub := filepath.Join(dir, "sub")
inside := filepath.Join(sub, "inside.ts")
alias := filepath.Join(dir, "alias")
back := filepath.Join(sub, "back-to-root")
if err := os.Mkdir(sub, 0o755); err != nil {
t.Fatal(err)
}
write(top, "top")
write(inside, "inside")
if err := os.Symlink(sub, alias); err != nil {
t.Skipf("symlinks are unavailable: %v", err)
}
if err := os.Symlink(dir, back); err != nil {
t.Skipf("directory symlinks are unavailable: %v", err)
}

shallow, err := source.Resolve("@dir:"+dir, opts(dir))
if err != nil {
t.Fatal(err)
}
if len(shallow.Files) != 1 || shallow.Files[0] != top {
t.Errorf("shallow traversal should skip real and linked directories, got %v", shallow.Files)
}

o := opts(dir)
o.Recursive = true
deep, err := source.Resolve("@dir:"+dir, o)
if err != nil {
t.Fatal(err)
}
want := map[string]bool{
top: true,
inside: true,
filepath.Join(alias, "inside.ts"): true,
}
if len(deep.Files) != len(want) {
t.Fatalf("recursive aliases should be traversed once per path, got %v", deep.Files)
}
for _, file := range deep.Files {
if !want[file] {
t.Errorf("unexpected file from recursive traversal: %q", file)
}
}
}

func TestDirectorySkipsDanglingLinkAndFollowsLinkOutsideRoot(t *testing.T) {
root := t.TempDir()
external := t.TempDir()
regular := filepath.Join(root, "regular.ts")
dangling := filepath.Join(root, "dangling.ts")
linkedDir := filepath.Join(root, "external")
externalFile := filepath.Join(external, "linked.ts")
if err := os.WriteFile(regular, []byte("regular"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(externalFile, []byte("external"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "missing.ts"), dangling); err != nil {
t.Skipf("symlinks are unavailable: %v", err)
}
if err := os.Symlink(external, linkedDir); err != nil {
t.Skipf("directory symlinks are unavailable: %v", err)
}

o := opts(root)
o.Recursive = true
got, err := source.Resolve("@dir:"+root, o)
if err != nil {
t.Fatal(err)
}
want := map[string]bool{regular: true, filepath.Join(linkedDir, "linked.ts"): true}
if len(got.Files) != len(want) {
t.Fatalf("got files %v, want exactly the regular and external-link paths", got.Files)
}
for _, file := range got.Files {
if !want[file] {
t.Errorf("unexpected file %q", file)
}
}
}

func TestResolveAllJoinsInOrder(t *testing.T) {
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "second.ts"), []byte("SECOND"), 0o644)
Expand Down
95 changes: 95 additions & 0 deletions pkgs/mcpx/internal/source/source_unix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//go:build !windows

package source_test

import (
"context"
"errors"
"net"
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/source"
)

func TestDirectorySkipsFIFO(t *testing.T) {
if dir := os.Getenv("MCPX_SOURCE_FIFO_TEST_DIR"); dir != "" {
got, err := source.Resolve("@dir:"+dir, opts(dir))
if err != nil {
t.Fatal(err)
}
if len(got.Files) != 1 || filepath.Base(got.Files[0]) != "regular.ts" {
t.Fatalf("FIFO should be skipped while regular files are retained, got %v", got.Files)
}
return
}

dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "regular.ts"), []byte("regular"), 0o644); err != nil {
t.Fatal(err)
}
if err := syscall.Mkfifo(filepath.Join(dir, "fifo.ts"), 0o600); err != nil {
t.Skipf("cannot create FIFO: %v", err)
}

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDirectorySkipsFIFO$")
cmd.Env = append(os.Environ(), "MCPX_SOURCE_FIFO_TEST_DIR="+dir)
output, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("resolving a directory containing a FIFO did not finish within 3s")
}
if err != nil {
t.Fatalf("FIFO helper failed: %v\n%s", err, output)
}
}

func TestDirectorySkipsUnixSocket(t *testing.T) {
dir := t.TempDir()
regular := filepath.Join(dir, "regular.ts")
if err := os.WriteFile(regular, []byte("regular"), 0o644); err != nil {
t.Fatal(err)
}
listener, err := net.Listen("unix", filepath.Join(dir, "socket.ts"))
if err != nil {
t.Skipf("cannot create Unix socket: %v", err)
}
defer listener.Close()

got, err := source.Resolve("@dir:"+dir, opts(dir))
if err != nil {
t.Fatal(err)
}
if len(got.Files) != 1 || got.Files[0] != regular {
t.Fatalf("socket should be skipped while regular files are retained, got %v", got.Files)
}
}

func TestDirectoryReportsInaccessibleSymlinkTarget(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root can traverse directories without execute permission")
}

root := t.TempDir()
private := t.TempDir()
if err := os.WriteFile(filepath.Join(private, "secret.ts"), []byte("secret"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(private, "secret.ts"), filepath.Join(root, "inaccessible.ts")); err != nil {
t.Skipf("symlinks are unavailable: %v", err)
}
if err := os.Chmod(private, 0); err != nil {
t.Skipf("cannot make target directory inaccessible: %v", err)
}
defer os.Chmod(private, 0o700)

_, err := source.Resolve("@dir:"+root, opts(root))
if !errors.Is(err, os.ErrPermission) {
t.Fatalf("inaccessible symlink target should return a permission error, got %v", err)
}
}
Loading