Repository navigation
Add analyzer for overbroad parent-path prefix checks #80482
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
ca0e751
81a5843
ff1fa08
6760709
b2b14ce
fb4078f
31f7774
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # ADR-80482: Add Advisory `hasprefixdotdotpathescape` Analyzer for Parent-Path Prefix Checks | ||
|
|
||
| **Date**: 2026-11-23 | ||
| **Status**: Draft | ||
|
|
||
| ## Context | ||
|
|
||
| Path-containment checks in gh-aw often use `strings.HasPrefix(value, "..")` to decide whether a relative path escapes its base directory. That prefix also matches legitimate names such as `..foo`, so the check can reject safe paths or accept the wrong shape of path. The linked issue #80478 reports unsafe checks of this form in `pkg/parser/include_expander.go`, `pkg/parser/remote_download_file.go`, `pkg/gitutil/gitutil.go`, and `pkg/cli/poutine.go`. Those findings come from the issue body and were not re-verified in this gate. | ||
|
|
||
| The repository already ships a custom `go/analysis` linter suite under `pkg/linters/`, with an `analyzerutil` helper, a shared `nolint` directive index, and a documentation sync test (`pkg/linters/doc_sync_test.go`) that tracks analyzers that are documented but not yet enforced in CI. Existing call sites have not yet been audited, so turning a new check on in CI would immediately fail on code that has not been reviewed. | ||
|
|
||
| ## Decision | ||
|
|
||
| Add the `hasprefixdotdotpathescape` analyzer under `pkg/linters/hasprefixdotdotpathescape/` and register it in `pkg/linters/registry.go`. The analyzer: | ||
|
|
||
| - Matches `strings.HasPrefix` calls by resolved type (`types.Func` in package `strings`), so aliased imports, dot imports, and constant prefixes such as `"\x2e\x2e"` or a `const` built from `"." + "."` are detected. | ||
| - Reports only when the prefix value is exactly `..`. Checks such as `path == ".."` or `HasPrefix(path, "../")` and `HasPrefix(path, ".." + string(filepath.Separator))` are left alone. | ||
| - Skips generated files and honors the existing `nolint:hasprefixdotdotpathescape` directive. | ||
| - Recommends checking the exact `..` component plus a separator, or using `filepath.IsLocal`. | ||
|
|
||
| CI enforcement is deferred. The analyzer is listed in `notYetEnforced` in `pkg/linters/doc_sync_test.go` with the reason "existing parent-path checks need review and remediation before CI enforcement". It is documented in `pkg/linters/README.md` and `pkg/linters/doc.go` (analyzer count updated to 102), and it is listed in the `spec_test.go` documented-analyzers table. | ||
|
|
||
| ## Alternatives Considered | ||
|
|
||
| - **Enforce the analyzer in CI immediately.** Rejected. Existing call sites named in #80478 have not been reviewed, so enforcement would block unrelated PRs before remediation. The `notYetEnforced` mechanism exists for this case. | ||
| - **Use a text or regex check in CI instead of a `go/analysis` analyzer.** Rejected. A textual check cannot resolve aliased or dot-imported `strings.HasPrefix`, constant-folded prefixes, or shadowed names. The analyzer resolves these through `pass.TypesInfo`, and the testdata fixtures cover them. | ||
| - **Fix the flagged call sites by hand and add no analyzer.** Rejected as the only action. It fixes today's instances but gives no guard against new ones. Remediation of existing call sites remains a follow-up before enforcement, as the PR states. | ||
|
|
||
| ## Consequences | ||
|
|
||
| **Positive** | ||
|
|
||
| - Path-containment checks written with `strings.HasPrefix(value, "..")` get a diagnostic that points to the exact-component fix or `filepath.IsLocal`. | ||
| - The analyzer reuses existing linter infrastructure (`analyzerutil`, `nolint`, generated-file filtering) and has positive and negative `analysistest` fixtures. | ||
| - The documentation sync test keeps the README, `doc.go`, and the spec table aligned with the registry. | ||
|
|
||
| **Negative** | ||
|
|
||
| - Until remediation is complete, the analyzer is advisory only. It can flag existing call sites in the four files named in #80478, and CI will not catch them. | ||
| - Enforcement will require a remediation pass and then removing the entry from `notYetEnforced`. Maintainers must track that follow-up. | ||
| - Each new analyzer adds maintenance cost to the linter suite (now 102 analyzers). |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| // Package hasprefixdotdotpathescape reports overbroad parent-path prefix checks. | ||
| package hasprefixdotdotpathescape | ||
|
|
||
| import ( | ||
| "go/ast" | ||
| "go/constant" | ||
| "go/types" | ||
| "strings" | ||
| "unicode" | ||
|
|
||
| "golang.org/x/tools/go/analysis" | ||
|
|
||
| "github.com/github/gh-aw/pkg/linters/internal/analyzerutil" | ||
| "github.com/github/gh-aw/pkg/linters/internal/astutil" | ||
| "github.com/github/gh-aw/pkg/linters/internal/filecheck" | ||
| "github.com/github/gh-aw/pkg/linters/internal/nolint" | ||
| ) | ||
|
|
||
| const linterName = "hasprefixdotdotpathescape" | ||
|
|
||
| // Analyzer reports overbroad checks for paths escaping a directory. | ||
| var Analyzer = analyzerutil.New(linterName, `reports strings.HasPrefix on path-like values with a ".." prefix`, run) | ||
|
|
||
| func run(pass *analysis.Pass) (any, error) { | ||
| noLintIndex, generatedFiles, err := analyzerutil.Indexes(pass) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| return analyzerutil.Preorder(pass, []ast.Node{(*ast.CallExpr)(nil)}, func(n ast.Node) { | ||
| call, ok := n.(*ast.CallExpr) | ||
| if !ok || len(call.Args) != 2 { | ||
| return | ||
| } | ||
| var ident *ast.Ident | ||
| switch fun := astutil.UnwrapParenExpr(call.Fun).(type) { | ||
| case *ast.SelectorExpr: | ||
| ident = fun.Sel | ||
| case *ast.Ident: | ||
| ident = fun | ||
| } | ||
| if ident == nil { | ||
| return | ||
| } | ||
| fn, ok := pass.TypesInfo.Uses[ident].(*types.Func) | ||
| if !ok || fn.Name() != "HasPrefix" || fn.Pkg() == nil || fn.Pkg().Path() != "strings" { | ||
| return | ||
| } | ||
| prefix := call.Args[1] //nolint:uncheckedsliceindex // len(call.Args) is checked above | ||
| value := pass.TypesInfo.Types[prefix].Value | ||
| if value == nil || value.Kind() != constant.String || constant.StringVal(value) != ".." { | ||
| return | ||
| } | ||
| if !isPathLikeExpression(pass, call.Args[0]) { //nolint:uncheckedsliceindex // len(call.Args) is checked above | ||
| return | ||
| } | ||
| pos := pass.Fset.PositionFor(call.Pos(), false) | ||
| if filecheck.ShouldSkipFilename(pos.Filename, generatedFiles) || nolint.HasDirectiveForLinter(pos, noLintIndex, linterName) { | ||
| return | ||
| } | ||
| pass.Reportf(call.Pos(), `strings.HasPrefix(value, "..") also matches names like "..foo"; check exact ".." and a separator, or use filepath.IsLocal`) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a path-context filter using path-like identifier components and typed
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The diagnostic fires on any
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a documented path-context heuristic and negative text-prefix fixtures, so non-path strings are ignored. Implemented in |
||
| }) | ||
| } | ||
|
|
||
| // isPathLikeExpression uses identifier names and path-manipulation calls as a conservative path-context heuristic. | ||
| func isPathLikeExpression(pass *analysis.Pass, expr ast.Expr) bool { | ||
| switch expr := astutil.UnwrapParenExpr(expr).(type) { | ||
| case *ast.Ident: | ||
| return isPathLikeName(expr.Name) | ||
| case *ast.SelectorExpr: | ||
| return isPathLikeName(expr.Sel.Name) | ||
| case *ast.CallExpr: | ||
| var ident *ast.Ident | ||
| switch fun := astutil.UnwrapParenExpr(expr.Fun).(type) { | ||
| case *ast.SelectorExpr: | ||
| ident = fun.Sel | ||
| case *ast.Ident: | ||
| ident = fun | ||
| } | ||
| if ident == nil { | ||
| return false | ||
| } | ||
| fn, ok := pass.TypesInfo.Uses[ident].(*types.Func) | ||
| if !ok || fn.Pkg() == nil || (fn.Pkg().Path() != "path" && fn.Pkg().Path() != "path/filepath") { | ||
| return false | ||
| } | ||
| switch fn.Name() { | ||
| case "Abs", "Base", "Clean", "Dir", "EvalSymlinks", "FromSlash", "Join", "Rel", "ToSlash": | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func isPathLikeName(name string) bool { | ||
| runes := []rune(name) | ||
| start := 0 | ||
| for i := 1; i < len(runes); i++ { | ||
| current, previous := runes[i], runes[i-1] //nolint:uncheckedsliceindex // The loop bounds both indexes. | ||
| if !unicode.IsLetter(current) && !unicode.IsDigit(current) { | ||
| if isPathNameComponent(runes[start:i]) { | ||
| return true | ||
| } | ||
| start = i + 1 | ||
| } else if unicode.IsUpper(current) && (unicode.IsLower(previous) || unicode.IsDigit(previous)) { | ||
| if isPathNameComponent(runes[start:i]) { | ||
| return true | ||
| } | ||
| start = i | ||
| } else if unicode.IsUpper(previous) && unicode.IsUpper(current) && i+1 < len(runes) && unicode.IsLower(runes[i+1]) { //nolint:uncheckedsliceindex // The condition checks i+1 is in range. | ||
| if isPathNameComponent(runes[start:i]) { | ||
| return true | ||
| } | ||
| start = i | ||
| } | ||
| } | ||
| return isPathNameComponent(runes[start:]) | ||
| } | ||
|
|
||
| func isPathNameComponent(component []rune) bool { | ||
| switch strings.ToLower(string(component)) { | ||
| case "dir", "directory", "directories", "dirs", "file", "filename", "filenames", "files", "filepath", "filepaths", "path", "paths", "root": | ||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| //go:build !integration | ||
|
|
||
| package hasprefixdotdotpathescape_test | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "golang.org/x/tools/go/analysis/analysistest" | ||
|
|
||
| "github.com/github/gh-aw/pkg/linters/hasprefixdotdotpathescape" | ||
| ) | ||
|
|
||
| func TestAnalyzer(t *testing.T) { | ||
| t.Parallel() | ||
| analysistest.Run(t, analysistest.TestData(), hasprefixdotdotpathescape.Analyzer, "checks", "dotimport") | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package checks | ||
|
|
||
| import ( | ||
| "path/filepath" | ||
| s "strings" | ||
| ) | ||
|
|
||
| const parent = "." + "." | ||
|
|
||
| func checks(path, prefix string) { | ||
| _ = s.HasPrefix(path, "..") // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| _ = !s.HasPrefix(path, (`..`)) // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| _ = (s.HasPrefix)(path, parent) // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| _ = s.HasPrefix(path, "\x2e\x2e") // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| _ = s.HasPrefix(filepath.Clean(path), "..") // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| _ = path == ".." || s.HasPrefix(path, "../") | ||
| _ = path == ".." || s.HasPrefix(path, ".."+string(filepath.Separator)) | ||
| _ = s.HasPrefix(path, prefix) | ||
| _ = filepath.IsLocal(path) | ||
| //nolint:hasprefixdotdotpathescape | ||
| _ = s.HasPrefix(path, "..") | ||
| } | ||
|
|
||
| func nonPathText(text, tokenPrefix, profile string) { | ||
| _ = s.HasPrefix(text, "..") | ||
| _ = s.HasPrefix(tokenPrefix, "..") | ||
| _ = s.HasPrefix(profile, "..") | ||
| _ = s.HasPrefix(filepath.Clean(text), "..") // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| } | ||
|
|
||
| type stringLike struct{} | ||
|
|
||
| func (stringLike) HasPrefix(string, string) bool { return false } | ||
|
|
||
| func unrelated(path string) { | ||
| strings := stringLike{} | ||
| _ = strings.HasPrefix(path, "..") | ||
| } |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package dotimport | ||
|
|
||
| import . "strings" | ||
|
|
||
| func checks(path string) bool { | ||
| return HasPrefix(path, "..") // want `strings.HasPrefix\(value, "\.\."\) also matches` | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This diagnostic is emitted for every
strings.HasPrefix(..., "..")call, without establishing that the first argument is a filesystem path. The same API is also commonly used for non-path strings (for example, syntax/token prefixes), so registering this analyzer in the aggregate set can produce false positives and make enforcement noisy or unsafe. Please either add a documented/narrower path-context heuristic or validate and account for non-path call sites before enabling enforcement.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added the path-context filter and documented the heuristic. The analyzer now only reports path-like names or
path/filepathresults; ordinary text checks are covered by negative fixtures. Implemented infb4078f.