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
41 changes: 41 additions & 0 deletions docs/adr/80482-add-hasprefixdotdotpathescape-analyzer.md
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).
3 changes: 3 additions & 0 deletions pkg/linters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ The method names mentioned in analyzer descriptions (such as `Err`, `Flush`, `Re
- `goroutinemissingrecover` — reports goroutines started via a function literal whose body does not install a top-level `defer func() { recover() }()` guard.
- `goroutineresourceleak` — reports goroutine resource acquisitions without deferred cleanup before a possible exit, channels without a close or safely buffered send/receive pair, and loop-launched goroutines without matching `WaitGroup` synchronization.
- `hardcodedfilepath` — reports hard-coded file path string literals that match known path constants or should be extracted into named constants; also annotates paths that appear in log/print calls.
- `hasprefixdotdotpathescape` — reports `strings.HasPrefix(value, "..")` checks on path-like values, identified by path-related names or `path`/`filepath` operations; checks on ordinary text are ignored. Check the exact `..` component and separator or use `filepath.IsLocal`. Not enforced in CI until existing checks are reviewed.
- `httpclientnotimeout` — reports `net/http.Client` composite literals that do not set a `Timeout` field.
- `httpnoctx` — reports HTTP client and package-level HTTP calls that do not accept a `context.Context`.
- `httprespbodyclose` — reports directly matched HTTP response `Body.Close()` calls that are not deferred.
Expand Down Expand Up @@ -225,6 +226,7 @@ environment variable and gates findings on the recorded execution hit count for
| `goroutinemissingrecover` | Custom `go/analysis` analyzer that flags goroutines started via a function literal that do not install a top-level defer/recover guard |
| `goroutineresourceleak` | Custom `go/analysis` analyzer that flags goroutine resource acquisitions without immediate deferred cleanup, channels without a close or safely buffered send/receive pair, and loop-launched goroutines without matching `WaitGroup` synchronization |
| `hardcodedfilepath` | Custom `go/analysis` analyzer that flags hard-coded file path string literals that match known path constants or should be extracted as named constants; annotates paths in log/print calls |
| `hasprefixdotdotpathescape` | Custom `go/analysis` analyzer that flags overbroad `strings.HasPrefix(value, "..")` checks on path-like values |
| `httpclientnotimeout` | Custom `go/analysis` analyzer that flags `net/http.Client` composite literals without a `Timeout` field |
| `httpnoctx` | Custom `go/analysis` analyzer that flags HTTP calls that do not accept a `context.Context` |
| `httprespbodyclose` | Custom `go/analysis` analyzer that flags directly matched HTTP response `Body.Close()` calls that are not deferred |
Expand Down Expand Up @@ -406,6 +408,7 @@ _ = typeassertionnil.Analyzer
- `github.com/github/gh-aw/pkg/linters/fprintlnsprintf` — fprintln-sprintf analyzer subpackage
- `github.com/github/gh-aw/pkg/linters/globwalkignorederror` — glob-walk-ignored-error analyzer subpackage
- `github.com/github/gh-aw/pkg/linters/hardcodedfilepath` — hard-coded-file-path analyzer subpackage
- `github.com/github/gh-aw/pkg/linters/hasprefixdotdotpathescape` — parent-path prefix analyzer subpackage
- `github.com/github/gh-aw/pkg/linters/httpclientnotimeout` — HTTP-client-timeout analyzer subpackage
- `github.com/github/gh-aw/pkg/linters/httpnoctx` — HTTP-no-context analyzer subpackage
- `github.com/github/gh-aw/pkg/linters/httprespbodyclose` — HTTP-response-body-close analyzer subpackage
Expand Down
3 changes: 2 additions & 1 deletion pkg/linters/doc.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Package linters is a namespace for gh-aw's custom Go analysis linters.
//
// All 101 active analyzers:
// All 102 active analyzers:
//
// - appendbytestring — flags append(b, []byte(s)...) calls where s is a string that can be simplified to append(b, s...)
// - appendoneelement — flags append(s, []T{x}...) calls where a single-element slice literal is spread and can be simplified to append(s, x)
Expand Down Expand Up @@ -35,6 +35,7 @@
// - goroutinemissingrecover — flags goroutines started via a function literal whose body does not install a top-level defer/recover guard
// - goroutineresourceleak — flags goroutine resource acquisitions without immediate deferred cleanup, channels without a close or safely buffered send/receive pair, and loop-launched goroutines without WaitGroup synchronization
// - hardcodedfilepath — flags hard-coded file path string literals that match known path constants or should be extracted as named constants
// - hasprefixdotdotpathescape — reports path-like strings.HasPrefix(value, "..") checks that also match legitimate names like "..foo"
// - httpclientnotimeout — reports net/http.Client composite literals without a Timeout field
// - httpnoctx — flags HTTP calls that do not accept a context.Context
// - httprespbodyclose — flags HTTP response bodies that are not closed
Expand Down
1 change: 1 addition & 0 deletions pkg/linters/doc_sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var notYetEnforced = map[string]string{
"fprintferrorunchecked": "existing production violations need remediation before enforcement; nolint suppression already works",
"goroutineresourceleak": "requires an enforcement-readiness audit before native and WebAssembly CI enable it",
"hardcodedfilepath": "requires an enforcement audit after the same-package constant fix (#52428)",
"hasprefixdotdotpathescape": "existing parent-path checks need review and remediation before CI enforcement",
"httpclientnotimeout": "the new HTTP client timeout analyzer needs an enforcement-readiness audit",
"ignoredlocalerror": "existing ignored local errors need review before CI enforcement",
"jsondecodertrailingdataunchecked": "new JSON decoder correctness analyzer needs an enforcement-readiness audit before CI enables it",
Expand Down
127 changes: 127 additions & 0 deletions pkg/linters/hasprefixdotdotpathescape/hasprefixdotdotpathescape.go
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
}

Copy link
Copy Markdown
Contributor

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.

Copy link
Copy Markdown
Contributor

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/filepath results; ordinary text checks are covered by negative fixtures. Implemented in fb4078f.

pass.Reportf(call.Pos(), `strings.HasPrefix(value, "..") also matches names like "..foo"; check exact ".." and a separator, or use filepath.IsLocal`)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Added a path-context filter using path-like identifier components and typed path/filepath operations, with negative fixtures for ordinary text prefixes. Implemented in fb4078f.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The diagnostic fires on any strings.HasPrefix(x, "..") call regardless of whether x is a filesystem path. Consider adding a path-context heuristic (e.g. checking the variable name or type) to reduce false positives on non-path string comparisons. 🛡️

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 fb4078f.

})
}

// 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`
}
2 changes: 2 additions & 0 deletions pkg/linters/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
"github.com/github/gh-aw/pkg/linters/goroutinemissingrecover"
"github.com/github/gh-aw/pkg/linters/goroutineresourceleak"
"github.com/github/gh-aw/pkg/linters/hardcodedfilepath"
"github.com/github/gh-aw/pkg/linters/hasprefixdotdotpathescape"
"github.com/github/gh-aw/pkg/linters/httpclientnotimeout"
"github.com/github/gh-aw/pkg/linters/httpnoctx"
"github.com/github/gh-aw/pkg/linters/httprespbodyclose"
Expand Down Expand Up @@ -149,6 +150,7 @@ var allAnalyzers = []*analysis.Analyzer{
goroutineresourceleak.Analyzer,
goroutinemissingrecover.Analyzer,
hardcodedfilepath.Analyzer,
hasprefixdotdotpathescape.Analyzer,
httpclientnotimeout.Analyzer,
httpnoctx.Analyzer,
httprespbodyclose.Analyzer,
Expand Down
6 changes: 4 additions & 2 deletions pkg/linters/spec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import (
"github.com/github/gh-aw/pkg/linters/goroutinemissingrecover"
"github.com/github/gh-aw/pkg/linters/goroutineresourceleak"
"github.com/github/gh-aw/pkg/linters/hardcodedfilepath"
"github.com/github/gh-aw/pkg/linters/hasprefixdotdotpathescape"
"github.com/github/gh-aw/pkg/linters/httpclientnotimeout"
"github.com/github/gh-aw/pkg/linters/httpnoctx"
"github.com/github/gh-aw/pkg/linters/httprespbodyclose"
Expand Down Expand Up @@ -127,15 +128,15 @@ type docAnalyzer struct {
}

// documentedAnalyzers returns the analyzer subpackages documented in the README
// "Public API > Subpackages" table. The README documents 100 analyzer
// "Public API > Subpackages" table. The README documents 102 analyzer
// subpackages (the non-analyzer `internal` helper subpackage is excluded because
// it exposes no Analyzer).
//
// Spec (README "Public API > Subpackages"):
//
// appendbytestring, appendoneelement, blankassigncomma, blankassignedcleanuperror, bufferresetbeforereuse, bufioscannererunchecked, bytesbufferstring, bytescomparestring, closeerrorunchecked, contextcancelnotdeferred, ctxbackground, deferinloop, deferrerrorunchecked, errorfwrapv, excessivefuncparams, errormessage, errorsnewerrorstring,
// errortypeassertion, errstringmatch, execcommandoutputerrdiscard, execcommandwithoutcontext, fileclosenotdeferred, filepathwalkpreferwalkdir, fmterrorfnoverbs, formatintitoa, fprintferrorunchecked, fprintlnsprintf,
// generatedyamlheredoc, globwalkignorederror, goroutinemissingrecover, goroutineresourceleak, hardcodedfilepath, httpclientnotimeout, httpnoctx, httprespbodyclose, httpstatuscode, ignoredlocalerror, ioutildeprecated, jsondecodertrailingdataunchecked, jsonmarshalignoredeerror, jsonunmarshalbytesconversion, largefunc, lenstringsplit, lenstringzero,
// generatedyamlheredoc, globwalkignorederror, goroutinemissingrecover, goroutineresourceleak, hardcodedfilepath, hasprefixdotdotpathescape, httpclientnotimeout, httpnoctx, httprespbodyclose, httpstatuscode, ignoredlocalerror, ioutildeprecated, jsondecodertrailingdataunchecked, jsonmarshalignoredeerror, jsonunmarshalbytesconversion, largefunc, lenstringsplit, lenstringzero,
// logfatallibrary, manualmutexunlock, manualpathconcat, mapclearloop, mapdeletecheck, nilctxpassed, osexitinlibrary, osgetenvlibrary, osisnotexist, osopenreadallpreferreadfile, osremoveuncheckedcleanup, osstatignoredeerrorderef, ossetenvlibrary, packagelevelmutableslicemap, panic-in-library-code, prefercutprefix, rawloginlib,
// readerstringconv, reflectdeepequalusage, regexpcompileinfunction, regexpdynamicpattern, seenmapbool, slicemakezerolength, sortbasicslices, sortslice, splitindexzero, splitlines-on-newline, sprintferrdot, sprintferrorsnew, sprintfbool, sprintfint, ssljson,
// strconvparseignorederror, stringbytesroundtrip, stringreplaceminusone, stringsconcatloop, stringscountcontains, stringsindexcontains, stringsindexhasprefix, stringsjoinone, stringssplitfirst,
Expand Down Expand Up @@ -176,6 +177,7 @@ func documentedAnalyzers() []docAnalyzer {
{"goroutinemissingrecover", goroutinemissingrecover.Analyzer},
{"goroutineresourceleak", goroutineresourceleak.Analyzer},
{"hardcodedfilepath", hardcodedfilepath.Analyzer},
{"hasprefixdotdotpathescape", hasprefixdotdotpathescape.Analyzer},
{"httpclientnotimeout", httpclientnotimeout.Analyzer},
{"httpnoctx", httpnoctx.Analyzer},
{"httprespbodyclose", httprespbodyclose.Analyzer},
Expand Down
Loading