Compare commits

..

1 Commits

Author SHA1 Message Date
Rodin 282b6e0e86 nit(#154): add t.Fatal guard if baseSubprocessArgs flag not found
PR Ready Gate / clear-labels (pull_request) Successful in 2s
CI / test (pull_request) Successful in 17s
CI / review (anthropic--claude-4.6-sonnet, sonnet, SONNET_REVIEW_TOKEN) (pull_request) Successful in 22s
CI / review (gpt-5, security, ., rodin/security-patterns, SECURITY_REVIEW.md, SECURITY_REVIEW_TOKEN) (pull_request) Successful in 38s
CI / review (gpt-5, gpt, GPT_REVIEW_TOKEN) (pull_request) Successful in 40s
Address sonnet NIT: if --repo or --pr is ever removed from
baseSubprocessArgs(), the mutation loop silently no-ops and the test
becomes meaningless. Adding a found guard and t.Fatal makes the
regression immediately visible.
2026-05-15 08:06:18 -07:00
3 changed files with 31 additions and 124 deletions
+10
View File
@@ -903,12 +903,17 @@ func TestMainSubprocess_InvalidRepo(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
args := baseSubprocessArgs() args := baseSubprocessArgs()
// Replace the canonical --repo value with an invalid one. // Replace the canonical --repo value with an invalid one.
found := false
for i, a := range args { for i, a := range args {
if a == "--repo" && i+1 < len(args) { if a == "--repo" && i+1 < len(args) {
args[i+1] = "invalidrepo" args[i+1] = "invalidrepo"
found = true
break break
} }
} }
if !found {
t.Fatal("baseSubprocessArgs() does not contain --repo; test is broken")
}
os.Args = args os.Args = args
main() main()
return return
@@ -930,12 +935,17 @@ func TestMainSubprocess_InvalidPRNumber(t *testing.T) {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
args := baseSubprocessArgs() args := baseSubprocessArgs()
// Replace the canonical --pr value with a non-numeric string. // Replace the canonical --pr value with a non-numeric string.
found := false
for i, a := range args { for i, a := range args {
if a == "--pr" && i+1 < len(args) { if a == "--pr" && i+1 < len(args) {
args[i+1] = "notanumber" args[i+1] = "notanumber"
found = true
break break
} }
} }
if !found {
t.Fatal("baseSubprocessArgs() does not contain --pr; test is broken")
}
os.Args = args os.Args = args
main() main()
return return
+20 -31
View File
@@ -23,19 +23,18 @@ const maxDocmapBytes int64 = 10 * 1024 * 1024 // 10 MB
// 1. The path resolves to a regular file within resolvedRoot (path // 1. The path resolves to a regular file within resolvedRoot (path
// confinement): prevents a PR-controlled --docmap from reading arbitrary // confinement): prevents a PR-controlled --docmap from reading arbitrary
// host files via absolute paths or ".." traversal. // host files via absolute paths or ".." traversal.
// 2. The resolved path is within resolvedRoot: in-repo file-level symlinks // 2. The path is not a symlink: prevents denial-of-service via /dev/zero or
// are allowed when their resolved target is still inside the root; // information disclosure via symlinks that point outside the workspace.
// symlinks that escape the root are rejected by the confinement check.
// 3. The file does not exceed maxDocmapBytes: prevents memory exhaustion // 3. The file does not exceed maxDocmapBytes: prevents memory exhaustion
// from an oversized but legitimately committed doc-map file. // from an oversized but legitimately committed doc-map file.
// //
// resolvedRoot must already be an absolute, symlink-free path (obtained from // resolvedRoot must already be an absolute, symlink-free path (obtained from
// filepath.Abs + filepath.EvalSymlinks). // filepath.Abs + filepath.EvalSymlinks).
func validateDocmapPath(localPath, resolvedRoot string) (string, error) { func validateDocmapPath(localPath, resolvedRoot string) error {
// Resolve the docmap path to an absolute path. // Resolve the docmap path to an absolute path.
absPath, err := filepath.Abs(localPath) absPath, err := filepath.Abs(localPath)
if err != nil { if err != nil {
return "", fmt.Errorf("cannot resolve path: %w", err) return fmt.Errorf("cannot resolve path: %w", err)
} }
// Resolve ALL symlink components, not just the final one. // Resolve ALL symlink components, not just the final one.
@@ -47,36 +46,34 @@ func validateDocmapPath(localPath, resolvedRoot string) (string, error) {
// path is inside the root while the actual destination is not. // path is inside the root while the actual destination is not.
resolvedPath, err := filepath.EvalSymlinks(absPath) resolvedPath, err := filepath.EvalSymlinks(absPath)
if err != nil { if err != nil {
return "", fmt.Errorf("cannot resolve path (symlink): %w", err) return fmt.Errorf("cannot resolve path (symlink): %w", err)
} }
// Lstat the resolved path — EvalSymlinks guarantees resolvedPath is // Lstat the resolved path — at this point resolvedPath is symlink-free, so
// symlink-free, so ModeSymlink can never be set here; this is unreachable. // ModeSymlink will never be set. We keep the check as defense-in-depth.
fi, err := os.Lstat(resolvedPath) fi, err := os.Lstat(resolvedPath)
if err != nil { if err != nil {
return "", fmt.Errorf("cannot stat file: %w", err) return fmt.Errorf("cannot stat file: %w", err)
} }
// Reject anything that is not a regular file (directories, FIFOs, device // Defense-in-depth: reject any remaining symlink indicator.
// nodes, etc.) — ParseDocMapConfig expects a plain YAML file and would if fi.Mode()&os.ModeSymlink != 0 {
// produce a confusing error on non-regular entries. return fmt.Errorf("symlinks are not allowed")
if !fi.Mode().IsRegular() {
return "", fmt.Errorf("docmap must be a regular file")
} }
// Confine to resolvedRoot: use the fully-resolved path so that a directory // Confine to resolvedRoot: use the fully-resolved path so that a directory
// symlink inside the repo cannot carry the path outside the root. // symlink inside the repo cannot carry the path outside the root.
rel, err := filepath.Rel(resolvedRoot, resolvedPath) rel, err := filepath.Rel(resolvedRoot, resolvedPath)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
return "", fmt.Errorf("path must be within --repo-root") return fmt.Errorf("path must be within --repo-root")
} }
// Enforce size cap before reading to prevent memory exhaustion. // Enforce size cap before reading to prevent memory exhaustion.
if fi.Size() > maxDocmapBytes { if fi.Size() > maxDocmapBytes {
return "", fmt.Errorf("file size %d bytes exceeds %d-byte limit", fi.Size(), maxDocmapBytes) return fmt.Errorf("file size %d bytes exceeds %d-byte limit", fi.Size(), maxDocmapBytes)
} }
return resolvedPath, nil return nil
} }
// runValidateDocmap implements the `review-bot validate-docmap` subcommand. // runValidateDocmap implements the `review-bot validate-docmap` subcommand.
@@ -140,23 +137,18 @@ func runValidateDocmap(args []string) int {
// may reference a PR-controlled file (e.g. .review-bot/doc-map.yml). // may reference a PR-controlled file (e.g. .review-bot/doc-map.yml).
// Validate that it: // Validate that it:
// 1. Resolves within resolvedRoot (prevent reading arbitrary host files). // 1. Resolves within resolvedRoot (prevent reading arbitrary host files).
// 2. Resolved target stays within the root (in-repo symlinks are allowed // 2. Is not a symlink (prevent /dev/zero or symlink-based host probing).
// if they resolve to a path inside the root).
// 3. Does not exceed maxDocmapBytes (prevent memory exhaustion from an // 3. Does not exceed maxDocmapBytes (prevent memory exhaustion from an
// oversized committed file). // oversized committed file).
// validateDocmapPath returns the resolved path; use it directly to if err := validateDocmapPath(*docmapFlag, resolvedRoot); err != nil {
// eliminate any TOCTOU race between validation and use.
resolvedDocmap, err := validateDocmapPath(*docmapFlag, resolvedRoot)
if err != nil {
fmt.Fprintf(errWriter, "Error: --docmap %q is invalid: %v\n", *docmapFlag, err) fmt.Fprintf(errWriter, "Error: --docmap %q is invalid: %v\n", *docmapFlag, err)
return 2 return 2
} }
// Parse docmap YAML using the resolved path — eliminates any TOCTOU race // Parse docmap YAML.
// between validation and use. cfg, err := review.ParseDocMapConfig(*docmapFlag)
cfg, err := review.ParseDocMapConfig(resolvedDocmap)
if err != nil { if err != nil {
fmt.Fprintf(errWriter, "Error: failed to parse docmap %q: %v\n", resolvedDocmap, err) fmt.Fprintf(errWriter, "Error: failed to parse docmap %q: %v\n", *docmapFlag, err)
return 2 return 2
} }
@@ -179,9 +171,6 @@ func runValidateDocmap(args []string) int {
// Normalize Windows-style backslashes to forward slashes so that // Normalize Windows-style backslashes to forward slashes so that
// changed-file paths from git on Windows match doc-map globs. // changed-file paths from git on Windows match doc-map globs.
f = strings.ReplaceAll(f, "\\", "/") f = strings.ReplaceAll(f, "\\", "/")
// Strip a leading "./" emitted by non-git tools (e.g. `find`) so that
// paths like "./cmd/foo.go" match doc-map globs written as "cmd/**".
f = strings.TrimPrefix(f, "./")
if !review.FileCoveredByDocMap(cfg, f) { if !review.FileCoveredByDocMap(cfg, f) {
uncovered = append(uncovered, f) uncovered = append(uncovered, f)
} }
@@ -200,7 +189,7 @@ func runValidateDocmap(args []string) int {
staleDocs := checkStaleDocs(cfg, resolvedRoot) staleDocs := checkStaleDocs(cfg, resolvedRoot)
if len(staleDocs) > 0 { if len(staleDocs) > 0 {
failed = true failed = true
fmt.Fprintln(errWriter, "ERROR: stale docmap entries (paths do not exist):") fmt.Fprintln(errWriter, "ERROR: stale docmap docs: entries (paths do not exist):")
for _, d := range staleDocs { for _, d := range staleDocs {
fmt.Fprintf(errWriter, " %s\n", d) fmt.Fprintf(errWriter, " %s\n", d)
} }
+1 -93
View File
@@ -595,99 +595,7 @@ func TestValidateDocmapPath_DirSymlinkBypass(t *testing.T) {
t.Fatalf("EvalSymlinks(repoDir): %v", err) t.Fatalf("EvalSymlinks(repoDir): %v", err)
} }
if _, err := validateDocmapPath(attackPath, resolvedRoot); err == nil { if err := validateDocmapPath(attackPath, resolvedRoot); err == nil {
t.Error("expected rejection of dir-symlink bypass, got nil error") t.Error("expected rejection of dir-symlink bypass, got nil error")
} }
} }
// TestValidateDocmapPath_NonRegularFile verifies that --docmap pointing at a
// non-regular file (e.g. a directory) is rejected with a clear error before
// ParseDocMapConfig is called.
func TestValidateDocmapPath_NonRegularFile(t *testing.T) {
dir := t.TempDir()
// Use the directory itself as the docmap path — directories pass Lstat but
// are not regular files.
reviewBotDir := filepath.Join(dir, ".review-bot")
if err := os.MkdirAll(reviewBotDir, 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
code, _, stderr := stdinValidateDocmap(t,
"",
[]string{"--docmap", reviewBotDir, "--repo-root", dir},
)
if code != 2 {
t.Errorf("expected exit 2 for directory docmap, got %d; stderr: %q", code, stderr)
}
if !strings.Contains(stderr, "regular file") && !strings.Contains(stderr, "invalid") {
t.Errorf("expected regular-file rejection in stderr, got %q", stderr)
}
}
// TestRunValidateDocmap_DotSlashPrefix verifies that paths emitted with a
// leading "./" (e.g. from `find` or `ls`) match doc-map globs correctly.
// Without TrimPrefix, "./cmd/foo.go" would not match the pattern "cmd/**".
func TestRunValidateDocmap_DotSlashPrefix(t *testing.T) {
dir := t.TempDir()
makeDocFile(t, dir, "docs/foo.md")
docmap := makeDocmapInDir(t, dir, `
mappings:
- paths:
- "cmd/**"
docs:
- docs/foo.md
`)
// File with a leading "./" should be treated as covered.
code, _, stderr := stdinValidateDocmap(t,
"./cmd/foo.go\n",
[]string{"--docmap", docmap, "--repo-root", dir},
)
if code != 0 {
t.Errorf("expected exit 0 for './' prefixed covered file, got %d; stderr: %q", code, stderr)
}
}
// TestValidateDocmapPath_InRepoSymlinkAllowed verifies that an in-repo
// file-level symlink whose resolved target is still within the repo root is
// accepted. This is the positive case for the issue #150 behavioral change:
// only symlinks that escape the root are rejected; intra-repo symlinks are
// allowed because EvalSymlinks resolves the target and the confinement check
// is applied to the resolved path, not the symlink entry itself.
func TestValidateDocmapPath_InRepoSymlinkAllowed(t *testing.T) {
dir := t.TempDir()
// Create the real docmap file inside the repo root.
if err := os.MkdirAll(filepath.Join(dir, ".review-bot"), 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
realDocmap := filepath.Join(dir, ".review-bot", "doc-map-real.yml")
if err := os.WriteFile(realDocmap, []byte("mappings: []\n"), 0o644); err != nil {
t.Fatalf("WriteFile: %v", err)
}
// Create a symlink inside the repo root that points to the real file
// (also inside the root).
symlinkPath := filepath.Join(dir, ".review-bot", "doc-map-link.yml")
if err := os.Symlink(realDocmap, symlinkPath); err != nil {
t.Skipf("cannot create symlink (platform may not support it): %v", err)
}
// Resolve dir to a symlink-free root, as runValidateDocmap does.
resolvedRoot, err := filepath.EvalSymlinks(dir)
if err != nil {
t.Fatalf("EvalSymlinks(dir): %v", err)
}
// In-repo symlink whose target is within root: must be accepted.
resolved, err := validateDocmapPath(symlinkPath, resolvedRoot)
if err != nil {
t.Fatalf("expected in-repo symlink to be accepted, got error: %v", err)
}
// The returned resolved path must be the real file (not the symlink entry).
if resolved == symlinkPath {
t.Errorf("expected resolved path to differ from symlink path")
}
}