From 8a81c38d3a801df4cad70daf633ec1ef7175489d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:36:00 +0000 Subject: [PATCH 1/8] brotli: a never-checked finding no longer reads as already fixed pins.Plan took any pin missing on rescan as already fixed unless the file itself carried a skip, so fix (and Sensei's brotlifix, which copies this package) reported it fixed when the rescan never checked it. Plan now returns already only when it read the file in full and the pin is gone from its line, or the file was deleted; otherwise it declines with "rescan to confirm": - a not-checked finding (a skip) or any rule Plan does not plan for (the image check's rules), whatever the file holds now; - a file the rescan cannot read this time: a shell script, Makefile or other text candidate that is now oversized or unreadable (its read recorded no skip), or any file that is now a symbolic link; - a skip anywhere in the rescan, not only one on the finding's own file; - a line past the end of the file; - a line that now pins another release without the fix (the scan's "current" no longer matched, so the pin read as gone); - a cancelled context (the text patterns stop early without an error); - a root that is not there, which read every file as deleted. package-lock.json, npm-shrinkwrap.json, packages.lock.json and global.json that are not valid JSON were dropped without a skip, by the scan as well as the plan; they are reported as not checked now. A deleted Dockerfile or Compose file used to decline (the image reader records a skip for a missing file); it reads as gone now, like any other deleted file. Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/deps.go | 2 + .../brotli/internal/pins/notchecked_test.go | 248 ++++++++++++++++++ detectors/brotli/internal/pins/plan.go | 82 +++++- detectors/brotli/internal/pins/sources.go | 6 +- 4 files changed, 331 insertions(+), 7 deletions(-) create mode 100644 detectors/brotli/internal/pins/notchecked_test.go diff --git a/detectors/brotli/internal/pins/deps.go b/detectors/brotli/internal/pins/deps.go index c78cea6..665d04d 100644 --- a/detectors/brotli/internal/pins/deps.go +++ b/detectors/brotli/internal/pins/deps.go @@ -292,6 +292,7 @@ func (s *scanner) dependencies(rel string, b []byte) { } `json:"packages"` } if json.Unmarshal(b, &doc) != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON"}) return } for key, p := range doc.Packages { @@ -541,6 +542,7 @@ func (s *scanner) nugetLock(rel string, b []byte) { } `json:"dependencies"` } if json.Unmarshal(b, &doc) != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON"}) return } for _, pkgs := range doc.Dependencies { diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go new file mode 100644 index 0000000..32bb591 --- /dev/null +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -0,0 +1,248 @@ +package pins_test + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/DefectDojo/earlylight/detectors/brotli/internal/pins" +) + +// A finding that was not checked, or that cannot be checked again now, is +// never "already fixed": Plan declines with "rescan to confirm" instead. + +// mustDecline fails unless Plan declined with "rescan to confirm". +func mustDecline(t *testing.T, what string, ch *pins.Change, already bool, err error) { + t.Helper() + d, ok := pins.IsDeclined(err) + if already || ch != nil || !ok { + t.Errorf("%s: want a decline, got change %+v, already %v, err %v", what, ch, already, err) + return + } + if !strings.Contains(d.Reason, "rescan to confirm") { + t.Errorf("%s: reason %q does not say rescan to confirm", what, d.Reason) + } +} + +// mustBeGone fails unless Plan reported the finding already fixed. +func mustBeGone(t *testing.T, what string, ch *pins.Change, already bool, err error) { + t.Helper() + if !already || ch != nil || err != nil { + t.Errorf("%s: want already fixed, got change %+v, already %v, err %v", what, ch, already, err) + } +} + +// only scans root and returns its one finding of rule. +func only(t *testing.T, root, rule string) pins.Finding { + t.Helper() + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil { + t.Fatal(err) + } + var out []pins.Finding + for _, f := range res.Findings { + if f.Rule == rule { + out = append(out, f) + } + } + if len(out) != 1 { + t.Fatalf("want one %s finding, got %+v (skips %+v)", rule, res.Findings, res.Skips) + } + return out[0] +} + +func plan(root string, f pins.Finding) (*pins.Change, bool, error) { + return pins.Plan(context.Background(), root, f.File, f.Line, f.Rule, f.Props) +} + +const oversized = 5 << 20 // past the 4 MiB the pin finder reads + +func big(head string) string { return head + strings.Repeat("#\n", oversized/2) } + +// A skip reaches a report as a not-checked finding. Whatever the file holds +// now, Plan did not check what the skip left out. +func TestPlanNotCheckedFinding(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "FROM node@sha256:" + strings.Repeat("a", 64) + "\n"}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 1 || len(res.Findings) != 0 { + t.Fatalf("%v %+v", err, res) + } + sk := res.Skips[0] + try := func(what string) { + t.Helper() + ch, already, err := pins.Plan(ctx, root, sk.File, sk.Line, pins.RuleNotChecked, nil) + mustDecline(t, what, ch, already, err) + } + try("still digest only") + write(t, root, map[string]string{"Dockerfile": "FROM node:24.22.0\n"}) + try("now a vulnerable tag") + write(t, root, map[string]string{"Dockerfile": "FROM node:24-slim\n"}) + try("now a floating tag") + os.Remove(filepath.Join(root, "Dockerfile")) + try("removed") + + // A file-level skip: package.json that was not valid JSON. + write(t, root, map[string]string{"package.json": "{\"volta\": {\"node\": \"24.22.0\"}"}) + res, err = pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 1 { + t.Fatalf("%v %+v", err, res) + } + write(t, root, map[string]string{"package.json": "{\"volta\": {\"node\": \"24.22.1\"}}"}) + ch, already, err := pins.Plan(ctx, root, "package.json", res.Skips[0].Line, pins.RuleNotChecked, nil) + mustDecline(t, "package.json valid now", ch, already, err) + + // Rules this package does not plan for are not checked here either. + for _, rule := range []string{pins.RuleImage, pins.RuleImageUnknown, "", "brotli/other"} { + ch, already, err := pins.Plan(ctx, root, "package.json", 1, rule, nil) + mustDecline(t, "rule "+rule, ch, already, err) + } +} + +// A file the rescan cannot read this time says nothing about the pin. A +// text candidate (a shell script, a Makefile) used to be read without +// recording why it was not. +func TestPlanFileUnreadableNow(t *testing.T) { + for _, c := range []struct{ file, body, rule string }{ + {"install.sh", "export NODE_VERSION=24.22.0\n", pins.RuleNode}, + {"Makefile", "build:\n\tnvm install 24.22.0\n", pins.RuleNode}, + {".nvmrc", "24.22.0\n", pins.RuleNode}, + {"Dockerfile", "FROM node:24.22.0\n", pins.RuleNode}, + {"requirements.txt", "pycurl==7.48.0\n", pins.RuleDependency}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + f := only(t, root, c.rule) + p := filepath.Join(root, c.file) + + os.WriteFile(p, []byte(big(c.body)), 0o644) + ch, already, err := plan(root, f) + mustDecline(t, c.file+" oversized", ch, already, err) + + os.Remove(p) + write(t, root, map[string]string{"real/" + c.file: c.body}) + if err := os.Symlink(filepath.Join("real", c.file), p); err != nil { + t.Fatal(err) + } + ch, already, err = plan(root, f) + mustDecline(t, c.file+" now a symbolic link", ch, already, err) + } +} + +// A lockfile, project or global.json that does not parse this time was +// not checked, and the scan says so. +func TestPlanUnparseableJSON(t *testing.T) { + ctx := context.Background() + for _, c := range []struct{ file, body, rule string }{ + {"web/package-lock.json", "{\n \"packages\": {\n \"node_modules/iltorb\": {\n \"version\": \"2.4.5\"\n }\n }\n}\n", pins.RuleDependency}, + {"npm-shrinkwrap.json", "{\n \"packages\": {\n \"node_modules/iltorb\": {\n \"version\": \"2.4.5\"\n }\n }\n}\n", pins.RuleDependency}, + {"svc/packages.lock.json", depsRepo["svc/packages.lock.json"], pins.RuleDotnet}, + {"global.json", "{\n \"sdk\": {\n \"version\": \"8.0.415\"\n }\n}\n", pins.RuleDotnet}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + f := only(t, root, c.rule) + write(t, root, map[string]string{c.file: c.body[:len(c.body)/2]}) + ch, already, err := plan(root, f) + mustDecline(t, c.file+" not valid JSON", ch, already, err) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 1 || res.Skips[0].File != c.file || !strings.Contains(res.Skips[0].Reason, "not valid JSON") { + t.Errorf("%s: the scan does not report it as not checked: %v %+v", c.file, err, res.Skips) + } + } +} + +// A finding whose line is past the end of the file, or whose line now pins +// another release without the fix, is not fixed: the file changed since +// the scan. +func TestPlanStaleLine(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22 AS a\nRUN true\nFROM node:24.22.0 AS b\n"}) + f := only(t, root, pins.RuleNode) + // Cut short, and the pin moved to line 1 at another vulnerable release. + write(t, root, map[string]string{"Dockerfile": "FROM node:24.21.0\n"}) + ch, already, err := plan(root, f) + mustDecline(t, "past the end", ch, already, err) + // Cut short, nothing left to pin: the line still is not there to check. + write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22\n"}) + ch, already, err = plan(root, f) + mustDecline(t, "past the end, no pin", ch, already, err) + + write(t, root, map[string]string{".nvmrc": "22.23.1\n"}) + only(t, root, pins.RuleNode) + write(t, root, map[string]string{".nvmrc": "22.23.2\n"}) + n := pins.Finding{File: ".nvmrc", Line: 1, Rule: pins.RuleNode, Props: map[string]string{"current": "22.23.1", "source": "nvmrc"}} + ch, already, err = plan(root, n) + mustDecline(t, "another vulnerable release on the line", ch, already, err) +} + +// A cancelled plan read nothing to the end. +func TestPlanCancelled(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"install.sh": "export NODE_VERSION=24.22.0\n"}) + f := only(t, root, pins.RuleNode) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ch, already, err := pins.Plan(ctx, root, f.File, f.Line, f.Rule, f.Props) + if already || ch != nil || err == nil { + t.Fatalf("cancelled: change %+v, already %v, err %v", ch, already, err) + } +} + +// A root that is not there is not a repository with nothing in it. +func TestPlanMissingRoot(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{".nvmrc": "22.23.1\n"}) + f := only(t, root, pins.RuleNode) + ch, already, err := plan(filepath.Join(root, "nope"), f) + if already || ch != nil || err == nil { + t.Fatalf("missing root: change %+v, already %v, err %v", ch, already, err) + } +} + +// What was checked and is really gone still reads as already fixed. +func TestPlanCheckedAndGone(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "install.sh": "export NODE_VERSION=24.22.0\n", + "Dockerfile": "FROM node:24.22.0 AS a\nFROM node:22.23.1 AS b\n", + ".nvmrc": "22.23.1\n", + }) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Findings) != 4 || len(res.Skips) != 0 { + t.Fatalf("%v %+v", err, res) + } + write(t, root, map[string]string{ + "install.sh": "export NODE_VERSION=24.22.1\n", + "Dockerfile": "FROM node:24.22.1 AS a\nFROM node:22.23.1 AS b\n", + ".nvmrc": "lts/*\n", + }) + at := map[string]pins.Finding{} + for _, f := range res.Findings { + at[f.File+":"+itoa(f.Line)] = f + } + for _, k := range []string{".nvmrc:1", "Dockerfile:1", "install.sh:1"} { + ch, already, err := plan(root, at[k]) + mustBeGone(t, k, ch, already, err) + } + // The pin left in place is still found. + if _, already, err := plan(root, at["Dockerfile:2"]); already { + t.Fatalf("Dockerfile:2: already %v, err %v", already, err) + } + // A deleted file has no pins left. + os.Remove(filepath.Join(root, "install.sh")) + ch, already, err := plan(root, at["install.sh:1"]) + mustBeGone(t, "install.sh deleted", ch, already, err) + os.Remove(filepath.Join(root, "Dockerfile")) + ch, already, err = plan(root, at["Dockerfile:2"]) + mustBeGone(t, "Dockerfile deleted", ch, already, err) + // A line 0 finding (the scan did not know the line) is checked by the + // whole file. + f := at[".nvmrc:1"] + f.Line = 0 + ch, already, err = plan(root, f) + mustBeGone(t, ".nvmrc line 0", ch, already, err) +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index 9ee4539..2907bc2 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -3,7 +3,10 @@ package pins import ( "context" "fmt" + "os" "strings" + + "github.com/DefectDojo/earlylight/internal/refs" ) // VerifyImage proves an image change before it is planned: target must hold @@ -16,13 +19,53 @@ func declined(format string, args ...any) error { return &Declined{Reason: clean(fmt.Sprintf(format, args...), 1500)} } +// notChecked declines a finding the plan could not check again: it is not +// known to be fixed, so it must not read as "already fixed". +func notChecked(format string, args ...any) error { + return declined(format+"; rescan to confirm", args...) +} + +// planRules are the rules Plan checks again. A not-checked finding (a skip) +// and the image check's rules name nothing this package can look up, so +// they are never "already fixed" here. +var planRules = map[string]bool{RuleNode: true, RuleDotnet: true, RuleBun: true, RuleDependency: true} + // Plan re-scans file, finds the pin the finding at line names (narrowed by // props source and current when given), and plans the one-line edit to the // fixed release. The edit is verified by scanning the edited file again in // memory: the pin must be fixed and nothing else may change. An image tag is // changed only to a tag the registry shows is published for every platform // the current one has, on the same base OS. It writes nothing. +// +// already is true only when the rescan read the file in full and the pin is +// gone from it, or the file was deleted. A finding that was not checked, or +// cannot be checked again now (the file is unreadable, too large or does not +// parse, the line is past its end, the line pins another release without the +// fix), declines with "rescan to confirm". func Plan(ctx context.Context, root, file string, line int, rule string, props map[string]string) (*Change, bool, error) { + if !planRules[rule] { + return nil, false, notChecked("%s:%d was not checked for the %s fix (%s), and a plan does not check it", file, line, CVE, clean(rule, 60)) + } + if fi, err := os.Stat(root); err != nil { + return nil, false, err + } else if !fi.IsDir() { + return nil, false, fmt.Errorf("%s is not a directory", root) + } + // The file as the scan reads it: what it cannot read says nothing about + // the pin. + probe := &scanner{ctx: ctx, root: root} + now, ok := probe.read(file) + if !ok { + if len(probe.skips) > 0 { + return nil, false, notChecked("%s was not read: %s", file, probe.skips[0].Reason) + } + if p, err := refs.SafePath(root, file); err == nil { + if _, err := os.Lstat(p); err == nil { + return nil, false, notChecked("%s is not a regular file, so it was not read", file) + } + } + return nil, true, nil // deleted: no pin is left in it + } before, err := scanPins(ctx, root, []string{file}, Options{}) if err != nil { return nil, false, err @@ -32,12 +75,8 @@ func Plan(ctx context.Context, root, file string, line int, rule string, props m return nil, false, err } if !found { - for _, sk := range before.skips { - if sk.File == file { - // Not read this time (too large, not parseable): nothing is - // known about the pin, so it is not "already fixed". - return nil, false, declined("%s was not read: %s", file, sk.Reason) - } + if err := unchecked(before, file, line, rule, now); err != nil { + return nil, false, err } return nil, true, nil } @@ -131,9 +170,40 @@ func scanPins(ctx context.Context, root string, files []string, opts Options) (* if err := s.images(files); err != nil { return nil, err } + // A cancelled scan stops early: what it did not reach is not gone. + if err := ctx.Err(); err != nil { + return nil, err + } return s, nil } +// unchecked explains why a pin the rescan did not find is still not known to +// be gone, or returns nil when the rescan checked the place it was. +func unchecked(s *scanner, file string, line int, rule string, content []byte) error { + if len(s.skips) > 0 { + // Not read in full this time (too large, not parseable, an + // unresolved reference): nothing is known about the pin. + return notChecked("%s was not read: %s", s.skips[0].File, s.skips[0].Reason) + } + n := strings.Count(string(content), "\n") + if len(content) > 0 && content[len(content)-1] != '\n' { + n++ + } + if line > n { + return notChecked("line %d is past the end of %s, which changed since the scan", line, file) + } + for _, q := range s.pins { + if q.file == file && q.line == line && q.prod.rule() == rule { + what := q.prod.name() + if q.dep != nil { + what = q.dep.name + } + return notChecked("line %d of %s still pins %s %s, without the fix", line, file, what, q.j.current) + } + } + return nil +} + // choose finds the pin a finding names. found is false when the file no // longer has a vulnerable pin of that rule, source and release: it was fixed // or removed. diff --git a/detectors/brotli/internal/pins/sources.go b/detectors/brotli/internal/pins/sources.go index 23a6234..3cb388a 100644 --- a/detectors/brotli/internal/pins/sources.go +++ b/detectors/brotli/internal/pins/sources.go @@ -270,7 +270,11 @@ func (s *scanner) globalJSON(rel string, b []byte) { Version string `json:"version"` } `json:"sdk"` } - if err := json.Unmarshal(b, &doc); err != nil || doc.SDK.Version == "" { + if err := json.Unmarshal(b, &doc); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON: " + clean(err.Error(), 200)}) + return + } + if doc.SDK.Version == "" { return } v := doc.SDK.Version From 1475fb7b8fd377e67c50af67f296d828ac15e54f Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:59:21 +0000 Subject: [PATCH 2/8] brotli: fixes from the independent review of the not-checked change - A removed last line reads as fixed again. A line past the end of the file declines only while the file still pins a release of that rule without the fix (or has a skip on any line); read in full with nothing left, the pin is gone, wherever its line sat. - A line 0 finding declines while the file pins any release of that rule without the fix. - Plan cleans the path as Scan does: ./Dockerfile, svc/../Dockerfile and svc//compose.yaml no longer read an untouched pin as already fixed. - A file whose directory was deleted is deleted. Read errors and Plan's messages no longer carry the checkout's absolute path. - Only a skip on the whole file, or on the finding's own line, holds back "already fixed"; the message names the line. A digest-only or unresolved stage elsewhere in a Dockerfile no longer does. - The JSON readers see // and /* */ comments and a leading byte-order mark as spaces (lines and columns kept): a commented global.json, which the .NET SDK accepts, and a package.json or packages.lock.json saved with a BOM are read instead of reported as not checked. - Lockfile skips say what failed: not valid JSON, or JSON of another shape (with the parser's message). A lockfileVersion 1 package-lock.json and a Pipfile.lock section of another shape are reported as not checked instead of dropped. - FuzzPins checks that a finding the scan just reported never plans as already fixed. Two cases still read as gone, since Plan cannot tell them from a fix (noted in the code): a pin that moved and changed to another vulnerable release in a file that did not get shorter, and a path that never held the pin. Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/brotlipin.go | 88 +++++++- detectors/brotli/internal/pins/deps.go | 24 ++- detectors/brotli/internal/pins/fuzz_test.go | 13 +- .../brotli/internal/pins/notchecked_test.go | 195 +++++++++++++++++- detectors/brotli/internal/pins/plan.go | 95 +++++++-- detectors/brotli/internal/pins/sources.go | 2 +- 6 files changed, 373 insertions(+), 44 deletions(-) diff --git a/detectors/brotli/internal/pins/brotlipin.go b/detectors/brotli/internal/pins/brotlipin.go index 53be37a..463741a 100644 --- a/detectors/brotli/internal/pins/brotlipin.go +++ b/detectors/brotli/internal/pins/brotlipin.go @@ -476,7 +476,7 @@ func (s *scanner) walk() ([]string, error) { err := filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error { if err != nil { rel, _ := filepath.Rel(s.root, p) - s.skips = append(s.skips, Skip{File: filepath.ToSlash(rel), Reason: "could not be read: " + clean(err.Error(), 200)}) + s.skips = append(s.skips, Skip{File: filepath.ToSlash(rel), Reason: "could not be read: " + clean(errText(err), 200)}) if d != nil && d.IsDir() { return fs.SkipDir } @@ -526,13 +526,17 @@ func (s *scanner) read(rel string) ([]byte, bool) { } p, err := refs.SafePath(s.root, rel) if err != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: clean(err.Error(), 200)}) + // A directory on the way that is not there: the file is not + // there either. + if !errors.Is(err, fs.ErrNotExist) { + s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(errText(err), 200)}) + } return nil, false } fi, err := os.Lstat(p) if err != nil { if !os.IsNotExist(err) { - s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(err.Error(), 200)}) + s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(errText(err), 200)}) } return nil, false } @@ -545,13 +549,13 @@ func (s *scanner) read(rel string) ([]byte, bool) { } f, err := os.Open(p) if err != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(err.Error(), 200)}) + s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(errText(err), 200)}) return nil, false } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, s.opts.maxSize()+1)) if err != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(err.Error(), 200)}) + s.skips = append(s.skips, Skip{File: rel, Reason: "could not be read: " + clean(errText(err), 200)}) return nil, false } s.files++ @@ -573,6 +577,12 @@ func (s *scanner) parseFile(rel string, k fileKind) { if !ok { return } + // The JSON readers see comments and a byte-order mark as spaces, so + // every line and column stays where it is in the file. + text := b + if isJSON(rel) { + b = jsonText(b) + } switch k { case kindNvmrc: s.versionFile(rel, b, node, "nvmrc", ".nvmrc") @@ -600,7 +610,7 @@ func (s *scanner) parseFile(rel string, k fileKind) { s.netlify(rel, b) } if textCandidate(rel) { - s.textPatterns(rel, b) + s.textPatterns(rel, text) } if dependencyFile(rel) { s.dependencies(rel, b) @@ -715,7 +725,7 @@ func (s *scanner) mise(rel string, b []byte) { func (s *scanner) packageJSON(rel string, b []byte) { var raw map[string]json.RawMessage if err := json.Unmarshal(b, &raw); err != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON: " + clean(err.Error(), 200)}) + s.skips = append(s.skips, Skip{File: rel, Reason: jsonProblem(err)}) return } // Each field is read on its own: an old-style "engines" array or any @@ -1038,3 +1048,67 @@ func ImageUpgrade(image string) (string, string, bool) { } return base[:i] + ":" + strings.Replace(ref.Tag, j.current, up, 1), kind, true } + +func isJSON(rel string) bool { + return strings.HasSuffix(strings.ToLower(rel), ".json") || path.Base(rel) == "Pipfile.lock" +} + +// jsonText returns b with a leading byte-order mark and // and /* */ +// comments outside strings replaced by spaces, line breaks kept: global.json +// may carry comments, and a file saved by some Windows editors starts with a +// byte-order mark. Lines and byte columns are unchanged. +func jsonText(b []byte) []byte { + out := append([]byte(nil), b...) + if bytes.HasPrefix(out, []byte("\xef\xbb\xbf")) { + copy(out, " ") + } + blank := func(from, to int) { + for k := from; k < to; k++ { + if out[k] != '\n' && out[k] != '\r' { + out[k] = ' ' + } + } + } + for i := 0; i < len(out); i++ { + switch out[i] { + case '"': + for i++; i < len(out) && out[i] != '"' && out[i] != '\n'; i++ { + if out[i] == '\\' { + i++ + } + } + case '/': + if i+1 >= len(out) { + break + } + switch out[i+1] { + case '/': + e := bytes.IndexByte(out[i:], '\n') + if e < 0 { + e = len(out) - i + } + blank(i, i+e) + i += e - 1 + case '*': + e := bytes.Index(out[i+2:], []byte("*/")) + end := len(out) + if e >= 0 { + end = i + 2 + e + 2 + } + blank(i, end) + i = end - 1 + } + } + } + return out +} + +// jsonProblem says why a JSON file was not read: not JSON, or JSON of +// another shape than the reader expects. +func jsonProblem(err error) string { + var te *json.UnmarshalTypeError + if errors.As(err, &te) { + return "not the expected shape: " + clean(err.Error(), 200) + } + return "not valid JSON: " + clean(err.Error(), 200) +} diff --git a/detectors/brotli/internal/pins/deps.go b/detectors/brotli/internal/pins/deps.go index 665d04d..58edf6f 100644 --- a/detectors/brotli/internal/pins/deps.go +++ b/detectors/brotli/internal/pins/deps.go @@ -290,9 +290,15 @@ func (s *scanner) dependencies(rel string, b []byte) { Packages map[string]struct { Version string `json:"version"` } `json:"packages"` + Dependencies json.RawMessage `json:"dependencies"` } - if json.Unmarshal(b, &doc) != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON"}) + if err := json.Unmarshal(b, &doc); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: jsonProblem(err)}) + return + } + if doc.Packages == nil && len(doc.Dependencies) > 0 { + // npm 6 and older wrote only the nested "dependencies" tree. + s.skips = append(s.skips, Skip{File: rel, Reason: `a lockfileVersion 1 lockfile (npm 6 and older, no "packages" map) is not read; npm 7 or later rewrites it`}) return } for key, p := range doc.Packages { @@ -358,15 +364,19 @@ func (s *scanner) dependencies(rel string, b []byte) { case base == "Pipfile.lock": // Only default and develop: _meta and anything else have other shapes. var raw map[string]json.RawMessage - if json.Unmarshal(b, &raw) != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON"}) + if err := json.Unmarshal(b, &raw); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: jsonProblem(err)}) return } for _, sec := range []string{"default", "develop"} { var pkgs map[string]struct { Version string `json:"version"` } - if json.Unmarshal(raw[sec], &pkgs) != nil { + if raw[sec] == nil { + continue + } + if err := json.Unmarshal(raw[sec], &pkgs); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: sec + ": " + jsonProblem(err)}) continue } for name, p := range pkgs { @@ -541,8 +551,8 @@ func (s *scanner) nugetLock(rel string, b []byte) { Resolved string `json:"resolved"` } `json:"dependencies"` } - if json.Unmarshal(b, &doc) != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON"}) + if err := json.Unmarshal(b, &doc); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: jsonProblem(err)}) return } for _, pkgs := range doc.Dependencies { diff --git a/detectors/brotli/internal/pins/fuzz_test.go b/detectors/brotli/internal/pins/fuzz_test.go index 83719c8..1c084fd 100644 --- a/detectors/brotli/internal/pins/fuzz_test.go +++ b/detectors/brotli/internal/pins/fuzz_test.go @@ -15,10 +15,12 @@ var fuzzNames = []string{".nvmrc", ".tool-versions", "mise.toml", "package.json" "poetry.lock", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "Pipfile.lock", "Gemfile", "Gemfile.lock", "pom.xml", "build.gradle.kts", "gradle.lockfile", "libs.versions.toml", "Cargo.lock", "go.mod", "packages.lock.json", "compose.yaml"} -// Hostile file content never panics the scan or a plan, and a plan only -// ever edits the file the finding names. +// Hostile file content never panics the scan or a plan, a finding the scan +// just reported never plans as already fixed, and a plan only ever edits +// the file the finding names. func FuzzPins(f *testing.F) { for _, s := range []string{"20\n", "FROM node:24.22.0-slim\n", "{\"engines\":{\"node\":\"20.x\"}}", "pycurl==7.48.0\n", + "\ufeff{\"sdk\": {/* \"version\": \"8.0.1\" */ \"version\": \"8.0.415\"}} // \"https://x\"\n", "jobs:\n a:\n strategy:\n matrix:\n n: [20]\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ matrix.n }}\n"} { for i := range fuzzNames { f.Add(uint8(i), s) @@ -37,7 +39,12 @@ func FuzzPins(f *testing.F) { return } for _, fd := range res.Findings { - ch, _, err := pins.Plan(context.Background(), dir, fd.File, fd.Line, fd.Rule, fd.Props) + ch, already, err := pins.Plan(context.Background(), dir, fd.File, fd.Line, fd.Rule, fd.Props) + if already { + // The file has not changed since the scan: a finding it + // just reported is never already fixed. + t.Fatalf("%s:%d %s %v, just reported, plans as already fixed", fd.File, fd.Line, fd.Rule, fd.Props) + } if err != nil || ch == nil { continue } diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go index 32bb591..9f2e8bf 100644 --- a/detectors/brotli/internal/pins/notchecked_test.go +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -155,9 +155,9 @@ func TestPlanUnparseableJSON(t *testing.T) { } } -// A finding whose line is past the end of the file, or whose line now pins -// another release without the fix, is not fixed: the file changed since -// the scan. +// A finding whose line is past the end of a file that still pins another +// release without the fix, or whose line now pins one, is not fixed: the +// file changed since the scan. func TestPlanStaleLine(t *testing.T) { root := t.TempDir() write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22 AS a\nRUN true\nFROM node:24.22.0 AS b\n"}) @@ -166,10 +166,10 @@ func TestPlanStaleLine(t *testing.T) { write(t, root, map[string]string{"Dockerfile": "FROM node:24.21.0\n"}) ch, already, err := plan(root, f) mustDecline(t, "past the end", ch, already, err) - // Cut short, nothing left to pin: the line still is not there to check. + // Cut short, nothing left to pin: read in full, the pin is gone. write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22\n"}) ch, already, err = plan(root, f) - mustDecline(t, "past the end, no pin", ch, already, err) + mustBeGone(t, "past the end, no pin", ch, already, err) write(t, root, map[string]string{".nvmrc": "22.23.1\n"}) only(t, root, pins.RuleNode) @@ -246,3 +246,188 @@ func TestPlanCheckedAndGone(t *testing.T) { ch, already, err = plan(root, f) mustBeGone(t, ".nvmrc line 0", ch, already, err) } + +// Removing the pin's line is a fix wherever the line sat, the last line +// included, as long as nothing of that rule is left in the file. +func TestPlanRemovedLastLine(t *testing.T) { + for _, c := range []struct{ file, body, now, rule string }{ + {"tools/.tool-versions", "python 3.13.1\nnodejs 22.23.1\n", "python 3.13.1\n", pins.RuleNode}, + {"requirements.txt", "requests==2.32.3\npycurl==7.48.0\n", "requests==2.32.3\n", pins.RuleDependency}, + {".nvmrc", "22.23.1\n", "", pins.RuleNode}, + {"Dockerfile", "FROM alpine:3.22 AS a\nRUN true\nFROM node:24.22.0 AS b\n", "FROM alpine:3.22 AS a\nRUN true\n", pins.RuleNode}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + f := only(t, root, c.rule) + write(t, root, map[string]string{c.file: c.now}) + ch, already, err := plan(root, f) + mustBeGone(t, c.file+" last line removed", ch, already, err) + } +} + +// A line 0 finding (the scan did not know the line) is not gone while the +// file pins any release of that rule without the fix. +func TestPlanLineZeroStillPinned(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{".nvmrc": "22.23.2\n"}) + f := pins.Finding{File: ".nvmrc", Line: 0, Rule: pins.RuleNode, Props: map[string]string{"current": "22.23.1", "source": "nvmrc"}} + ch, already, err := plan(root, f) + mustDecline(t, "line 0, another vulnerable release", ch, already, err) +} + +// Plan reads a path in any form the scan would have cleaned to the same file. +func TestPlanPathForms(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{ + "Dockerfile": "FROM node:24.22.0\n", + "svc/compose.yaml": "services:\n web:\n image: node:24.22.0\n", + ".nvmrc": "22.23.1\n", + }) + for _, c := range []struct { + file string + line int + }{{"./Dockerfile", 1}, {"svc/../Dockerfile", 1}, {"svc//compose.yaml", 3}, {"./svc/compose.yaml", 3}, {"./.nvmrc", 1}} { + ch, already, err := pins.Plan(context.Background(), root, c.file, c.line, pins.RuleNode, nil) + if already { + t.Errorf("%s: an untouched vulnerable pin reads as already fixed (change %+v, err %v)", c.file, ch, err) + } + } + ch, _, err := pins.Plan(context.Background(), root, "./.nvmrc", 1, pins.RuleNode, nil) + if err != nil || ch == nil || ch.File != ".nvmrc" { + t.Errorf("./.nvmrc: change %+v, err %v", ch, err) + } +} + +// A file whose directory was deleted is deleted. What cannot be read never +// names the checkout's absolute path. +func TestPlanDirectoryDeleted(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"svc/.nvmrc": "22.23.1\n"}) + f := only(t, root, pins.RuleNode) + os.RemoveAll(filepath.Join(root, "svc")) + ch, already, err := plan(root, f) + mustBeGone(t, "directory removed", ch, already, err) + + long := strings.Repeat("a", 300) + "/.nvmrc" // the directory name is too long to look up + ch, already, err = pins.Plan(context.Background(), root, long, 1, pins.RuleNode, nil) + mustDecline(t, "name too long", ch, already, err) + if err != nil && strings.Contains(err.Error(), root) { + t.Errorf("the message names the absolute path: %v", err) + } + _, _, err = pins.Plan(context.Background(), filepath.Join(root, "nope"), ".nvmrc", 1, pins.RuleNode, nil) + if err == nil || strings.Contains(err.Error(), root) { + t.Errorf("missing root: %v", err) + } +} + +// Which skips hold back "already fixed": one on the whole file, or one on +// the finding's own line. A skip on another line of the file is about +// another pin, and is reported on its own. +func TestPlanSkipScope(t *testing.T) { + digest := "FROM node@sha256:" + strings.Repeat("a", 64) + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": digest + " AS a\nFROM node:24.22.0 AS b\n"}) + f := only(t, root, pins.RuleNode) + if f.Line != 2 { + t.Fatalf("%+v", f) + } + // Fixed; the digest-only stage on line 1 is still not checked. + write(t, root, map[string]string{"Dockerfile": digest + " AS a\nFROM node:24.22.1 AS b\n"}) + ch, already, err := plan(root, f) + mustBeGone(t, "skip on another line", ch, already, err) + // Line 2 itself is digest only now. + write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22 AS a\n" + digest + " AS b\n"}) + ch, already, err = plan(root, f) + mustDecline(t, "skip on the finding's line", ch, already, err) + if d, ok := pins.IsDeclined(err); ok && !strings.Contains(d.Reason, "line 2") { + t.Errorf("the decline does not name the line: %q", d.Reason) + } + // A line 0 finding is held back by a skip on any line. + g := f + g.Line = 0 + ch, already, err = plan(root, g) + mustDecline(t, "line 0 with a skip in the file", ch, already, err) + // The finding's line is past the end now: a skip on any line of the + // file may be where its pin went. + write(t, root, map[string]string{"Dockerfile": digest + " AS b\n"}) + ch, already, err = plan(root, f) + mustDecline(t, "past the end with a skip in the file", ch, already, err) + // A skip on the whole file holds back every finding in it. + write(t, root, map[string]string{"package.json": "{\n \"volta\": {\n \"node\": \"24.22.0\"\n }\n}\n"}) + v := only(t, root, pins.RuleNode) + write(t, root, map[string]string{"package.json": "{\n \"volta\": {\n \"node\": \"24.22.1\"\n }\n}\n,"}) + ch, already, err = plan(root, v) + mustDecline(t, "skip on the whole file", ch, already, err) +} + +// global.json may carry comments and a byte-order mark, which the .NET SDK +// accepts; package.json and packages.lock.json may start with a byte-order +// mark. They are read, not reported as not checked. +func TestJSONCommentsAndBOM(t *testing.T) { + ctx := context.Background() + bom := "\ufeff" + for _, c := range []struct { + file, body string + line int + rule, want string + }{ + {"global.json", bom + "{\n // pinned for the build agents, see https://example.com/x\n \"sdk\": {\n /* \"version\": \"8.0.100\" */ \"version\": \"8.0.415\",\n \"rollForward\": \"disable\"\n }\n}\n", + 4, pins.RuleDotnet, ` /* "version": "8.0.100" */ "version": "8.0.427",`}, + {"app/package.json", bom + "{\n \"volta\": {\n \"node\": \"24.22.0\"\n }\n}\n", 3, pins.RuleNode, ` "node": "24.22.1"`}, + {"svc/packages.lock.json", bom + depsRepo["svc/packages.lock.json"], 0, pins.RuleDotnet, ""}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 0 || len(res.Findings) != 1 || res.Findings[0].Rule != c.rule { + t.Errorf("%s: %v findings %+v skips %+v", c.file, err, res.Findings, res.Skips) + continue + } + f := res.Findings[0] + if c.line != 0 && f.Line != c.line { + t.Errorf("%s: line %d, want %d", c.file, f.Line, c.line) + } + if c.want == "" { + continue + } + ch, _, err := plan(root, f) + if err != nil || ch == nil || ch.Edits[0].New[0] != c.want { + t.Errorf("%s: change %+v, err %v", c.file, ch, err) + } + } + // Fixed, or without an sdk key, a commented global.json is clean. + for _, body := range []string{"{\n // fixed\n \"sdk\": { \"version\": \"8.0.427\" }\n}\n", "/* tools only */ { \"msbuild-sdks\": {} }\n"} { + root := t.TempDir() + write(t, root, map[string]string{"global.json": body}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 0 || len(res.Findings) != 0 { + t.Errorf("%q: %v %+v", body, err, res) + } + } +} + +// A lockfile that is not read says why: not JSON, JSON of another shape, or +// a lockfile version the scan does not read. +func TestLockfileSkipReasons(t *testing.T) { + for _, c := range []struct{ file, body, want string }{ + {"package-lock.json", "{\"packages\": {", "not valid JSON: unexpected end"}, + {"package-lock.json", "{\"packages\": []}", "not the expected shape"}, + {"package-lock.json", "{\"lockfileVersion\": 1, \"dependencies\": {\"iltorb\": {\"version\": \"2.4.5\"}}}", "lockfileVersion 1"}, + {"packages.lock.json", "{\"dependencies\": []}", "not the expected shape"}, + {"Pipfile.lock", "{\"default\": [", "not valid JSON: unexpected end"}, + {"Pipfile.lock", "{\"default\": []}", "not the expected shape"}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 1 || !strings.Contains(res.Skips[0].Reason, c.want) { + t.Errorf("%s %q: %v skips %+v, want a reason with %q", c.file, c.body, err, res.Skips, c.want) + } + } + // A lockfile with nothing in it is read, not skipped. + root := t.TempDir() + write(t, root, map[string]string{"package-lock.json": "{\"name\": \"x\", \"lockfileVersion\": 3, \"packages\": {}}"}) + if res, err := pins.Scan(context.Background(), root, nil, pins.Options{}); err != nil || len(res.Skips) != 0 { + t.Errorf("empty lockfile: %v %+v", err, res.Skips) + } +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index 2907bc2..eda6d28 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -2,8 +2,12 @@ package pins import ( "context" + "errors" "fmt" + "io/fs" "os" + "path" + "path/filepath" "strings" "github.com/DefectDojo/earlylight/internal/refs" @@ -38,18 +42,24 @@ var planRules = map[string]bool{RuleNode: true, RuleDotnet: true, RuleBun: true, // the current one has, on the same base OS. It writes nothing. // // already is true only when the rescan read the file in full and the pin is -// gone from it, or the file was deleted. A finding that was not checked, or -// cannot be checked again now (the file is unreadable, too large or does not -// parse, the line is past its end, the line pins another release without the -// fix), declines with "rescan to confirm". +// gone from it, or the file (or its directory) was deleted. A finding that +// was not checked, or cannot be checked again now, declines with "rescan to +// confirm": the file is unreadable, too large or does not parse; its line +// was not checked (a skip on that line); its line pins another release +// without the fix; or it has no line any more (line 0, or past the end of +// the file) and the file still pins a release of that rule without the fix +// or has a skip on any line. func Plan(ctx context.Context, root, file string, line int, rule string, props map[string]string) (*Change, bool, error) { + // The path as the scan writes it: ./Dockerfile and svc/../Dockerfile + // are Dockerfile, or the pins found in it would not match. + file = strings.TrimPrefix(path.Clean(filepath.ToSlash(file)), "./") if !planRules[rule] { return nil, false, notChecked("%s:%d was not checked for the %s fix (%s), and a plan does not check it", file, line, CVE, clean(rule, 60)) } if fi, err := os.Stat(root); err != nil { - return nil, false, err + return nil, false, fmt.Errorf("the repository root cannot be read: %s", errText(err)) } else if !fi.IsDir() { - return nil, false, fmt.Errorf("%s is not a directory", root) + return nil, false, errors.New("the repository root is not a directory") } // The file as the scan reads it: what it cannot read says nothing about // the pin. @@ -57,7 +67,7 @@ func Plan(ctx context.Context, root, file string, line int, rule string, props m now, ok := probe.read(file) if !ok { if len(probe.skips) > 0 { - return nil, false, notChecked("%s was not read: %s", file, probe.skips[0].Reason) + return nil, false, notChecked("%s was not read: %s", file, scrub(root, probe.skips[0].Reason)) } if p, err := refs.SafePath(root, file); err == nil { if _, err := os.Lstat(p); err == nil { @@ -75,7 +85,7 @@ func Plan(ctx context.Context, root, file string, line int, rule string, props m return nil, false, err } if !found { - if err := unchecked(before, file, line, rule, now); err != nil { + if err := unchecked(root, before, file, line, rule, now); err != nil { return nil, false, err } return nil, true, nil @@ -179,31 +189,74 @@ func scanPins(ctx context.Context, root string, files []string, opts Options) (* // unchecked explains why a pin the rescan did not find is still not known to // be gone, or returns nil when the rescan checked the place it was. -func unchecked(s *scanner, file string, line int, rule string, content []byte) error { - if len(s.skips) > 0 { - // Not read in full this time (too large, not parseable, an - // unresolved reference): nothing is known about the pin. - return notChecked("%s was not read: %s", s.skips[0].File, s.skips[0].Reason) - } +// +// Two cases cannot be told apart from a fix, and read as gone: a pin that +// moved to another line and changed to another release without the fix, in +// a file that did not get shorter (it looks like a second pin that was +// always there), and a path that never held the pin (a wrong path, a +// renamed file, a file no reader handles), which looks like a deleted file. +func unchecked(root string, s *scanner, file string, line int, rule string, content []byte) error { n := strings.Count(string(content), "\n") if len(content) > 0 && content[len(content)-1] != '\n' { n++ } - if line > n { - return notChecked("line %d is past the end of %s, which changed since the scan", line, file) + // Without its line (line 0, or a line past the end of a file that got + // shorter) the finding may be anywhere in the file now. + lost := line == 0 || line > n + for _, sk := range s.skips { + switch { + case sk.Line == 0: + // Not read in full this time (too large, not parseable): + // nothing is known about the pin. + return notChecked("%s was not read: %s", sk.File, scrub(root, sk.Reason)) + case sk.File == file && (lost || sk.Line == line): + // That line (an unresolved reference, an image pinned by + // digest only) was not checked. A skip on another line is + // about another pin, which is reported on its own. + return notChecked("line %d of %s was not checked: %s", sk.Line, sk.File, scrub(root, sk.Reason)) + } } for _, q := range s.pins { - if q.file == file && q.line == line && q.prod.rule() == rule { - what := q.prod.name() - if q.dep != nil { - what = q.dep.name - } + if q.file != file || q.prod.rule() != rule { + continue + } + what := q.prod.name() + if q.dep != nil { + what = q.dep.name + } + switch { + case q.line == line: return notChecked("line %d of %s still pins %s %s, without the fix", line, file, what, q.j.current) + case line == 0: + return notChecked("%s still pins %s %s on line %d, without the fix, and the finding names no line", file, what, q.j.current, q.line) + case line > n: + return notChecked("line %d is past the end of %s, which still pins %s %s on line %d, without the fix", line, file, what, q.j.current, q.line) } } return nil } +// errText is err without the absolute path a file system error carries. +func errText(err error) string { + var pe *fs.PathError + if errors.As(err, &pe) { + return pe.Err.Error() + } + return err.Error() +} + +// scrub removes the checkout's absolute path from a reason. +func scrub(root, s string) string { + for _, r := range []string{root, filepath.Clean(root)} { + if r == "" || r == "." { + continue + } + s = strings.ReplaceAll(s, r+string(filepath.Separator), "") + s = strings.ReplaceAll(s, r, ".") + } + return s +} + // choose finds the pin a finding names. found is false when the file no // longer has a vulnerable pin of that rule, source and release: it was fixed // or removed. diff --git a/detectors/brotli/internal/pins/sources.go b/detectors/brotli/internal/pins/sources.go index 3cb388a..54a5b9e 100644 --- a/detectors/brotli/internal/pins/sources.go +++ b/detectors/brotli/internal/pins/sources.go @@ -271,7 +271,7 @@ func (s *scanner) globalJSON(rel string, b []byte) { } `json:"sdk"` } if err := json.Unmarshal(b, &doc); err != nil { - s.skips = append(s.skips, Skip{File: rel, Reason: "not valid JSON: " + clean(err.Error(), 200)}) + s.skips = append(s.skips, Skip{File: rel, Reason: jsonProblem(err)}) return } if doc.SDK.Version == "" { From 6bbe5b48e31fa339cdf29ae329c688bbdfa34203 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:30:04 +0000 Subject: [PATCH 3/8] brotli: second review round of the not-checked change - An image pin that moved off its line and became a reference the scan cannot judge (FROM node:${NODE_VERSION} with no default, a digest-only FROM under an added # syntax= line) no longer reads as already fixed: for an image finding, or one without props, a skip elsewhere in the file holds it back unless a resolved image still sits on the finding's own line. A pin fixed in place still reads as fixed, and a text pin is held back only by a skip on its own line, as before. - The text patterns read a JSON file as the JSON readers do, so a value inside a comment is not a pin. - The column of a pin on line 1 does not count a byte-order mark. - A lockfileVersion 1 package-lock.json with no dependencies is not reported as not checked. - scrub removed "/" too few for a root written with a trailing slash ("open .a.json"); it works on the cleaned root. - Tests for each, and for // and /* */ inside JSON strings and the line breaks inside a block comment. Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/brotlipin.go | 32 ++++- detectors/brotli/internal/pins/deps.go | 11 +- detectors/brotli/internal/pins/export_test.go | 4 + .../brotli/internal/pins/notchecked_test.go | 115 ++++++++++++++++++ detectors/brotli/internal/pins/plan.go | 36 ++++-- 5 files changed, 179 insertions(+), 19 deletions(-) create mode 100644 detectors/brotli/internal/pins/export_test.go diff --git a/detectors/brotli/internal/pins/brotlipin.go b/detectors/brotli/internal/pins/brotlipin.go index 463741a..575488b 100644 --- a/detectors/brotli/internal/pins/brotlipin.go +++ b/detectors/brotli/internal/pins/brotlipin.go @@ -316,8 +316,16 @@ type scanner struct { files int truncated bool lines map[string][]string // files split once per scan, for columns + // refLines holds file\x00line for every image reference the scan + // resolved, judged or not. + refLines map[string]bool + // bom holds the files that start with a byte-order mark, which is not + // part of line 1's columns. + bom map[string]bool } +func lineKey(file string, line int) string { return fmt.Sprint(file, "\x00", line) } + // exists reports a regular file in the repository (or the overlay). func (s *scanner) exists(rel string) bool { if _, ok := s.opts.Overlay[rel]; ok { @@ -382,7 +390,12 @@ func (s *scanner) result() Result { continue } seen[k] = true - r.Findings = append(r.Findings, p.finding()) + f := p.finding() + if c, err := strconv.Atoi(f.Props["column"]); err == nil && p.line == 1 && s.bom[p.file] && c > len(utf8BOM) { + // The byte-order mark is not text on the line. + f.Props["column"] = strconv.Itoa(c - len(utf8BOM)) + } + r.Findings = append(r.Findings, f) } sort.SliceStable(r.Findings, func(i, j int) bool { a, b := r.Findings[i], r.Findings[j] @@ -579,7 +592,12 @@ func (s *scanner) parseFile(rel string, k fileKind) { } // The JSON readers see comments and a byte-order mark as spaces, so // every line and column stays where it is in the file. - text := b + if bytes.HasPrefix(b, utf8BOM) { + if s.bom == nil { + s.bom = map[string]bool{} + } + s.bom[rel] = true + } if isJSON(rel) { b = jsonText(b) } @@ -610,7 +628,7 @@ func (s *scanner) parseFile(rel string, k fileKind) { s.netlify(rel, b) } if textCandidate(rel) { - s.textPatterns(rel, text) + s.textPatterns(rel, b) // in JSON, a value inside a comment is not a pin } if dependencyFile(rel) { s.dependencies(rel, b) @@ -873,6 +891,10 @@ func (s *scanner) images(files []string) error { s.skips = append(s.skips, Skip{File: k.File, Line: k.Line, Reason: clean(k.Reason, 200)}) } for _, r := range rs { + if s.refLines == nil { + s.refLines = map[string]bool{} + } + s.refLines[lineKey(r.File, r.Line)] = true s.judgeImage(r) } return nil @@ -1049,6 +1071,8 @@ func ImageUpgrade(image string) (string, string, bool) { return base[:i] + ":" + strings.Replace(ref.Tag, j.current, up, 1), kind, true } +var utf8BOM = []byte("\xef\xbb\xbf") + func isJSON(rel string) bool { return strings.HasSuffix(strings.ToLower(rel), ".json") || path.Base(rel) == "Pipfile.lock" } @@ -1059,7 +1083,7 @@ func isJSON(rel string) bool { // byte-order mark. Lines and byte columns are unchanged. func jsonText(b []byte) []byte { out := append([]byte(nil), b...) - if bytes.HasPrefix(out, []byte("\xef\xbb\xbf")) { + if bytes.HasPrefix(out, utf8BOM) { copy(out, " ") } blank := func(from, to int) { diff --git a/detectors/brotli/internal/pins/deps.go b/detectors/brotli/internal/pins/deps.go index 58edf6f..bbe0e27 100644 --- a/detectors/brotli/internal/pins/deps.go +++ b/detectors/brotli/internal/pins/deps.go @@ -298,8 +298,15 @@ func (s *scanner) dependencies(rel string, b []byte) { } if doc.Packages == nil && len(doc.Dependencies) > 0 { // npm 6 and older wrote only the nested "dependencies" tree. - s.skips = append(s.skips, Skip{File: rel, Reason: `a lockfileVersion 1 lockfile (npm 6 and older, no "packages" map) is not read; npm 7 or later rewrites it`}) - return + var deps map[string]json.RawMessage + if err := json.Unmarshal(doc.Dependencies, &deps); err != nil { + s.skips = append(s.skips, Skip{File: rel, Reason: "dependencies: " + jsonProblem(err)}) + return + } + if len(deps) > 0 { + s.skips = append(s.skips, Skip{File: rel, Reason: `a lockfileVersion 1 lockfile (npm 6 and older, no "packages" map) is not read; npm 7 or later rewrites it`}) + return + } } for key, p := range doc.Packages { i := strings.LastIndex(key, "node_modules/") diff --git a/detectors/brotli/internal/pins/export_test.go b/detectors/brotli/internal/pins/export_test.go new file mode 100644 index 0000000..fe790dc --- /dev/null +++ b/detectors/brotli/internal/pins/export_test.go @@ -0,0 +1,4 @@ +package pins + +// Scrub is scrub, for the external tests. +var Scrub = scrub diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go index 9f2e8bf..274837b 100644 --- a/detectors/brotli/internal/pins/notchecked_test.go +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -431,3 +431,118 @@ func TestLockfileSkipReasons(t *testing.T) { t.Errorf("empty lockfile: %v %+v", err, res.Skips) } } + +// An image pin that moved off its line and became a reference the scan +// cannot judge (an ARG with no default, an image pinned by digest only) +// is not fixed: the skip on its new line holds back "already fixed" +// unless a resolved image still sits on the finding's own line. +func TestPlanImageMovedAndUnresolved(t *testing.T) { + digest := "node@sha256:" + strings.Repeat("a", 64) + for _, c := range []struct{ what, now string }{ + {"an ARG with no default", "ARG NODE_VERSION\nFROM node:${NODE_VERSION}\n"}, + {"a syntax line above a digest-only FROM", "# syntax=docker/dockerfile:1\nFROM " + digest + "\n"}, + } { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "FROM node:24.22.0\n"}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{"Dockerfile": c.now}) + ch, already, err := plan(root, f) + mustDecline(t, c.what, ch, already, err) + // Without the finding's props the plan cannot tell an image pin + // from another: it holds back too. + ch, already, err = pins.Plan(context.Background(), root, f.File, f.Line, f.Rule, nil) + mustDecline(t, c.what+", no props", ch, already, err) + } + // Fixed in place, with an unresolved stage elsewhere: fixed. + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "FROM node:24.22.0 AS a\nARG BASE\nFROM ${BASE} AS b\n"}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{"Dockerfile": "FROM node:24.22.1 AS a\nARG BASE\nFROM ${BASE} AS b\n"}) + ch, already, err := plan(root, f) + mustBeGone(t, "fixed in place", ch, already, err) + // A text pin is not an image: a skip on another line does not hold it. + write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22\nENV NODE_VERSION=24.22.0\nFROM " + digest + "\n"}) + g := only(t, root, pins.RuleNode) + write(t, root, map[string]string{"Dockerfile": "FROM alpine:3.22\nENV NODE_VERSION=24.22.1\nFROM " + digest + "\n"}) + ch, already, err = plan(root, g) + mustBeGone(t, "a text pin fixed in place", ch, already, err) +} + +// The comment reader leaves strings alone and keeps every line break, and +// the text patterns read what it leaves: a URL in a JSON string is not a +// comment, and a pin inside a comment is not a pin. +func TestJSONTextKeepsStringsAndLines(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, map[string]string{ + "app/package.json": "{\n \"homepage\": \"https://example.com/a//b\",\n \"repository\": \"git://x/*not a comment*/\",\n \"volta\": {\n \"node\": \"24.22.0\"\n }\n}\n", + "global.json": "{\n /* the SDK\n for the build\n agents */\n \"sdk\": {\n \"version\": \"8.0.415\"\n }\n}\n", + "tools.json": "{\n // was \"https://nodejs.org/dist/v24.21.0/node.tar.gz\"\n \"url\": \"https://nodejs.org/dist/v24.22.0/node.tar.gz\"\n}\n", + }) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 0 { + t.Fatalf("%v %+v", err, res.Skips) + } + got := map[string]string{} + for _, f := range res.Findings { + got[f.File+":"+itoa(f.Line)] = f.Props["current"] + } + want := map[string]string{"app/package.json:5": "24.22.0", "global.json:6": "8.0.415", "tools.json:3": "24.22.0"} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for k, v := range want { + if got[k] != v { + t.Errorf("%s: got %q, want %q (all: %v)", k, got[k], v, got) + } + } + for _, f := range res.Findings { + if f.File == "tools.json" { + continue + } + ch, _, err := plan(root, f) + if err != nil || ch == nil || ch.Edits[0].Line != f.Line { + t.Errorf("%s:%d: change %+v, err %v", f.File, f.Line, ch, err) + } + } +} + +// A byte-order mark is not part of line 1: the column does not count it. +func TestBOMColumn(t *testing.T) { + body := `{"volta":{"node":"24.22.0"}}` + root := t.TempDir() + write(t, root, map[string]string{"package.json": "\ufeff" + body}) + f := only(t, root, pins.RuleNode) + if want := itoa(strings.Index(body, "24.22.0") + 1); f.Props["column"] != want { + t.Errorf("column %q, want %q", f.Props["column"], want) + } + ch, _, err := plan(root, f) + if err != nil || ch == nil || ch.Edits[0].New[0] != "\ufeff"+`{"volta":{"node":"24.22.1"}}` { + t.Errorf("change %+v, err %v", ch, err) + } +} + +// A lockfileVersion 1 package-lock.json with no dependencies has nothing +// to read: it is not reported as not checked. +func TestLockfileV1Empty(t *testing.T) { + for _, body := range []string{`{"lockfileVersion": 1, "dependencies": {}}`, `{"lockfileVersion": 1}`} { + root := t.TempDir() + write(t, root, map[string]string{"package-lock.json": body}) + if res, err := pins.Scan(context.Background(), root, nil, pins.Options{}); err != nil || len(res.Skips) != 0 { + t.Errorf("%s: %v %+v", body, err, res.Skips) + } + } +} + +func TestScrub(t *testing.T) { + for _, c := range []struct{ root, in, want string }{ + {"/w/repo", "lstat /w/repo/svc: no such file or directory", "lstat svc: no such file or directory"}, + {"/w/repo/", "open /w/repo/a.json: denied", "open a.json: denied"}, + {"/w/repo", "the root /w/repo is gone", "the root . is gone"}, + {".", "lstat svc: x", "lstat svc: x"}, + } { + if got := pins.Scrub(c.root, c.in); got != c.want { + t.Errorf("Scrub(%q, %q) = %q, want %q", c.root, c.in, got, c.want) + } + } +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index eda6d28..8c58a08 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -46,9 +46,11 @@ var planRules = map[string]bool{RuleNode: true, RuleDotnet: true, RuleBun: true, // was not checked, or cannot be checked again now, declines with "rescan to // confirm": the file is unreadable, too large or does not parse; its line // was not checked (a skip on that line); its line pins another release -// without the fix; or it has no line any more (line 0, or past the end of -// the file) and the file still pins a release of that rule without the fix -// or has a skip on any line. +// without the fix; it has no line any more (line 0, or past the end of the +// file) and the file still pins a release of that rule without the fix or +// has a skip on any line; or it is an image pin (or a finding without +// props), no resolved image is left on its line, and the file has a skip +// on another line, where the image may have moved. func Plan(ctx context.Context, root, file string, line int, rule string, props map[string]string) (*Change, bool, error) { // The path as the scan writes it: ./Dockerfile and svc/../Dockerfile // are Dockerfile, or the pins found in it would not match. @@ -85,7 +87,7 @@ func Plan(ctx context.Context, root, file string, line int, rule string, props m return nil, false, err } if !found { - if err := unchecked(root, before, file, line, rule, now); err != nil { + if err := unchecked(root, before, file, line, rule, props, now); err != nil { return nil, false, err } return nil, true, nil @@ -195,7 +197,7 @@ func scanPins(ctx context.Context, root string, files []string, opts Options) (* // a file that did not get shorter (it looks like a second pin that was // always there), and a path that never held the pin (a wrong path, a // renamed file, a file no reader handles), which looks like a deleted file. -func unchecked(root string, s *scanner, file string, line int, rule string, content []byte) error { +func unchecked(root string, s *scanner, file string, line int, rule string, props map[string]string, content []byte) error { n := strings.Count(string(content), "\n") if len(content) > 0 && content[len(content)-1] != '\n' { n++ @@ -203,6 +205,13 @@ func unchecked(root string, s *scanner, file string, line int, rule string, cont // Without its line (line 0, or a line past the end of a file that got // shorter) the finding may be anywhere in the file now. lost := line == 0 || line > n + // An image pin can move to another line and become a reference the + // scan cannot judge (FROM node:${V} with no default for V, a digest + // only). Unless a resolved image still sits on its own line, a skip + // elsewhere in the file may be it. Without props the finding may be + // an image pin. + image := props["image"] != "" || strings.HasSuffix(props["source"], "-image") || props["source"] == "" + moved := image && !s.refLines[lineKey(file, line)] for _, sk := range s.skips { switch { case sk.Line == 0: @@ -214,6 +223,8 @@ func unchecked(root string, s *scanner, file string, line int, rule string, cont // digest only) was not checked. A skip on another line is // about another pin, which is reported on its own. return notChecked("line %d of %s was not checked: %s", sk.Line, sk.File, scrub(root, sk.Reason)) + case sk.File == file && moved: + return notChecked("line %d of %s holds no image now, and line %d was not checked (%s): the image may have moved there", line, file, sk.Line, scrub(root, sk.Reason)) } } for _, q := range s.pins { @@ -245,16 +256,15 @@ func errText(err error) string { return err.Error() } -// scrub removes the checkout's absolute path from a reason. +// scrub removes the checkout's absolute path from a reason. File system +// errors name joined, so cleaned, paths. func scrub(root, s string) string { - for _, r := range []string{root, filepath.Clean(root)} { - if r == "" || r == "." { - continue - } - s = strings.ReplaceAll(s, r+string(filepath.Separator), "") - s = strings.ReplaceAll(s, r, ".") + r := filepath.Clean(root) + if r == "." || r == string(filepath.Separator) { + return s } - return s + s = strings.ReplaceAll(s, r+string(filepath.Separator), "") + return strings.ReplaceAll(s, r, ".") } // choose finds the pin a finding names. found is false when the file no From 10be3b5f4f339b5b727251db7bee032a3c6d4fdd Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 07:22:46 +0000 Subject: [PATCH 4/8] brotli: third review round of the not-checked change - A pin that moved off its line and became a value the scan cannot judge read as already fixed when any resolved image landed on its old line: an ARG with no default, a digest-only FROM pushed down, reordered Compose services, Kubernetes containers or GitLab jobs with an unset tag, a distroless line image from a variable, and setup-node under an unresolved matrix or env value. The scan now records, for every value of a rule it judges, its file, line and rule, whatever the verdict; a finding whose own line holds no judged value of its rule is held back by a skip anywhere in its file. This applies to every finding, not only image pins. The cost: a pin replaced by another line, in a file with any skip, asks for a rescan. - The text patterns read a JSON file with its comments blanked only when the result is valid JSON. Single-quoted strings (which the comment reader does not follow) and an unterminated /* kept real pins out of sight; such files are read as written again, and an unterminated /* is left alone. - The byte-order-mark column fix reads line 1 as the column was found, so it covers files read only as image files (Dockerfile-prod). - scrub leaves a relative root alone, and replaces an absolute one only where it is a whole path (not inside gcr.io/app/web or /application). - Tests for each, and for the surviving mutants: a column on line 1 without a byte-order mark and on a later line with one, a lockfileVersion 1 "dependencies" of another shape, scrub with "/" and ".". Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/brotlipin.go | 63 ++++++---- detectors/brotli/internal/pins/deps.go | 4 +- .../brotli/internal/pins/notchecked_test.go | 108 ++++++++++++++++++ detectors/brotli/internal/pins/plan.go | 59 +++++++--- detectors/brotli/internal/pins/sources.go | 4 + 5 files changed, 200 insertions(+), 38 deletions(-) diff --git a/detectors/brotli/internal/pins/brotlipin.go b/detectors/brotli/internal/pins/brotlipin.go index 575488b..5a9a281 100644 --- a/detectors/brotli/internal/pins/brotlipin.go +++ b/detectors/brotli/internal/pins/brotlipin.go @@ -316,15 +316,25 @@ type scanner struct { files int truncated bool lines map[string][]string // files split once per scan, for columns - // refLines holds file\x00line for every image reference the scan - // resolved, judged or not. - refLines map[string]bool - // bom holds the files that start with a byte-order mark, which is not - // part of line 1's columns. - bom map[string]bool + // judged holds file, line and rule for every value of a rule the scan + // judged there, whatever the verdict: what a plan finds on a finding's + // line when the pin is gone. + judged map[judgedKey]bool } -func lineKey(file string, line int) string { return fmt.Sprint(file, "\x00", line) } +type judgedKey struct { + file string + line int + rule string +} + +// judge records that line of file holds a value of rule the scan judged. +func (s *scanner) judge(file string, line int, rule string) { + if s.judged == nil { + s.judged = map[judgedKey]bool{} + } + s.judged[judgedKey{file, line, rule}] = true +} // exists reports a regular file in the repository (or the overlay). func (s *scanner) exists(rel string) bool { @@ -361,6 +371,7 @@ func (s *scanner) fileLines(rel string) []string { } func (s *scanner) add(p pin) { + s.judge(p.file, p.line, p.prod.rule()) if p.j.vd == bump || p.j.vd == noFixLine { s.pins = append(s.pins, p) } @@ -391,7 +402,7 @@ func (s *scanner) result() Result { } seen[k] = true f := p.finding() - if c, err := strconv.Atoi(f.Props["column"]); err == nil && p.line == 1 && s.bom[p.file] && c > len(utf8BOM) { + if c, err := strconv.Atoi(f.Props["column"]); err == nil && p.line == 1 && c > len(utf8BOM) && s.startsWithBOM(p.file) { // The byte-order mark is not text on the line. f.Props["column"] = strconv.Itoa(c - len(utf8BOM)) } @@ -592,14 +603,16 @@ func (s *scanner) parseFile(rel string, k fileKind) { } // The JSON readers see comments and a byte-order mark as spaces, so // every line and column stays where it is in the file. - if bytes.HasPrefix(b, utf8BOM) { - if s.bom == nil { - s.bom = map[string]bool{} - } - s.bom[rel] = true - } + text := b if isJSON(rel) { b = jsonText(b) + // The text patterns read the file as the JSON readers do, so a + // value inside a comment is not a pin, but only when that is JSON: + // in looser text (single quotes, an unterminated comment) what + // looks like a comment may not be one. + if json.Valid(b) { + text = b + } } switch k { case kindNvmrc: @@ -628,7 +641,7 @@ func (s *scanner) parseFile(rel string, k fileKind) { s.netlify(rel, b) } if textCandidate(rel) { - s.textPatterns(rel, b) // in JSON, a value inside a comment is not a pin + s.textPatterns(rel, text) } if dependencyFile(rel) { s.dependencies(rel, b) @@ -637,6 +650,7 @@ func (s *scanner) parseFile(rel string, k fileKind) { // textPin judges value written at byte col of line and adds the pin. func (s *scanner) textPin(prod product, source, desc, rel string, line, col int, value string) { + s.judge(rel, line, prod.rule()) j := judgeValue(prod, value, false) if j.vd == notJudged { return @@ -891,10 +905,6 @@ func (s *scanner) images(files []string) error { s.skips = append(s.skips, Skip{File: k.File, Line: k.Line, Reason: clean(k.Reason, 200)}) } for _, r := range rs { - if s.refLines == nil { - s.refLines = map[string]bool{} - } - s.refLines[lineKey(r.File, r.Line)] = true s.judgeImage(r) } return nil @@ -915,6 +925,7 @@ func (s *scanner) judgeImage(r refs.Ref) { s.skips = append(s.skips, Skip{File: r.File, Line: r.Line, Reason: clean(fmt.Sprintf("%s is pinned by digest only; its %s release is checked by the brotli-images scan, which reads the image", r.Image, prod.name()), 300)}) return } + s.judge(r.File, r.Line, prod.rule()) // A tag@digest pin is judged by its tag; its fix moves both. j := judgeValue(prod, ref.Tag, true) if j.vd == notJudged || j.current == "" { @@ -944,6 +955,7 @@ func (s *scanner) judgeLineImage(r refs.Ref, ref reference, desc string) { if m == nil { continue } + s.judge(r.File, r.Line, lr.prod.rule()) j := judgeLine(lr.prod, parsed{parts: []int{atoi(m[1])}, text: m[1]}) if j.vd != noFixLine { return @@ -1073,6 +1085,13 @@ func ImageUpgrade(image string) (string, string, bool) { var utf8BOM = []byte("\xef\xbb\xbf") +// startsWithBOM reports a file whose line 1 starts with a byte-order mark, +// read as the column was found. +func (s *scanner) startsWithBOM(rel string) bool { + ls := s.fileLines(rel) + return len(ls) > 0 && strings.HasPrefix(ls[0], string(utf8BOM)) +} + func isJSON(rel string) bool { return strings.HasSuffix(strings.ToLower(rel), ".json") || path.Base(rel) == "Pipfile.lock" } @@ -1115,10 +1134,10 @@ func jsonText(b []byte) []byte { i += e - 1 case '*': e := bytes.Index(out[i+2:], []byte("*/")) - end := len(out) - if e >= 0 { - end = i + 2 + e + 2 + if e < 0 { + return out // not a comment that ends: left as written } + end := i + 2 + e + 2 blank(i, end) i = end - 1 } diff --git a/detectors/brotli/internal/pins/deps.go b/detectors/brotli/internal/pins/deps.go index bbe0e27..ad4c0ef 100644 --- a/detectors/brotli/internal/pins/deps.go +++ b/detectors/brotli/internal/pins/deps.go @@ -169,6 +169,7 @@ func (s *scanner) addDep(d depPin) { if !ok { return } + s.judge(d.file, d.line, RuleDependency) affected, fixed := depVerdict(b, d.version) if !affected { return @@ -567,11 +568,12 @@ func (s *scanner) nugetLock(rel string, b []byte) { if !runtimePackRe.MatchString(name) || p.Resolved == "" { continue } + line, _, _ := locateJSON(b, "", name, "") + s.judge(rel, max(line, 1), RuleDotnet) j := judgeValue(dotnet, p.Resolved, false) if j.vd != bump && j.vd != noFixLine { continue } - line, _, _ := locateJSON(b, "", name, "") s.add(pin{prod: dotnet, source: "runtime-pack-lock", desc: "packages.lock.json " + name, file: rel, line: max(line, 1), editFile: rel, editLine: max(line, 1), col: -1, j: j, notes: lockCommand("NuGet", name, j.fixed, rel)}) } diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go index 274837b..60eefcf 100644 --- a/detectors/brotli/internal/pins/notchecked_test.go +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -546,3 +546,111 @@ func TestScrub(t *testing.T) { } } } + +// A pin that moved to another line and became a value the scan cannot +// judge is not fixed, even when another value lands on its old line: only +// a value of the finding's own rule judged on its line clears it. +func TestPlanMovedOntoAnotherValue(t *testing.T) { + digest := "node@sha256:" + strings.Repeat("a", 64) + k8s := func(first, second string) string { + return "apiVersion: v1\nkind: Pod\nmetadata:\n name: p\nspec:\n containers:\n - name: " + first + "\n - name: " + second + "\n" + } + wf := "on: push\njobs:\n test:\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: 24.22.0\n" + for _, c := range []struct{ what, file, was, now string }{ + {"an ARG with no default, another image on the old line", "Dockerfile", + "FROM golang:1.25 AS build\nFROM node:24.22.0\n", "ARG NODE_VERSION\nFROM golang:1.25 AS build\nFROM node:${NODE_VERSION}\n"}, + {"a digest-only FROM pushed down two lines", "Dockerfile", + "FROM golang:1.25 AS build\nFROM node:24.22.0\n", "FROM alpine:3.22 AS a\nFROM golang:1.25 AS build\nRUN true\nFROM " + digest + "\n"}, + {"Compose services reordered, the tag now unset", "compose.yaml", + "services:\n web:\n image: node:24.22.0\n db:\n image: postgres:16\n", "services:\n db:\n image: postgres:16\n web:\n image: node:${NODE_TAG}\n"}, + {"Kubernetes containers reordered, the tag now $(TAG)", "pod.yaml", + k8s("a\n image: node:24.22.0", "b\n image: redis:7"), k8s("b\n image: redis:7", "a\n image: node:$(TAG)")}, + {"GitLab jobs reordered, the tag now $NODE_TAG", ".gitlab-ci.yml", + "build:\n image: node:24.22.0\n script: [x]\nlint:\n image: python:3.13\n script: [y]\n", "lint:\n image: python:3.13\n script: [y]\nbuild:\n image: node:$NODE_TAG\n script: [x]\n"}, + {"a distroless line image now built from a variable", "Dockerfile", + "FROM golang:1.25 AS b\nFROM gcr.io/distroless/nodejs20-debian12\n", "ARG V\nFROM golang:1.25 AS b\nFROM gcr.io/distroless/nodejs${V}-debian12\n"}, + {"setup-node under a matrix the scan cannot resolve", ".github/workflows/ci.yml", + wf, "on: push\njobs:\n test:\n strategy:\n matrix: ${{ fromJSON(needs.x.outputs.m) }}\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ matrix.node }}\n"}, + {"setup-node from an env value that is not set", ".github/workflows/ci.yml", + wf, "on: push\njobs:\n test:\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ env.NODE_VERSION }}\n"}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.was}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{c.file: c.now}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Skips) == 0 { + t.Errorf("%s: the rewrite is not a skip: %v %+v", c.what, err, res) + continue + } + ch, already, err := plan(root, f) + mustDecline(t, c.what, ch, already, err) + } +} + +// In a JSON file that is not strict JSON (single quotes, an unterminated +// comment), the text patterns read the file as written: what the comment +// reader cannot follow is not taken as a comment. +func TestTextPatternsInLooseJSON(t *testing.T) { + for _, c := range []struct{ file, body, current string }{ + {"tools.json", "{'url': 'https://nodejs.org/dist/v24.22.0/node.tar.gz'}\n", "24.22.0"}, + {"tasks.json", "{ files: ['src/*.ts'], \"setup\": \"nvm install 24.22.0\" }\n", "24.22.0"}, + {"cdk.json", "{\n 'context': {\n 'install': 'curl -fsSL https://deb.nodesource.com/setup_20.x | bash'\n }\n}\n", "20"}, + {"loose.json", "{ /* open\n\"setup\": \"nvm install 24.22.0\" }\n", "24.22.0"}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + f := only(t, root, pins.RuleNode) + if f.Props["current"] != c.current { + t.Errorf("%s: %+v", c.file, f) + } + } +} + +// The column counts no byte-order mark, and only on line 1: a file without +// one keeps every column, and a later line of a file with one too. A +// Dockerfile-prod is read only as an image file, and is no exception. +func TestColumnsAndBOM(t *testing.T) { + for _, c := range []struct{ file, body, value string }{ + {"package.json", `{"volta":{"node":"24.22.0"}}`, `{"volta":{"node":"24.22.0"}}`}, + {"Dockerfile-prod", "\ufeffFROM node:24.22.0\n", "FROM node:24.22.0"}, + {"Dockerfile_prod", "\ufeffFROM node:24.22.0\n", "FROM node:24.22.0"}, + {"svc/package.json", "\ufeff{\n \"volta\": {\n \"node\": \"24.22.0\"\n }\n}\n", ` "node": "24.22.0"`}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + f := only(t, root, pins.RuleNode) + if want := itoa(strings.Index(c.value, "24.22.0") + 1); f.Props["column"] != want { + t.Errorf("%s line %d: column %q, want %q", c.file, f.Line, f.Props["column"], want) + } + } +} + +// A lockfileVersion 1 "dependencies" of another shape is not checked, and +// says so. +func TestLockfileV1DependenciesShape(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{"package-lock.json": `{"lockfileVersion": 1, "dependencies": [1]}`}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 1 || !strings.Contains(res.Skips[0].Reason, "dependencies: not the expected shape") { + t.Errorf("%v %+v", err, res.Skips) + } +} + +// scrub removes only an absolute checkout path, and only where it is a +// whole path: a relative root, or the root's name inside another path or +// word, is left alone. +func TestScrubBoundaries(t *testing.T) { + for _, c := range []struct{ root, in, want string }{ + {"/", "open /a.json: denied", "open /a.json: denied"}, + {".", "open ./a.json: denied", "open ./a.json: denied"}, + {"repo", "open repo/a.json: the repository is gone", "open repo/a.json: the repository is gone"}, + {"/app", "gcr.io/app/web is pinned by digest only", "gcr.io/app/web is pinned by digest only"}, + {"/app", "lstat /app/svc: x; /application is not /app", "lstat svc: x; /application is not ."}, + {"/app", `"/app/a.json" is not read`, `"a.json" is not read`}, + } { + if got := pins.Scrub(c.root, c.in); got != c.want { + t.Errorf("Scrub(%q, %q) = %q, want %q", c.root, c.in, got, c.want) + } + } +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index 8c58a08..67e4f59 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -87,7 +87,7 @@ func Plan(ctx context.Context, root, file string, line int, rule string, props m return nil, false, err } if !found { - if err := unchecked(root, before, file, line, rule, props, now); err != nil { + if err := unchecked(root, before, file, line, rule, now); err != nil { return nil, false, err } return nil, true, nil @@ -197,7 +197,7 @@ func scanPins(ctx context.Context, root string, files []string, opts Options) (* // a file that did not get shorter (it looks like a second pin that was // always there), and a path that never held the pin (a wrong path, a // renamed file, a file no reader handles), which looks like a deleted file. -func unchecked(root string, s *scanner, file string, line int, rule string, props map[string]string, content []byte) error { +func unchecked(root string, s *scanner, file string, line int, rule string, content []byte) error { n := strings.Count(string(content), "\n") if len(content) > 0 && content[len(content)-1] != '\n' { n++ @@ -205,13 +205,13 @@ func unchecked(root string, s *scanner, file string, line int, rule string, prop // Without its line (line 0, or a line past the end of a file that got // shorter) the finding may be anywhere in the file now. lost := line == 0 || line > n - // An image pin can move to another line and become a reference the - // scan cannot judge (FROM node:${V} with no default for V, a digest - // only). Unless a resolved image still sits on its own line, a skip - // elsewhere in the file may be it. Without props the finding may be - // an image pin. - image := props["image"] != "" || strings.HasSuffix(props["source"], "-image") || props["source"] == "" - moved := image && !s.refLines[lineKey(file, line)] + // A pin can move to another line and become a value the scan cannot + // judge (FROM node:${V} with no default for V, a digest only, a + // setup-node version from a matrix it cannot resolve). Unless the + // scan judged a value of the finding's rule on its own line, a skip + // elsewhere in the file may be it. The cost: a pin replaced by + // another line in a file with any skip asks for a rescan. + moved := !s.judged[judgedKey{file, line, rule}] for _, sk := range s.skips { switch { case sk.Line == 0: @@ -224,7 +224,7 @@ func unchecked(root string, s *scanner, file string, line int, rule string, prop // about another pin, which is reported on its own. return notChecked("line %d of %s was not checked: %s", sk.Line, sk.File, scrub(root, sk.Reason)) case sk.File == file && moved: - return notChecked("line %d of %s holds no image now, and line %d was not checked (%s): the image may have moved there", line, file, sk.Line, scrub(root, sk.Reason)) + return notChecked("line %d of %s holds no value of this kind now, and line %d was not checked (%s): the pin may have moved there", line, file, sk.Line, scrub(root, sk.Reason)) } } for _, q := range s.pins { @@ -256,15 +256,44 @@ func errText(err error) string { return err.Error() } -// scrub removes the checkout's absolute path from a reason. File system -// errors name joined, so cleaned, paths. +// scrub removes the checkout's absolute path from a reason where it is a +// whole path: root/x becomes x and root alone becomes ".". File system +// errors name joined, so cleaned, paths. A relative root (repo, .) is left +// alone: its name is also a word, and it says nothing about the machine. func scrub(root, s string) string { r := filepath.Clean(root) - if r == "." || r == string(filepath.Separator) { + if !filepath.IsAbs(r) || r == string(filepath.Separator) { return s } - s = strings.ReplaceAll(s, r+string(filepath.Separator), "") - return strings.ReplaceAll(s, r, ".") + sep := string(filepath.Separator) + var b strings.Builder + for { + i := strings.Index(s, r) + if i < 0 { + b.WriteString(s) + return b.String() + } + j := i + len(r) + switch { + case i > 0 && pathByte(s[i-1]): + // Inside another path or word (gcr.io/app/web): kept. + b.WriteString(s[:j]) + case strings.HasPrefix(s[j:], sep): + b.WriteString(s[:i]) + j += len(sep) + case j < len(s) && pathByte(s[j]): + b.WriteString(s[:j]) // a longer name (/application) + default: + b.WriteString(s[:i] + ".") + } + s = s[j:] + } +} + +// pathByte reports a byte that continues a path or a name. +func pathByte(c byte) bool { + return c == '/' || c == '\\' || c == '.' || c == '_' || c == '-' || c == '~' || c == '+' || c == '@' || + '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' } // choose finds the pin a finding names. found is false when the file no diff --git a/detectors/brotli/internal/pins/sources.go b/detectors/brotli/internal/pins/sources.go index 54a5b9e..ecb0f7a 100644 --- a/detectors/brotli/internal/pins/sources.go +++ b/detectors/brotli/internal/pins/sources.go @@ -78,6 +78,7 @@ func (s *scanner) nodePin(prod product, source, desc, rel string, lines []string // addJudged adds a judged value written at col of line (col -1: not // editable verbatim). func (s *scanner) addJudged(prod product, source, desc, rel string, line, col int, value string, j judgement) { + s.judge(rel, line, prod.rule()) if j.vd == notJudged { return } @@ -327,6 +328,7 @@ func (s *scanner) dotnetProject(rel string, b []byte) { if strings.HasPrefix(t, "netcoreapp") { major = 3 // netcoreapp1.x to 3.1: long out of support } + s.judge(rel, i+1, RuleDotnet) j := judgeLine(dotnet, parsed{parts: []int{major}, text: t}) if j.vd == noFixLine { s.add(pin{prod: dotnet, source: "target-framework", desc: path.Base(rel) + " TargetFramework", file: rel, line: i + 1, @@ -514,6 +516,7 @@ func (s *scanner) textPatterns(rel string, b []byte) { v := l[m[2]:m[3]] desc := fmt.Sprintf("%s (%s)", tp.desc, path.Base(rel)) if tp.line { + s.judge(rel, i+1, tp.prod.rule()) j := judgeLine(tp.prod, parsed{parts: []int{atoi(v)}, text: v}) if j.vd != noFixLine { continue @@ -550,6 +553,7 @@ func (s *scanner) textPatterns(rel string, b []byte) { if uses > 1 { col, notes = -1, "the release is written more than once in the command (for example a URL and its file name); change every one" } + s.judge(rel, i+1, tp.prod.rule()) j := judgeValue(tp.prod, v, false) if j.vd == notJudged { continue From f26f93d75de3db42faf62181ab91cf7daa24ea75 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 08:37:12 +0000 Subject: [PATCH 5/8] brotli: fourth review round of the not-checked change - The judged record is keyed by source as well as rule, and compared with the finding's props["source"] (any source without props). A .NET SDK image where the aspnet image was, or an ARG NODE_VERSION where the node image was, no longer clears a pin that moved and became unresolved. - Values the scan could not judge (a range, an expression) are no longer recorded as judged: textPin, addJudged and the text patterns record only through add(). A range landing on the pin's line no longer clears it. - A pin changed in place to an expression is reported as not checked on its line instead of dropped: setup-node/bun/dotnet inputs and the env and matrix values they read written as ${{ ... }}, Azure versionSpec $(var), CircleCI orb << parameters >> and runtime images tagged with a << parameter >>, .nvmrc-style and mise/.tool-versions values with ${VAR}, and ENV/ARG/export NODE_VERSION (BUN, DOTNET, ASPNET) set from a variable the file does not itself set to a release. - The third case Plan cannot tell from a fix (a same-rule, same-source value landing on the old line of a pin that became unresolved) is documented beside the other two. - Tests for each, and for the survivors: a line image and a NodeSource line fixed in place with a skip elsewhere, a .NET rule through the moved logic, a node pin whose line now holds a .NET image, a judged value on the next line, and a skip beside a judged value on the line. Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/brotlipin.go | 40 +++-- detectors/brotli/internal/pins/deps.go | 4 +- .../brotli/internal/pins/notchecked_test.go | 149 ++++++++++++++++++ detectors/brotli/internal/pins/plan.go | 23 ++- detectors/brotli/internal/pins/sources.go | 42 ++++- 5 files changed, 231 insertions(+), 27 deletions(-) diff --git a/detectors/brotli/internal/pins/brotlipin.go b/detectors/brotli/internal/pins/brotlipin.go index 5a9a281..2b0fa12 100644 --- a/detectors/brotli/internal/pins/brotlipin.go +++ b/detectors/brotli/internal/pins/brotlipin.go @@ -323,17 +323,19 @@ type scanner struct { } type judgedKey struct { - file string - line int - rule string + file string + line int + rule, source string } -// judge records that line of file holds a value of rule the scan judged. -func (s *scanner) judge(file string, line int, rule string) { +// judge records that line of file holds a value of rule from source the +// scan judged, under its source and under "" (a finding without props). +func (s *scanner) judge(file string, line int, rule, source string) { if s.judged == nil { s.judged = map[judgedKey]bool{} } - s.judged[judgedKey{file, line, rule}] = true + s.judged[judgedKey{file, line, rule, source}] = true + s.judged[judgedKey{file, line, rule, ""}] = true } // exists reports a regular file in the repository (or the overlay). @@ -371,7 +373,7 @@ func (s *scanner) fileLines(rel string) []string { } func (s *scanner) add(p pin) { - s.judge(p.file, p.line, p.prod.rule()) + s.judge(p.file, p.line, p.prod.rule(), p.source) if p.j.vd == bump || p.j.vd == noFixLine { s.pins = append(s.pins, p) } @@ -650,9 +652,9 @@ func (s *scanner) parseFile(rel string, k fileKind) { // textPin judges value written at byte col of line and adds the pin. func (s *scanner) textPin(prod product, source, desc, rel string, line, col int, value string) { - s.judge(rel, line, prod.rule()) j := judgeValue(prod, value, false) if j.vd == notJudged { + s.expression(rel, line, desc, value) return } at := col @@ -910,6 +912,22 @@ func (s *scanner) images(files []string) error { return nil } +// imageSource is Props["source"] of an official runtime image's pin. +var imageSource = map[product]string{node: "node-image", dotnet: "dotnet-image", bun: "bun-image", dotnetSDK: "dotnet-sdk-image"} + +// exprRef matches a value written as a reference the scan does not +// resolve: ${{ ... }}, ${VAR}, $VAR, $(VAR), << parameters.x >>. +var exprRef = regexp.MustCompile(`\$\{\{|\$\{[A-Za-z_]|\$[A-Za-z_]|\$\(|<<`) + +// expression records a value written as an expression as not checked: a +// pin changed to one in place is not fixed, and is not known to be. +func (s *scanner) expression(rel string, line int, desc, value string) { + if line < 1 || !exprRef.MatchString(value) { + return + } + s.skips = append(s.skips, Skip{File: rel, Line: line, Reason: clean(fmt.Sprintf("%s is %s, an expression the scan does not resolve; check the release it selects by hand", desc, value), 300)}) +} + func (s *scanner) judgeImage(r refs.Ref) { ref, err := parseReference(r.Image) if err != nil { @@ -925,13 +943,13 @@ func (s *scanner) judgeImage(r refs.Ref) { s.skips = append(s.skips, Skip{File: r.File, Line: r.Line, Reason: clean(fmt.Sprintf("%s is pinned by digest only; its %s release is checked by the brotli-images scan, which reads the image", r.Image, prod.name()), 300)}) return } - s.judge(r.File, r.Line, prod.rule()) + s.judge(r.File, r.Line, prod.rule(), imageSource[prod]) // A tag@digest pin is judged by its tag; its fix moves both. j := judgeValue(prod, ref.Tag, true) if j.vd == notJudged || j.current == "" { return } - p := pin{prod: prod, source: map[product]string{node: "node-image", dotnet: "dotnet-image", bun: "bun-image", dotnetSDK: "dotnet-sdk-image"}[prod], desc: desc, + p := pin{prod: prod, source: imageSource[prod], desc: desc, file: r.File, line: r.Line, editFile: r.EditFile, editLine: r.EditLine, col: -1, j: j, image: r.Image} if p.editFile == "" { p.editFile, p.editLine = r.File, r.Line @@ -955,7 +973,7 @@ func (s *scanner) judgeLineImage(r refs.Ref, ref reference, desc string) { if m == nil { continue } - s.judge(r.File, r.Line, lr.prod.rule()) + s.judge(r.File, r.Line, lr.prod.rule(), lr.source) j := judgeLine(lr.prod, parsed{parts: []int{atoi(m[1])}, text: m[1]}) if j.vd != noFixLine { return diff --git a/detectors/brotli/internal/pins/deps.go b/detectors/brotli/internal/pins/deps.go index ad4c0ef..27c4f18 100644 --- a/detectors/brotli/internal/pins/deps.go +++ b/detectors/brotli/internal/pins/deps.go @@ -169,7 +169,7 @@ func (s *scanner) addDep(d depPin) { if !ok { return } - s.judge(d.file, d.line, RuleDependency) + s.judge(d.file, d.line, RuleDependency, "dependency") affected, fixed := depVerdict(b, d.version) if !affected { return @@ -569,7 +569,7 @@ func (s *scanner) nugetLock(rel string, b []byte) { continue } line, _, _ := locateJSON(b, "", name, "") - s.judge(rel, max(line, 1), RuleDotnet) + s.judge(rel, max(line, 1), RuleDotnet, "runtime-pack-lock") j := judgeValue(dotnet, p.Resolved, false) if j.vd != bump && j.vd != noFixLine { continue diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go index 60eefcf..fd099aa 100644 --- a/detectors/brotli/internal/pins/notchecked_test.go +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -654,3 +654,152 @@ func TestScrubBoundaries(t *testing.T) { } } } + +// A value of the same rule but another source on the pin's old line (a +// .NET SDK image where the aspnet image was, an ARG NODE_VERSION where +// the node image was) is not the pin: a skip elsewhere still holds it. +func TestPlanSameRuleOtherSource(t *testing.T) { + for _, c := range []struct{ what, was, now string }{ + {"an SDK image on the aspnet image's line", + "FROM mcr.microsoft.com/dotnet/sdk:8.0.415 AS build\nFROM mcr.microsoft.com/dotnet/aspnet:8.0.32\n", + "ARG V\nFROM mcr.microsoft.com/dotnet/sdk:8.0.427 AS build\nFROM mcr.microsoft.com/dotnet/aspnet:${V}\n"}, + {"an ARG NODE_VERSION on the node image's line", + "FROM golang:1.25 AS b\nFROM node:24.22.0\n", + "FROM golang:1.25 AS b\nARG NODE_VERSION=24.22.1\nFROM ${BASE}\n"}, + } { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": c.was}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil { + t.Fatal(err) + } + var f *pins.Finding + for i := range res.Findings { + if res.Findings[i].Line == 2 { + f = &res.Findings[i] + } + } + if f == nil { + t.Fatalf("%s: %+v", c.what, res.Findings) + } + write(t, root, map[string]string{"Dockerfile": c.now}) + ch, already, err := plan(root, *f) + mustDecline(t, c.what, ch, already, err) + } +} + +// A value the scan could not judge (a range, an expression) on the pin's +// line is not a judged value there. +func TestPlanUnjudgedValueOnTheLine(t *testing.T) { + root := t.TempDir() + job := func(name, version string) string { + return " " + name + ":\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: " + version + "\n" + } + write(t, root, map[string]string{".github/workflows/ci.yml": "on: push\njobs:\n" + job("a", "24.22.0") + job("b", "'>=22 <25'")}) + f := only(t, root, pins.RuleNode) + if f.Line != 8 { + t.Fatalf("%+v", f) + } + write(t, root, map[string]string{".github/workflows/ci.yml": "on: push\njobs:\n" + job("b", "'>=22 <25'") + job("a", "${{ env.NODE_VERSION }}")}) + ch, already, err := plan(root, f) + mustDecline(t, "a range on the line, the pin now an unset env value", ch, already, err) +} + +// A pin changed in place to an expression the scan does not resolve is +// not checked, and is reported so: it never reads as fixed. +func TestExpressionInPlace(t *testing.T) { + setup := func(v string) string { + return "on: push\njobs:\n a:\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: " + v + "\n" + } + envWF := func(v string) string { + return "on: push\nenv:\n NODE_VERSION: " + v + "\njobs:\n a:\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ env.NODE_VERSION }}\n" + } + matrix := func(v string) string { + return "on: push\njobs:\n a:\n runs-on: x\n strategy:\n matrix:\n n: " + v + "\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ matrix.n }}\n" + } + circle := func(v string) string { + return "version: 2.1\njobs:\n build:\n docker:\n - image: cimg/node:" + v + "\n steps: [checkout]\n" + } + azure := func(v string) string { + return "steps:\n- task: NodeTool@0\n inputs:\n versionSpec: '" + v + "'\n" + } + for _, c := range []struct{ what, file, was, now string }{ + {"node-version from vars", ".github/workflows/ci.yml", setup("24.22.0"), setup("${{ vars.NODE }}")}, + {"node-version from inputs", ".github/workflows/ci.yml", setup("24.22.0"), setup("${{ inputs.node }}")}, + {"workflow env from vars", ".github/workflows/ci.yml", envWF("24.22.0"), envWF("${{ vars.X }}")}, + {"matrix from fromJSON", ".github/workflows/ci.yml", matrix("[24.22.0]"), matrix("${{ fromJSON(needs.x.outputs.m) }}")}, + {"CircleCI image parameter", ".circleci/config.yml", circle("24.22.0"), circle("<< parameters.tag >>")}, + {"Azure versionSpec variable", "azure-pipelines.yml", azure("24.22.0"), azure("$(nodeVersion)")}, + {".nvmrc variable", ".nvmrc", "24.22.0\n", "${NODE_VERSION}\n"}, + {"ENV from a build variable", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=24.22.0\n", "FROM debian:12\nENV NODE_VERSION=$BUILD_NODE\n"}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.was}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{c.file: c.now}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Skips) != 1 || res.Skips[0].Line != f.Line { + t.Errorf("%s: want one not-checked item on line %d: %v %+v", c.what, f.Line, err, res.Skips) + } + ch, already, err := plan(root, f) + mustDecline(t, c.what, ch, already, err) + } + // A variable the file sets to a release is read where it is set: the + // reference to it is no gap. + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "ARG NODE_VERSION=24.22.1\nFROM debian:12\nENV NODE_VERSION=$NODE_VERSION\n"}) + if res, err := pins.Scan(context.Background(), root, nil, pins.Options{}); err != nil || len(res.Skips) != 0 || len(res.Findings) != 0 { + t.Errorf("a set variable: %v %+v", err, res) + } +} + +// The judged record covers line images, line text patterns and every +// rule, keyed by the rule and the line it was found on. +func TestPlanJudgedRecord(t *testing.T) { + digest := "FROM node@sha256:" + strings.Repeat("a", 64) + for _, c := range []struct { + what, was, now string + line int + rule string + gone bool + }{ + {"a line image fixed in place", "FROM gcr.io/distroless/nodejs20-debian12 AS a\n" + digest + " AS b\n", + "FROM gcr.io/distroless/nodejs22-debian12 AS a\n" + digest + " AS b\n", 1, pins.RuleNode, true}, + {"a NodeSource line fixed in place", digest + "\nRUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash\n", + digest + "\nRUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash\n", 2, pins.RuleNode, true}, + {"a .NET image fixed in place", "FROM mcr.microsoft.com/dotnet/aspnet:8.0.32 AS a\n" + digest + " AS b\n", + "FROM mcr.microsoft.com/dotnet/aspnet:8.0.33 AS a\n" + digest + " AS b\n", 1, pins.RuleDotnet, true}, + {"a node pin whose line now holds a .NET image", "FROM node:24.22.0 AS a\n", + "FROM mcr.microsoft.com/dotnet/aspnet:8.0.33 AS a\nARG V\nFROM node:${V}\n", 1, pins.RuleNode, false}, + {"a judged value on the next line, not on the pin's", digest + " AS a\nFROM node:24.22.0 AS b\n", + digest + " AS a\nRUN true\nFROM node:24.22.1 AS b\n", 2, pins.RuleNode, false}, + } { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": c.was}) + f := only(t, root, c.rule) + if f.Line != c.line { + t.Fatalf("%s: %+v", c.what, f) + } + write(t, root, map[string]string{"Dockerfile": c.now}) + // With the finding's props and without them. + for _, props := range []map[string]string{f.Props, nil} { + ch, already, err := pins.Plan(context.Background(), root, f.File, f.Line, f.Rule, props) + if c.gone { + mustBeGone(t, c.what, ch, already, err) + } else { + mustDecline(t, c.what, ch, already, err) + } + } + } + // A skip on the pin's own line holds it even beside a judged value of + // its rule on that line. + root := t.TempDir() + pod := func(a, b string) string { + return "apiVersion: v1\nkind: Pod\nmetadata: {name: p}\nspec:\n containers: [{name: a, image: " + a + "}, {name: b, image: " + b + "}]\n" + } + write(t, root, map[string]string{"pod.yaml": pod("node:24.22.0", "redis:7")}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{"pod.yaml": pod("node:24.22.1", "node:$(TAG)")}) + ch, already, err := plan(root, f) + mustDecline(t, "a skip beside a judged value on the line", ch, already, err) +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index 67e4f59..947e1e4 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -87,7 +87,7 @@ func Plan(ctx context.Context, root, file string, line int, rule string, props m return nil, false, err } if !found { - if err := unchecked(root, before, file, line, rule, now); err != nil { + if err := unchecked(root, before, file, line, rule, props, now); err != nil { return nil, false, err } return nil, true, nil @@ -192,12 +192,19 @@ func scanPins(ctx context.Context, root string, files []string, opts Options) (* // unchecked explains why a pin the rescan did not find is still not known to // be gone, or returns nil when the rescan checked the place it was. // -// Two cases cannot be told apart from a fix, and read as gone: a pin that -// moved to another line and changed to another release without the fix, in -// a file that did not get shorter (it looks like a second pin that was -// always there), and a path that never held the pin (a wrong path, a -// renamed file, a file no reader handles), which looks like a deleted file. -func unchecked(root string, s *scanner, file string, line int, rule string, content []byte) error { +// Three cases cannot be told apart from a fix, and read as gone: +// +// - a pin that moved to another line and changed to another release +// without the fix, in a file that did not get shorter: it looks like a +// second pin that was always there; +// - a path that never held the pin (a wrong path, a renamed file, a file +// no reader handles): it looks like a deleted file; +// - a pin that moved and became a value the scan cannot judge, while a +// judged value of the same rule and source lands on its old line (two +// node stages, services or jobs reordered with the pinned one now +// unresolved; a flow-style Kubernetes list rewrapped): the value on the +// line looks like the pin, fixed in place. +func unchecked(root string, s *scanner, file string, line int, rule string, props map[string]string, content []byte) error { n := strings.Count(string(content), "\n") if len(content) > 0 && content[len(content)-1] != '\n' { n++ @@ -211,7 +218,7 @@ func unchecked(root string, s *scanner, file string, line int, rule string, cont // scan judged a value of the finding's rule on its own line, a skip // elsewhere in the file may be it. The cost: a pin replaced by // another line in a file with any skip asks for a rescan. - moved := !s.judged[judgedKey{file, line, rule}] + moved := !s.judged[judgedKey{file, line, rule, props["source"]}] for _, sk := range s.skips { switch { case sk.Line == 0: diff --git a/detectors/brotli/internal/pins/sources.go b/detectors/brotli/internal/pins/sources.go index ecb0f7a..0e05ba8 100644 --- a/detectors/brotli/internal/pins/sources.go +++ b/detectors/brotli/internal/pins/sources.go @@ -42,7 +42,11 @@ func mapGet(n *yaml.Node, key string) *yaml.Node { // nodePin judges a YAML scalar as a pin of prod at the scalar's own line. func (s *scanner) nodePin(prod product, source, desc, rel string, lines []string, v *yaml.Node, judge func(string) judgement) { - if v == nil || v.Kind != yaml.ScalarNode || strings.Contains(v.Value, "${{") || strings.Contains(v.Value, "$(") { + if v == nil || v.Kind != yaml.ScalarNode { + return + } + if strings.Contains(v.Value, "${{") || strings.Contains(v.Value, "$(") || strings.Contains(v.Value, "<<") { + s.expression(rel, v.Line, desc, strings.TrimSpace(v.Value)) return } if strings.Contains(v.Value, "\n") { @@ -78,8 +82,8 @@ func (s *scanner) nodePin(prod product, source, desc, rel string, lines []string // addJudged adds a judged value written at col of line (col -1: not // editable verbatim). func (s *scanner) addJudged(prod product, source, desc, rel string, line, col int, value string, j judgement) { - s.judge(rel, line, prod.rule()) if j.vd == notJudged { + s.expression(rel, line, desc, value) return } p := pin{prod: prod, source: source, desc: desc, file: rel, line: line, editFile: rel, editLine: line, col: -1, j: j} @@ -249,7 +253,16 @@ func (s *scanner) circleCI(rel string, b []byte) { if d := mapGet(n, "docker"); d != nil && d.Kind == yaml.SequenceNode { for _, e := range d.Content { img := mapGet(e, "image") - if img == nil || img.Kind != yaml.ScalarNode || strings.Contains(img.Value, "<<") { + if img == nil || img.Kind != yaml.ScalarNode { + continue + } + if k := strings.Index(img.Value, "<<"); k >= 0 { + // A runtime image whose tag is a parameter is not checked. + if ref, err := parseReference(strings.TrimSuffix(strings.TrimSpace(img.Value[:k]), ":")); err == nil { + if _, ok := imageRepos[ref.Registry+"/"+ref.Path]; ok { + s.expression(rel, img.Line, "CircleCI docker image", img.Value) + } + } continue } s.judgeImage(refs.Ref{File: rel, Line: img.Line, Column: img.Column, Kind: "circleci", Context: "docker image", @@ -328,7 +341,7 @@ func (s *scanner) dotnetProject(rel string, b []byte) { if strings.HasPrefix(t, "netcoreapp") { major = 3 // netcoreapp1.x to 3.1: long out of support } - s.judge(rel, i+1, RuleDotnet) + s.judge(rel, i+1, RuleDotnet, "target-framework") j := judgeLine(dotnet, parsed{parts: []int{major}, text: t}) if j.vd == noFixLine { s.add(pin{prod: dotnet, source: "target-framework", desc: path.Base(rel) + " TargetFramework", file: rel, line: i + 1, @@ -474,6 +487,13 @@ var textPatterns = []textPattern{ {re: regexp.MustCompile(`\bRuntime\.DOTNET_CORE_(\d)_\d\b`), prod: dotnet, source: "managed-runtime", desc: "AWS CDK Lambda runtime", line: true, sourceOnly: true, managed: true}, } +// versionVarExprRe finds a runtime version variable set from another +// variable (ENV NODE_VERSION=$BUILD_NODE): group 3 is the variable read. +var versionVarExprRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+(NODE_VERSION|BUN_VERSION|DOTNET_VERSION|ASPNET_VERSION|ASPNETCORE_VERSION)[= ]["']?(\$\{?([A-Za-z_][A-Za-z0-9_]*)[^\s"']*)`) + +// setVarRe finds a variable set to a release (ARG NODE_VERSION=24.22.0). +var setVarRe = regexp.MustCompile(`(?m)\b(?:ENV|ARG|export)\s+([A-Za-z_][A-Za-z0-9_]*)[= ]["']?v?[0-9]`) + // sha256Re finds a pinned checksum, which a download's version change would // also need. var sha256Re = regexp.MustCompile(`\b[0-9a-f]{64}\b`) @@ -501,10 +521,21 @@ func (s *scanner) textPatterns(rel string, b []byte) { src := isProgramSource(rel) lines := splitLines(b) spans := logicalSpans(lines) + // Variables the file sets to a release: a version variable that reads + // one is judged where it is set. + set := map[string]bool{} + for _, m := range setVarRe.FindAllSubmatch(b, -1) { + set[string(m[1])] = true + } for i, l := range lines { if i%4096 == 0 && s.ctx != nil && s.ctx.Err() != nil { return } + if !src { + if m := versionVarExprRe.FindStringSubmatch(l); m != nil && !set[m[3]] { + s.expression(rel, i+1, m[1], m[2]) + } + } for _, tp := range textPatterns { if tp.sourceOnly != src { continue @@ -516,7 +547,7 @@ func (s *scanner) textPatterns(rel string, b []byte) { v := l[m[2]:m[3]] desc := fmt.Sprintf("%s (%s)", tp.desc, path.Base(rel)) if tp.line { - s.judge(rel, i+1, tp.prod.rule()) + s.judge(rel, i+1, tp.prod.rule(), tp.source) j := judgeLine(tp.prod, parsed{parts: []int{atoi(v)}, text: v}) if j.vd != noFixLine { continue @@ -553,7 +584,6 @@ func (s *scanner) textPatterns(rel string, b []byte) { if uses > 1 { col, notes = -1, "the release is written more than once in the command (for example a URL and its file name); change every one" } - s.judge(rel, i+1, tp.prod.rule()) j := judgeValue(tp.prod, v, false) if j.vd == notJudged { continue From aa2170773e2b75c5db04d9aa9b5ec2941c1595c4 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 19 Nov 2026 01:53:13 +0000 Subject: [PATCH 6/8] brotli: in-place expressions never read as fixed; read version variables Follow-up to the approving confirmation review. - A release slot changed in place to a value the scan does not resolve never reads as already fixed: nvm/fnm/volta/asdf/mise with $V, a Node.js, NodeSource, Bun or dotnet-install download with ${V} or $(cat ...), and a YAML NODE_VERSION/BUN_VERSION: ${{ vars.N }} that no setup step reads. The scan records these slots without listing them as not checked (the shell sets them in ways it does not follow); Plan declines "rescan to confirm" when one sits on a finding's line. - ENV/ARG/export NODE_VERSION (BUN, DOTNET, ASPNET) set from another variable is judged by the value that variable was last set to above it in the file, and fixed there (ENV NODE_VERSION=$BUILD_NODE with ARG BUILD_NODE=24.22.0 is now a finding; it was missed). Reported once when the variable it reads is itself a pin or an image's ARG. A ${X:-d} default is judged when X is not set in the file. Only a variable the file never sets is listed as not checked. - Commented-out lines (# or //) are not read by the text patterns. - A library's TargetFramework on a supported .NET is recorded as judged. - Tests: fixed values recorded through add (a .tool-versions line beside a listed variable), the listing in addJudged (netlify.toml), ranges and floating values are not expressions, and the source each reader records matches its findings' source. Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/brotlipin.go | 28 ++- detectors/brotli/internal/pins/export_test.go | 18 ++ .../brotli/internal/pins/notchecked_test.go | 172 ++++++++++++++++++ detectors/brotli/internal/pins/plan.go | 6 + detectors/brotli/internal/pins/sources.go | 141 ++++++++++++-- 5 files changed, 353 insertions(+), 12 deletions(-) diff --git a/detectors/brotli/internal/pins/brotlipin.go b/detectors/brotli/internal/pins/brotlipin.go index 2b0fa12..8f2d965 100644 --- a/detectors/brotli/internal/pins/brotlipin.go +++ b/detectors/brotli/internal/pins/brotlipin.go @@ -154,6 +154,9 @@ type pin struct { // imgOff is where a line image's release line sits in image (0: in its // tag, found by the version text). imgOff int + // via: a version variable read from another variable the file sets + // (ENV NODE_VERSION=$BUILD_NODE), edited where that one is set. + via bool } // fixtureDirs name directories of test fixtures, which are inputs to tests, @@ -320,6 +323,19 @@ type scanner struct { // judged there, whatever the verdict: what a plan finds on a finding's // line when the pin is gone. judged map[judgedKey]bool + // exprAt holds file, line and rule ("" source) where a release slot + // holds a value the scan does not resolve (nvm install $V, a URL with + // ${V}): not listed as not checked, but never a fix in place. + exprAt map[judgedKey]bool +} + +// unresolved records that line of file sets a release of rule from a value +// the scan does not resolve. +func (s *scanner) unresolved(file string, line int, rule string) { + if s.exprAt == nil { + s.exprAt = map[judgedKey]bool{} + } + s.exprAt[judgedKey{file, line, rule, ""}] = true } type judgedKey struct { @@ -385,14 +401,23 @@ func (s *scanner) result() Result { // a text pattern on that same line would edit it without the image // verification. imageEdits := map[string]bool{} + textAt := map[string]bool{} for _, p := range s.pins { if p.image != "" { imageEdits[fmt.Sprint(p.editFile, "\x00", p.editLine)] = true + } else if !p.via { + textAt[fmt.Sprint(p.file, "\x00", p.line, "\x00", p.prod.rule())] = true } } seen := map[string]bool{} for _, p := range s.pins { - if p.image == "" && p.dep == nil && imageEdits[fmt.Sprint(p.file, "\x00", p.line)] { + if p.image == "" && p.dep == nil && imageEdits[fmt.Sprint(p.editFile, "\x00", p.editLine)] { + continue + } + // A variable read from another one that is itself a pin + // (ARG NODE_VERSION=24.22.0, then ENV NODE_VERSION=$NODE_VERSION) + // is reported once, where it is set. + if p.via && textAt[fmt.Sprint(p.editFile, "\x00", p.editLine, "\x00", p.prod.rule())] { continue } // One pin per place: a value two readers find (an env value that @@ -926,6 +951,7 @@ func (s *scanner) expression(rel string, line int, desc, value string) { return } s.skips = append(s.skips, Skip{File: rel, Line: line, Reason: clean(fmt.Sprintf("%s is %s, an expression the scan does not resolve; check the release it selects by hand", desc, value), 300)}) + s.unresolved(rel, line, "") } func (s *scanner) judgeImage(r refs.Ref) { diff --git a/detectors/brotli/internal/pins/export_test.go b/detectors/brotli/internal/pins/export_test.go index fe790dc..634ce26 100644 --- a/detectors/brotli/internal/pins/export_test.go +++ b/detectors/brotli/internal/pins/export_test.go @@ -1,4 +1,22 @@ package pins +import "context" + // Scrub is scrub, for the external tests. var Scrub = scrub + +// JudgedSources returns the sources the scan of file recorded as judged +// values of rule on line. +func JudgedSources(root, file string, line int, rule string) []string { + s, err := scanPins(context.Background(), root, []string{file}, Options{}) + if err != nil { + return nil + } + var out []string + for k := range s.judged { + if k.file == file && k.line == line && k.rule == rule && k.source != "" { + out = append(out, k.source) + } + } + return out +} diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go index fd099aa..713c0d5 100644 --- a/detectors/brotli/internal/pins/notchecked_test.go +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -803,3 +803,175 @@ func TestPlanJudgedRecord(t *testing.T) { ch, already, err := plan(root, f) mustDecline(t, "a skip beside a judged value on the line", ch, already, err) } + +// A pin changed in place to a value the scan does not resolve never reads +// as fixed, whether or not an ordinary scan lists it as not checked: a +// shell variable in a command or a URL is left to the plan, a version +// variable set from a build argument nobody sets is listed. +func TestInPlaceExpressionNeverFixed(t *testing.T) { + ctx := context.Background() + wf := func(v string) string { + return "on: push\nenv:\n NODE_VERSION: " + v + "\njobs:\n a:\n runs-on: x\n steps:\n - run: echo hi\n" + } + for _, c := range []struct { + what, file, was, now string + skips int + }{ + {"ENV from an ARG that holds a vulnerable release", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=24.22.0\n", "ARG OTHER=24.22.0\nENV NODE_VERSION=$OTHER\n", 0}, + {"ENV from an unset ARG, another ARG holding a release", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=24.22.0\n", "ARG NODE_VERSION=24.22.1\nENV NODE_VERSION=$OTHER\n", 1}, + {"nvm install $V", "install.sh", "nvm install 24.22.0\n", "nvm install $V\n", 0}, + {"a download URL with ${V}", "install.sh", "curl -fsSL https://nodejs.org/dist/v24.22.0/SHASUMS256.txt\n", "curl -fsSL https://nodejs.org/dist/v${V}/SHASUMS256.txt\n", 0}, + {"nvm install $(cat .nvmrc)", "install.sh", "nvm install 24.22.0\n", "nvm install $(cat .nvmrc)\n", 0}, + {"a workflow env value no setup step reads", ".github/workflows/ci.yml", wf("24.22.0"), wf("${{ vars.N }}"), 0}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.was}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{c.file: c.now}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Skips) != c.skips { + t.Errorf("%s: want %d not-checked items, got %v %+v", c.what, c.skips, err, res.Skips) + } + // Declined, or planned where the pin still is: never already fixed. + if _, already, err := plan(root, f); already { + t.Errorf("%s: already fixed (err %v)", c.what, err) + } else if _, ok := pins.IsDeclined(err); err != nil && !ok { + t.Errorf("%s: %v", c.what, err) + } + } +} + +// An ordinary scan reads what it can: an ENV set from an ARG in the same +// Dockerfile is judged by the ARG's value (and fixed there), a ${X:-d} +// default is judged, and a commented-out line is not read. +func TestVersionVariablesResolved(t *testing.T) { + ctx := context.Background() + scan := func(files map[string]string) pins.Result { + t.Helper() + root := t.TempDir() + write(t, root, files) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil { + t.Fatal(err) + } + return res + } + type want struct { + line int + current string + } + for _, c := range []struct { + what, file, body string + want []want + }{ + {"ENV from a fixed ARG", "Dockerfile", "ARG NODE_VERSION=24.22.1\nFROM debian:12\nENV NODE_VERSION=$NODE_VERSION\n", nil}, + {"ENV from a vulnerable ARG of another name", "Dockerfile", "ARG BUILD_NODE=24.22.0\nFROM debian:12\nENV NODE_VERSION=$BUILD_NODE\n", []want{{3, "24.22.0"}}}, + {"ENV from a vulnerable ARG of its name: one finding", "Dockerfile", "ARG NODE_VERSION=24.22.0\nFROM debian:12\nENV NODE_VERSION=${NODE_VERSION}\n", []want{{1, "24.22.0"}}}, + {"ENV from the ARG the FROM reads: the image finding", "Dockerfile", "ARG NODE_VERSION=24.22.0\nFROM node:${NODE_VERSION}\nENV NODE_VERSION=$NODE_VERSION\n", []want{{2, "24.22.0"}}}, + {"a fixed default", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=${NODE_VERSION:-24.22.1}\n", nil}, + {"a vulnerable default", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=${NODE_VERSION:-24.22.0}\n", []want{{2, "24.22.0"}}}, + {"commented-out lines", "Dockerfile", "# ENV NODE_VERSION=24.22.0\n# ENV NODE_VERSION=$UNSET\nFROM debian:12\n # RUN nvm install 18\n", nil}, + {"a commented-out CDK runtime", "stack.ts", "// runtime: Runtime.NODEJS_16_X,\nconst ok = 1\n", nil}, + {"a live CDK runtime", "stack.ts", "new Function(this, 'f', { runtime: Runtime.NODEJS_16_X })\n", []want{{1, "16"}}}, + } { + res := scan(map[string]string{c.file: c.body}) + if len(res.Skips) != 0 || len(res.Findings) != len(c.want) { + t.Errorf("%s: findings %+v skips %+v", c.what, res.Findings, res.Skips) + continue + } + for k, w := range c.want { + if f := res.Findings[k]; f.Line != w.line || f.Props["current"] != w.current { + t.Errorf("%s: %+v, want line %d current %s", c.what, f, w.line, w.current) + } + } + } + // The fix of an ENV that reads an ARG moves the ARG; of a default, the + // default. + for _, c := range []struct{ body, want string }{ + {"ARG BUILD_NODE=24.22.0\nFROM debian:12\nENV NODE_VERSION=$BUILD_NODE\n", "ARG BUILD_NODE=24.22.1"}, + {"FROM debian:12\nENV NODE_VERSION=${NODE_VERSION:-24.22.0}\n", "ENV NODE_VERSION=${NODE_VERSION:-24.22.1}"}, + } { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": c.body}) + f := only(t, root, pins.RuleNode) + ch, _, err := plan(root, f) + if err != nil || ch == nil || ch.Edits[0].New[0] != c.want { + t.Errorf("%q: change %+v, err %v", c.body, ch, err) + } + } +} + +// What a fixed value records, and where an unreadable value is listed. +func TestJudgedAndListed(t *testing.T) { + ctx := context.Background() + // A fixed .tool-versions line is judged (add records every verdict), + // and the variable on the next line is listed. + root := t.TempDir() + write(t, root, map[string]string{".tool-versions": "nodejs 24.22.0\nbun ${BUN}\n"}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{".tool-versions": "nodejs 24.22.1\nbun ${BUN}\n"}) + if res, err := pins.Scan(ctx, root, nil, pins.Options{}); err != nil || len(res.Skips) != 1 || res.Skips[0].Line != 2 { + t.Errorf(".tool-versions: %v %+v", err, res.Skips) + } + ch, already, err := plan(root, f) + mustBeGone(t, ".tool-versions fixed beside a variable", ch, already, err) + + // netlify.toml NODE_VERSION set from a variable is listed. + root = t.TempDir() + write(t, root, map[string]string{"netlify.toml": "[build.environment]\n NODE_VERSION = \"24.22.0\"\n"}) + f = only(t, root, pins.RuleNode) + write(t, root, map[string]string{"netlify.toml": "[build.environment]\n NODE_VERSION = \"$NODE\"\n"}) + if res, err := pins.Scan(ctx, root, nil, pins.Options{}); err != nil || len(res.Skips) != 1 || res.Skips[0].Line != 2 { + t.Errorf("netlify.toml: %v %+v", err, res.Skips) + } + ch, already, err = plan(root, f) + mustDecline(t, "netlify.toml from a variable", ch, already, err) + + // A range or a floating value is a value, not an expression. + for _, v := range []string{"'>=22 <25'", "'^24'", "lts/*", "24.x", "'~24.22'"} { + root := t.TempDir() + write(t, root, map[string]string{".github/workflows/ci.yml": "on: push\njobs:\n a:\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: " + v + "\n"}) + if res, err := pins.Scan(ctx, root, nil, pins.Options{}); err != nil || len(res.Skips) != 0 { + t.Errorf("%s: %v %+v", v, err, res.Skips) + } + } +} + +// Every reader records a fixed value under the source its findings carry, +// so a plan with the finding's props finds it there. +func TestJudgedSourceStrings(t *testing.T) { + ctx := context.Background() + for _, c := range []struct{ file, was, now string }{ + {"Dockerfile", "FROM node:24.22.0\n", "FROM node:24.22.1\n"}, + {"Dockerfile", "FROM mcr.microsoft.com/dotnet/aspnet:8.0.32\n", "FROM mcr.microsoft.com/dotnet/aspnet:8.0.33\n"}, + {"Dockerfile", "FROM mcr.microsoft.com/dotnet/sdk:8.0.415\n", "FROM mcr.microsoft.com/dotnet/sdk:8.0.427\n"}, + {"Dockerfile", "FROM oven/bun:1.4.3\n", "FROM oven/bun:1.4.4\n"}, + {"Dockerfile", "FROM gcr.io/distroless/nodejs20-debian12\n", "FROM gcr.io/distroless/nodejs22-debian12\n"}, + {"Dockerfile", "FROM debian:12\nRUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash\n", "FROM debian:12\nRUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash\n"}, + {"Dockerfile", "FROM debian:12\nENV NODE_VERSION=24.22.0\n", "FROM debian:12\nENV NODE_VERSION=24.22.1\n"}, + {"requirements.txt", "pycurl==7.48.0\n", "pycurl==7.49.0\n"}, + {"app.csproj", "\n \n net6.0\n \n\n", "\n \n net8.0\n \n\n"}, + {"svc/packages.lock.json", depsRepo["svc/packages.lock.json"], strings.Replace(depsRepo["svc/packages.lock.json"], "8.0.32", "8.0.33", 1)}, + {".nvmrc", "22.23.1\n", "22.23.4\n"}, + {".github/workflows/ci.yml", "on: push\njobs:\n a:\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: 24.22.0\n", + "on: push\njobs:\n a:\n runs-on: x\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: 24.22.1\n"}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.was}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Findings) != 1 { + t.Errorf("%s %q: %v %+v", c.file, c.was, err, res.Findings) + continue + } + f := res.Findings[0] + write(t, root, map[string]string{c.file: c.now}) + got := pins.JudgedSources(root, f.File, f.Line, f.Rule) + found := false + for _, s := range got { + found = found || s == f.Props["source"] + } + if !found { + t.Errorf("%s %q: the fixed value is recorded under %v, the finding's source is %q", c.file, c.now, got, f.Props["source"]) + } + } +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index 947e1e4..1960adb 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -234,6 +234,12 @@ func unchecked(root string, s *scanner, file string, line int, rule string, prop return notChecked("line %d of %s holds no value of this kind now, and line %d was not checked (%s): the pin may have moved there", line, file, sk.Line, scrub(root, sk.Reason)) } } + if moved && (s.exprAt[judgedKey{file, line, rule, ""}] || s.exprAt[judgedKey{file, line, "", ""}]) { + // The release on the line is now read from a variable or an + // expression (nvm install $V, a URL with ${V}): changed in place, + // not known to be fixed. + return notChecked("line %d of %s now sets the release from a variable or expression the scan does not resolve", line, file) + } for _, q := range s.pins { if q.file != file || q.prod.rule() != rule { continue diff --git a/detectors/brotli/internal/pins/sources.go b/detectors/brotli/internal/pins/sources.go index 0e05ba8..232a8a9 100644 --- a/detectors/brotli/internal/pins/sources.go +++ b/detectors/brotli/internal/pins/sources.go @@ -328,6 +328,9 @@ func (s *scanner) dotnetProject(rel string, b []byte) { supported = true } } + if supported { + s.judge(rel, i+1, RuleDotnet, "target-framework") // judged: on a supported .NET + } for _, tfm := range strings.Split(list, ";") { if supported { break @@ -488,11 +491,108 @@ var textPatterns = []textPattern{ } // versionVarExprRe finds a runtime version variable set from another -// variable (ENV NODE_VERSION=$BUILD_NODE): group 3 is the variable read. -var versionVarExprRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+(NODE_VERSION|BUN_VERSION|DOTNET_VERSION|ASPNET_VERSION|ASPNETCORE_VERSION)[= ]["']?(\$\{?([A-Za-z_][A-Za-z0-9_]*)[^\s"']*)`) +// variable: ENV NODE_VERSION=$BUILD_NODE, ${BUILD_NODE}, or +// ${BUILD_NODE:-24.22.1}. Groups: 1 the version variable, 2 the expression, +// 3 the braced name, 4 its default operator, 5 the default, 6 a bare name. +var versionVarExprRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+(NODE_VERSION|BUN_VERSION|DOTNET_VERSION|ASPNET_VERSION|ASPNETCORE_VERSION)[= ]["']?(\$(?:\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)([^}"'\s]*))?\}|([A-Za-z_][A-Za-z0-9_]*)))`) + +// versionVars are the version variables' products and sources. +var versionVars = map[string]struct { + prod product + source string +}{ + "NODE_VERSION": {node, "node-version-var"}, "BUN_VERSION": {bun, "bun-version-var"}, + "DOTNET_VERSION": {dotnet, "dotnet-version-var"}, "ASPNET_VERSION": {dotnet, "dotnet-version-var"}, "ASPNETCORE_VERSION": {dotnet, "dotnet-version-var"}, +} + +// assignRe finds a variable set to a release (ARG BUILD_NODE=24.22.0). +var assignRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+([A-Za-z_][A-Za-z0-9_]*)[= ]["']?(v?[0-9][0-9A-Za-z.+-]*)`) + +// exprValue is a value written as a reference the scan does not resolve. +const exprValue = `(\$\{\{[^}]*\}\}|\$\{[^}]*\}|\$\([^)]*\)|\$[A-Za-z_][A-Za-z0-9_]*)` -// setVarRe finds a variable set to a release (ARG NODE_VERSION=24.22.0). -var setVarRe = regexp.MustCompile(`(?m)\b(?:ENV|ARG|export)\s+([A-Za-z_][A-Za-z0-9_]*)[= ]["']?v?[0-9]`) +// exprPatterns are the release slots of the text patterns with such a value +// in them (nvm install $V, a download URL with ${V}). An ordinary scan +// does not list them, since the shell sets them in ways it does not +// follow; a plan never reads one as a pin fixed in place. +var exprPatterns = []struct { + re *regexp.Regexp + prod product +}{ + {regexp.MustCompile(`nodejs\.org/(?:dist|download/release)/v?` + exprValue), node}, + {regexp.MustCompile(`\b(?:nvm|fnm)\s+(?:install|use)\s+(?:--lts=)?["']?` + exprValue), node}, + {regexp.MustCompile(`\bvolta\s+(?:install|pin)\s+node@` + exprValue), node}, + {regexp.MustCompile(`\basdf\s+(?:install|local|global|set)\s+nodejs\s+` + exprValue), node}, + {regexp.MustCompile(`\bmise\s+(?:use|install)\s+(?:-g\s+|--global\s+)?node(?:js)?@` + exprValue), node}, + {regexp.MustCompile(`(?:deb|rpm)\.nodesource\.com/setup_` + exprValue), node}, + {regexp.MustCompile(`^\s*NODE_VERSION:\s*["']?` + exprValue), node}, + {regexp.MustCompile(`bun\.sh/install[^\n]*bun-v` + exprValue), bun}, + {regexp.MustCompile(`^\s*BUN_VERSION:\s*["']?` + exprValue), bun}, + {regexp.MustCompile(`dotnet-install\.(?:sh|ps1)\b[^\n]*(?:--version|-Version)\s+` + exprValue), dotnet}, +} + +// commentLine reports a line that is a comment in the files the text +// patterns read (#: shell, Dockerfile, YAML, TOML, Makefile, Python; +// //: JavaScript, TypeScript, C#, Go, Java, Kotlin, Bicep, Terraform). +func commentLine(l string) bool { + t := strings.TrimLeft(l, " \t") + return strings.HasPrefix(t, "#") || strings.HasPrefix(t, "//") +} + +// versionVar judges a version variable set from another variable: by the +// value that variable was last set to above it in the file, edited there; +// else by a ${X:-default}'s default; else it is listed as not checked (a +// build argument or environment value from outside the file). +func (s *scanner) versionVar(rel string, lines []string, i int, m []int, assigned map[string][][3]int) { + l := lines[i] + vv := versionVars[l[m[2]:m[3]]] + desc := fmt.Sprintf("%s (%s)", l[m[2]:m[3]], path.Base(rel)) + name := "" + switch { + case m[6] >= 0: + name = l[m[6]:m[7]] + case m[12] >= 0: + name = l[m[12]:m[13]] + } + if at := assigned[name]; len(at) > 0 { + var last [3]int // line, start and end of the value + for _, a := range at { + if a[0] < i { + last = a + } + } + if last[2] > 0 { + v := lines[last[0]][last[1]:last[2]] + j := judgeValue(vv.prod, v, false) + if j.vd == notJudged { + s.unresolved(rel, i+1, vv.prod.rule()) + return + } + p := pin{prod: vv.prod, source: vv.source, desc: desc, file: rel, line: i + 1, editFile: rel, editLine: last[0] + 1, col: -1, j: j, via: true} + if k := strings.Index(v, j.current); j.current != "" && k >= 0 { + p.col = last[1] + k + } + s.add(p) + return + } + } + if m[8] >= 0 && m[10] >= 0 && m[11] > m[10] { + v := l[m[10]:m[11]] + j := judgeValue(vv.prod, v, false) + if j.vd == notJudged { + s.unresolved(rel, i+1, vv.prod.rule()) + return + } + p := pin{prod: vv.prod, source: vv.source, desc: desc, file: rel, line: i + 1, editFile: rel, editLine: i + 1, col: -1, j: j} + if k := strings.Index(v, j.current); j.current != "" && k >= 0 { + p.col = m[10] + k + } + s.add(p) + return + } + s.expression(rel, i+1, desc, l[m[4]:m[5]]) + s.unresolved(rel, i+1, vv.prod.rule()) +} // sha256Re finds a pinned checksum, which a download's version change would // also need. @@ -521,19 +621,38 @@ func (s *scanner) textPatterns(rel string, b []byte) { src := isProgramSource(rel) lines := splitLines(b) spans := logicalSpans(lines) - // Variables the file sets to a release: a version variable that reads - // one is judged where it is set. - set := map[string]bool{} - for _, m := range setVarRe.FindAllSubmatch(b, -1) { - set[string(m[1])] = true + // Variables the file sets to a release, by line: a version variable + // that reads one is judged by it. + var assigned map[string][][3]int + if !src { + for i, l := range lines { + if commentLine(l) { + continue + } + for _, m := range assignRe.FindAllStringSubmatchIndex(l, -1) { + if assigned == nil { + assigned = map[string][][3]int{} + } + n := l[m[2]:m[3]] + assigned[n] = append(assigned[n], [3]int{i, m[4], m[5]}) + } + } } for i, l := range lines { if i%4096 == 0 && s.ctx != nil && s.ctx.Err() != nil { return } + if commentLine(l) { + continue + } if !src { - if m := versionVarExprRe.FindStringSubmatch(l); m != nil && !set[m[3]] { - s.expression(rel, i+1, m[1], m[2]) + if m := versionVarExprRe.FindStringSubmatchIndex(l); m != nil { + s.versionVar(rel, lines, i, m, assigned) + } + for _, ep := range exprPatterns { + if ep.re.MatchString(l) { + s.unresolved(rel, i+1, ep.prod.rule()) + } } } for _, tp := range textPatterns { From 2b926b24104e6ddd53a58534a36869eef6179c47 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 19 Nov 2026 01:56:45 +0000 Subject: [PATCH 7/8] brotli: fuzz seed for version variables and expression slots Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/fuzz_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/detectors/brotli/internal/pins/fuzz_test.go b/detectors/brotli/internal/pins/fuzz_test.go index 1c084fd..5f2a332 100644 --- a/detectors/brotli/internal/pins/fuzz_test.go +++ b/detectors/brotli/internal/pins/fuzz_test.go @@ -20,6 +20,7 @@ var fuzzNames = []string{".nvmrc", ".tool-versions", "mise.toml", "package.json" // the file the finding names. func FuzzPins(f *testing.F) { for _, s := range []string{"20\n", "FROM node:24.22.0-slim\n", "{\"engines\":{\"node\":\"20.x\"}}", "pycurl==7.48.0\n", + "ARG B=24.22.0\nFROM debian:12\nENV NODE_VERSION=${B:-24.21.0}\n# nvm install $V\nnvm install $(cat .nvmrc)\n", "\ufeff{\"sdk\": {/* \"version\": \"8.0.1\" */ \"version\": \"8.0.415\"}} // \"https://x\"\n", "jobs:\n a:\n strategy:\n matrix:\n n: [20]\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ matrix.n }}\n"} { for i := range fuzzNames { From fd0077703f423c5d004da0a533a130b574564947 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Thu, 19 Nov 2026 02:31:11 +0000 Subject: [PATCH 8/8] brotli: an unresolved release slot is never judged fixed Final review round: close the class rather than the cases. - One rule at fix time: when no release of the finding's rule is judged on its line and the line holds a value the scan does not resolve (a $ variable or expansion, $( ), a backtick, ${{ }}, << >>), Plan declines "rescan to confirm". It replaces the per-pattern expression slots, and covers ${V:?..}, ${V%..}, ${V:+..}, quoted defaults, export X=$(cat ..), nvm install v$V, quoted asdf, volta and dotnet-install values, and managed runtimes from a variable. - A text pattern no longer judges the start of a value that goes on as an expression (nvm install 24$SUFFIX), and textPin and addJudged never judge a value with an unresolved reference in it. - A version variable is evaluated only when it reads one variable plainly or with an unquoted literal default; any other $ or backtick value is listed as not checked, as is a variable nothing in scope sets. A shell command or URL slot is not listed: the plan declines it in place. - ARG scope across Dockerfile stages: an ENV reads its own stage's ARG, or the global one only through an ARG line in the stage. A variable-fed edit is made by hand when the ARG is set in more than one place or a FROM reads it. - A leading # is a comment only where the language says so: in JavaScript and TypeScript it is a private field, and CDK runtimes there are read. - One definition of an unresolved value (unresolvedRe), used by the listing and the plan. Co-Authored-By: Claude Opus 5.5 --- detectors/brotli/internal/pins/brotlipin.go | 24 +- detectors/brotli/internal/pins/fuzz_test.go | 1 + .../brotli/internal/pins/notchecked_test.go | 147 ++++++++++- detectors/brotli/internal/pins/plan.go | 11 +- detectors/brotli/internal/pins/sources.go | 228 ++++++++++++------ 5 files changed, 305 insertions(+), 106 deletions(-) diff --git a/detectors/brotli/internal/pins/brotlipin.go b/detectors/brotli/internal/pins/brotlipin.go index 8f2d965..e06206c 100644 --- a/detectors/brotli/internal/pins/brotlipin.go +++ b/detectors/brotli/internal/pins/brotlipin.go @@ -323,19 +323,6 @@ type scanner struct { // judged there, whatever the verdict: what a plan finds on a finding's // line when the pin is gone. judged map[judgedKey]bool - // exprAt holds file, line and rule ("" source) where a release slot - // holds a value the scan does not resolve (nvm install $V, a URL with - // ${V}): not listed as not checked, but never a fix in place. - exprAt map[judgedKey]bool -} - -// unresolved records that line of file sets a release of rule from a value -// the scan does not resolve. -func (s *scanner) unresolved(file string, line int, rule string) { - if s.exprAt == nil { - s.exprAt = map[judgedKey]bool{} - } - s.exprAt[judgedKey{file, line, rule, ""}] = true } type judgedKey struct { @@ -678,7 +665,9 @@ func (s *scanner) parseFile(rel string, k fileKind) { // textPin judges value written at byte col of line and adds the pin. func (s *scanner) textPin(prod product, source, desc, rel string, line, col int, value string) { j := judgeValue(prod, value, false) - if j.vd == notJudged { + if j.vd == notJudged || unresolvedRe.MatchString(value) { + // Never judged from a value the scan does not resolve, even when + // it starts like a release (24.22.1$X). s.expression(rel, line, desc, value) return } @@ -940,18 +929,13 @@ func (s *scanner) images(files []string) error { // imageSource is Props["source"] of an official runtime image's pin. var imageSource = map[product]string{node: "node-image", dotnet: "dotnet-image", bun: "bun-image", dotnetSDK: "dotnet-sdk-image"} -// exprRef matches a value written as a reference the scan does not -// resolve: ${{ ... }}, ${VAR}, $VAR, $(VAR), << parameters.x >>. -var exprRef = regexp.MustCompile(`\$\{\{|\$\{[A-Za-z_]|\$[A-Za-z_]|\$\(|<<`) - // expression records a value written as an expression as not checked: a // pin changed to one in place is not fixed, and is not known to be. func (s *scanner) expression(rel string, line int, desc, value string) { - if line < 1 || !exprRef.MatchString(value) { + if line < 1 || !unresolvedRe.MatchString(value) { return } s.skips = append(s.skips, Skip{File: rel, Line: line, Reason: clean(fmt.Sprintf("%s is %s, an expression the scan does not resolve; check the release it selects by hand", desc, value), 300)}) - s.unresolved(rel, line, "") } func (s *scanner) judgeImage(r refs.Ref) { diff --git a/detectors/brotli/internal/pins/fuzz_test.go b/detectors/brotli/internal/pins/fuzz_test.go index 5f2a332..a3412b3 100644 --- a/detectors/brotli/internal/pins/fuzz_test.go +++ b/detectors/brotli/internal/pins/fuzz_test.go @@ -21,6 +21,7 @@ var fuzzNames = []string{".nvmrc", ".tool-versions", "mise.toml", "package.json" func FuzzPins(f *testing.F) { for _, s := range []string{"20\n", "FROM node:24.22.0-slim\n", "{\"engines\":{\"node\":\"20.x\"}}", "pycurl==7.48.0\n", "ARG B=24.22.0\nFROM debian:12\nENV NODE_VERSION=${B:-24.21.0}\n# nvm install $V\nnvm install $(cat .nvmrc)\n", + "ARG B=24.22.0\nFROM node:${B} AS a\nARG B\nENV NODE_VERSION=$B\nFROM debian:12\nENV NODE_VERSION=${B:?x}\nRUN nvm install 24$S\n", "\ufeff{\"sdk\": {/* \"version\": \"8.0.1\" */ \"version\": \"8.0.415\"}} // \"https://x\"\n", "jobs:\n a:\n strategy:\n matrix:\n n: [20]\n steps:\n - uses: actions/setup-node@v4\n with:\n node-version: ${{ matrix.n }}\n"} { for i := range fuzzNames { diff --git a/detectors/brotli/internal/pins/notchecked_test.go b/detectors/brotli/internal/pins/notchecked_test.go index 713c0d5..eb36f29 100644 --- a/detectors/brotli/internal/pins/notchecked_test.go +++ b/detectors/brotli/internal/pins/notchecked_test.go @@ -747,7 +747,7 @@ func TestExpressionInPlace(t *testing.T) { // A variable the file sets to a release is read where it is set: the // reference to it is no gap. root := t.TempDir() - write(t, root, map[string]string{"Dockerfile": "ARG NODE_VERSION=24.22.1\nFROM debian:12\nENV NODE_VERSION=$NODE_VERSION\n"}) + write(t, root, map[string]string{"Dockerfile": "ARG NODE_VERSION=24.22.1\nFROM debian:12\nARG NODE_VERSION\nENV NODE_VERSION=$NODE_VERSION\n"}) if res, err := pins.Scan(context.Background(), root, nil, pins.Options{}); err != nil || len(res.Skips) != 0 || len(res.Findings) != 0 { t.Errorf("a set variable: %v %+v", err, res) } @@ -864,10 +864,10 @@ func TestVersionVariablesResolved(t *testing.T) { what, file, body string want []want }{ - {"ENV from a fixed ARG", "Dockerfile", "ARG NODE_VERSION=24.22.1\nFROM debian:12\nENV NODE_VERSION=$NODE_VERSION\n", nil}, - {"ENV from a vulnerable ARG of another name", "Dockerfile", "ARG BUILD_NODE=24.22.0\nFROM debian:12\nENV NODE_VERSION=$BUILD_NODE\n", []want{{3, "24.22.0"}}}, - {"ENV from a vulnerable ARG of its name: one finding", "Dockerfile", "ARG NODE_VERSION=24.22.0\nFROM debian:12\nENV NODE_VERSION=${NODE_VERSION}\n", []want{{1, "24.22.0"}}}, - {"ENV from the ARG the FROM reads: the image finding", "Dockerfile", "ARG NODE_VERSION=24.22.0\nFROM node:${NODE_VERSION}\nENV NODE_VERSION=$NODE_VERSION\n", []want{{2, "24.22.0"}}}, + {"ENV from a fixed ARG", "Dockerfile", "ARG NODE_VERSION=24.22.1\nFROM debian:12\nARG NODE_VERSION\nENV NODE_VERSION=$NODE_VERSION\n", nil}, + {"ENV from a vulnerable ARG of another name", "Dockerfile", "ARG BUILD_NODE=24.22.0\nFROM debian:12\nARG BUILD_NODE\nENV NODE_VERSION=$BUILD_NODE\n", []want{{4, "24.22.0"}}}, + {"ENV from a vulnerable ARG of its name: one finding", "Dockerfile", "ARG NODE_VERSION=24.22.0\nFROM debian:12\nARG NODE_VERSION\nENV NODE_VERSION=${NODE_VERSION}\n", []want{{1, "24.22.0"}}}, + {"ENV from the ARG the FROM reads: the image finding", "Dockerfile", "ARG NODE_VERSION=24.22.0\nFROM node:${NODE_VERSION}\nARG NODE_VERSION\nENV NODE_VERSION=$NODE_VERSION\n", []want{{2, "24.22.0"}}}, {"a fixed default", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=${NODE_VERSION:-24.22.1}\n", nil}, {"a vulnerable default", "Dockerfile", "FROM debian:12\nENV NODE_VERSION=${NODE_VERSION:-24.22.0}\n", []want{{2, "24.22.0"}}}, {"commented-out lines", "Dockerfile", "# ENV NODE_VERSION=24.22.0\n# ENV NODE_VERSION=$UNSET\nFROM debian:12\n # RUN nvm install 18\n", nil}, @@ -888,7 +888,7 @@ func TestVersionVariablesResolved(t *testing.T) { // The fix of an ENV that reads an ARG moves the ARG; of a default, the // default. for _, c := range []struct{ body, want string }{ - {"ARG BUILD_NODE=24.22.0\nFROM debian:12\nENV NODE_VERSION=$BUILD_NODE\n", "ARG BUILD_NODE=24.22.1"}, + {"ARG BUILD_NODE=24.22.0\nFROM debian:12\nARG BUILD_NODE\nENV NODE_VERSION=$BUILD_NODE\n", "ARG BUILD_NODE=24.22.1"}, {"FROM debian:12\nENV NODE_VERSION=${NODE_VERSION:-24.22.0}\n", "ENV NODE_VERSION=${NODE_VERSION:-24.22.1}"}, } { root := t.TempDir() @@ -975,3 +975,138 @@ func TestJudgedSourceStrings(t *testing.T) { } } } + +// The class: a release slot whose value is not a literal release after +// what the scan resolves (a $, a backtick, $( ), ${{ }}, << >>, or a +// parameter expansion it does not evaluate) is never judged fixed. It +// declines "rescan to confirm" at fix time, and is listed as not checked +// only where the value cannot be resolved (a version variable, a +// structured slot), not for a shell command or URL. +func TestUnresolvedSlotNeverFixed(t *testing.T) { + ctx := context.Background() + env := func(v string) string { return "FROM debian:12\nENV NODE_VERSION=" + v + "\n" } + for _, c := range []struct { + what, file, was, now string + listed bool + }{ + {"${V:?err}", "Dockerfile", env("24.22.0"), env("${V:?set V}"), true}, + {"${V%.*}", "Dockerfile", env("24.22.0"), env("${V%.*}"), true}, + {"${V:+alt}", "Dockerfile", env("24.22.0"), env("${V:+24.22.1}"), true}, + {"a quoted default", "Dockerfile", env("24.22.0"), env(`${V:-"24.22.1"}`), true}, + {"a default with a suffix", "Dockerfile", env("24.22.0"), env("${V:-24.22.1}-$X"), true}, + {"export from $(cat ..)", "install.sh", "export NODE_VERSION=24.22.0\n", "export NODE_VERSION=$(cat .nvmrc)\n", true}, + {"export from backticks", "install.sh", "export NODE_VERSION=24.22.0\n", "export NODE_VERSION=`cat .nvmrc`\n", true}, + {"nvm install v$V", "install.sh", "nvm install 24.22.0\n", "nvm install v$V\n", false}, + {"nvm install 24$SUFFIX", "install.sh", "nvm install 24.22.0\n", "nvm install 24$SUFFIX\n", false}, + {"nvm install `cat .nvmrc`", "install.sh", "nvm install 24.22.0\n", "nvm install `cat .nvmrc`\n", false}, + {"a quoted asdf value", "install.sh", "asdf install nodejs 24.22.0\n", "asdf install nodejs \"$V\"\n", false}, + {"a quoted volta value", "install.sh", "volta install node@24.22.0\n", "volta install node@\"$V\"\n", false}, + {"a quoted dotnet-install version", "install.sh", "./dotnet-install.sh --runtime dotnet --version 8.0.32\n", "./dotnet-install.sh --runtime dotnet --version \"$V\"\n", false}, + {"a managed runtime from a variable", "serverless.yml", "provider:\n runtime: nodejs18.x\n", "provider:\n runtime: ${self:custom.runtime}\n", false}, + {"a managed runtime with a variable major", "serverless.yml", "provider:\n runtime: nodejs18.x\n", "provider:\n runtime: nodejs${NODE}.x\n", false}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.was}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Findings) != 1 { + t.Fatalf("%s: %v %+v", c.what, err, res.Findings) + } + f := res.Findings[0] + write(t, root, map[string]string{c.file: c.now}) + res, err = pins.Scan(ctx, root, nil, pins.Options{}) + listed := err == nil && len(res.Skips) == 1 && res.Skips[0].Line == f.Line + if err != nil || listed != c.listed || len(res.Findings) != 0 || (!c.listed && len(res.Skips) != 0) { + t.Errorf("%s: want listed %v and no finding: %v findings %+v skips %+v", c.what, c.listed, err, res.Findings, res.Skips) + } + ch, already, err := plan(root, f) + mustDecline(t, c.what, ch, already, err) + } +} + +// In JavaScript and TypeScript a leading # is a private field, not a +// comment; in Python it is a comment. +func TestHashLines(t *testing.T) { + for _, c := range []struct { + file, body string + n int + }{ + {"stack.ts", "class S {\n #runtime = Runtime.NODEJS_16_X;\n}\n", 1}, + {"stack.js", "class S {\n #runtime = lambda.Runtime.NODEJS_16_X\n}\n", 1}, + {"stack.py", "# runtime=Runtime.NODEJS_16_X\n", 0}, + {"stack.ts", " // runtime: Runtime.NODEJS_16_X\n", 0}, + } { + root := t.TempDir() + write(t, root, map[string]string{c.file: c.body}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Findings) != c.n { + t.Errorf("%s %q: %v %+v", c.file, c.body, err, res.Findings) + } + } +} + +// ARG scope across Dockerfile stages: an ENV reads the ARG its own stage +// declares (a global ARG only through an ARG line in the stage), and a +// variable-fed edit is made by hand when the ARG is set in more than one +// place or a FROM reads it. +func TestARGStageScope(t *testing.T) { + ctx := context.Background() + type want struct { + line int + current string + fixable bool + } + for _, c := range []struct { + what, body string + want []want + skips int + }{ + {"a global ARG not declared in the stage", "ARG B=24.22.0\nFROM debian:12 AS a\nENV NODE_VERSION=$B\n", nil, 1}, + {"a global ARG declared in the stage", "ARG B=24.22.0\nFROM debian:12 AS a\nARG B\nENV NODE_VERSION=$B\n", []want{{4, "24.22.0", true}}, 0}, + {"an ARG of another stage", "FROM debian:12 AS a\nARG B=24.22.1\nFROM debian:12 AS b\nENV NODE_VERSION=$B\n", nil, 1}, + {"each stage its own ARG", "FROM debian:12 AS a\nARG B=24.22.0\nENV NODE_VERSION=$B\nFROM debian:12 AS b\nARG B=24.21.0\nENV NODE_VERSION=$B\n", + []want{{3, "24.22.0", false}, {6, "24.21.0", false}}, 0}, + {"an ARG a FROM reads", "ARG B=24.22.0\nFROM debian:${B} AS a\nARG B\nENV NODE_VERSION=$B\n", []want{{4, "24.22.0", false}}, 0}, + } { + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": c.body}) + res, err := pins.Scan(ctx, root, nil, pins.Options{}) + if err != nil || len(res.Findings) != len(c.want) || len(res.Skips) != c.skips { + t.Errorf("%s: %v findings %+v skips %+v", c.what, err, res.Findings, res.Skips) + continue + } + for k, w := range c.want { + f := res.Findings[k] + if f.Line != w.line || f.Props["current"] != w.current || f.Fixable != w.fixable { + t.Errorf("%s: %+v, want %+v", c.what, f, w) + } + if !w.fixable { + if ch, already, err := plan(root, f); ch != nil || already || err == nil { + t.Errorf("%s: a by-hand edit planned: %+v %v %v", c.what, ch, already, err) + } + } + } + } + // A pin whose stage now reads an ARG set only in another stage is not + // fixed. + root := t.TempDir() + write(t, root, map[string]string{"Dockerfile": "FROM debian:12 AS a\nARG B=24.22.1\nFROM debian:12 AS b\nENV NODE_VERSION=24.22.0\n"}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{"Dockerfile": "FROM debian:12 AS a\nARG B=24.22.1\nFROM debian:12 AS b\nENV NODE_VERSION=$B\n"}) + ch, already, err := plan(root, f) + mustDecline(t, "an ARG of another stage", ch, already, err) +} + +// A version file value that starts like a release but goes on as a +// variable is listed, not judged. +func TestVersionFileValueWithVariable(t *testing.T) { + root := t.TempDir() + write(t, root, map[string]string{".nvmrc": "24.22.0\n"}) + f := only(t, root, pins.RuleNode) + write(t, root, map[string]string{".nvmrc": "24.22.1$SUFFIX\n"}) + res, err := pins.Scan(context.Background(), root, nil, pins.Options{}) + if err != nil || len(res.Findings) != 0 || len(res.Skips) != 1 { + t.Errorf("%v %+v", err, res) + } + ch, already, err := plan(root, f) + mustDecline(t, ".nvmrc 24.22.1$SUFFIX", ch, already, err) +} diff --git a/detectors/brotli/internal/pins/plan.go b/detectors/brotli/internal/pins/plan.go index 1960adb..71b3a90 100644 --- a/detectors/brotli/internal/pins/plan.go +++ b/detectors/brotli/internal/pins/plan.go @@ -234,11 +234,12 @@ func unchecked(root string, s *scanner, file string, line int, rule string, prop return notChecked("line %d of %s holds no value of this kind now, and line %d was not checked (%s): the pin may have moved there", line, file, sk.Line, scrub(root, sk.Reason)) } } - if moved && (s.exprAt[judgedKey{file, line, rule, ""}] || s.exprAt[judgedKey{file, line, "", ""}]) { - // The release on the line is now read from a variable or an - // expression (nvm install $V, a URL with ${V}): changed in place, - // not known to be fixed. - return notChecked("line %d of %s now sets the release from a variable or expression the scan does not resolve", line, file) + if moved && line >= 1 && line <= n && unresolvedRe.MatchString(splitLines(content)[line-1]) { + // No release of the rule is judged on the line, and the line now + // holds a value the scan does not resolve (nvm install $V, a URL + // with ${V}, $(cat .nvmrc), a template): the pin may be there, + // changed in place. Whatever the slot, it is not known to be fixed. + return notChecked("line %d of %s now holds a value the scan does not resolve (a variable, a command or a template)", line, file) } for _, q := range s.pins { if q.file != file || q.prod.rule() != rule { diff --git a/detectors/brotli/internal/pins/sources.go b/detectors/brotli/internal/pins/sources.go index 232a8a9..d4110ed 100644 --- a/detectors/brotli/internal/pins/sources.go +++ b/detectors/brotli/internal/pins/sources.go @@ -82,7 +82,7 @@ func (s *scanner) nodePin(prod product, source, desc, rel string, lines []string // addJudged adds a judged value written at col of line (col -1: not // editable verbatim). func (s *scanner) addJudged(prod product, source, desc, rel string, line, col int, value string, j judgement) { - if j.vd == notJudged { + if j.vd == notJudged || unresolvedRe.MatchString(value) { s.expression(rel, line, desc, value) return } @@ -490,11 +490,15 @@ var textPatterns = []textPattern{ {re: regexp.MustCompile(`\bRuntime\.DOTNET_CORE_(\d)_\d\b`), prod: dotnet, source: "managed-runtime", desc: "AWS CDK Lambda runtime", line: true, sourceOnly: true, managed: true}, } -// versionVarExprRe finds a runtime version variable set from another -// variable: ENV NODE_VERSION=$BUILD_NODE, ${BUILD_NODE}, or -// ${BUILD_NODE:-24.22.1}. Groups: 1 the version variable, 2 the expression, -// 3 the braced name, 4 its default operator, 5 the default, 6 a bare name. -var versionVarExprRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+(NODE_VERSION|BUN_VERSION|DOTNET_VERSION|ASPNET_VERSION|ASPNETCORE_VERSION)[= ]["']?(\$(?:\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)([^}"'\s]*))?\}|([A-Za-z_][A-Za-z0-9_]*)))`) +// versionVarRe finds a runtime version variable and the value it is set +// to, as written: group 1 the variable, group 2 the value token. +var versionVarRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+(NODE_VERSION|BUN_VERSION|DOTNET_VERSION|ASPNET_VERSION|ASPNETCORE_VERSION)[= ](\S+)`) + +// varRefRe is a value that reads one variable, plainly or with a literal +// default: $X, ${X}, ${X:-24.22.1}, ${X-24.22.1}. Anything else with a $ or +// a backtick (${X:?..}, ${X%..}, ${X:+..}, a quoted default, $(..), a +// suffix) is not evaluated. +var varRefRe = regexp.MustCompile(`^\$(?:([A-Za-z_][A-Za-z0-9_]*)|\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)(v?[0-9][0-9A-Za-z.+-]*))?\})$`) // versionVars are the version variables' products and sources. var versionVars = map[string]struct { @@ -508,90 +512,164 @@ var versionVars = map[string]struct { // assignRe finds a variable set to a release (ARG BUILD_NODE=24.22.0). var assignRe = regexp.MustCompile(`\b(?:ENV|ARG|export)\s+([A-Za-z_][A-Za-z0-9_]*)[= ]["']?(v?[0-9][0-9A-Za-z.+-]*)`) -// exprValue is a value written as a reference the scan does not resolve. -const exprValue = `(\$\{\{[^}]*\}\}|\$\{[^}]*\}|\$\([^)]*\)|\$[A-Za-z_][A-Za-z0-9_]*)` - -// exprPatterns are the release slots of the text patterns with such a value -// in them (nvm install $V, a download URL with ${V}). An ordinary scan -// does not list them, since the shell sets them in ways it does not -// follow; a plan never reads one as a pin fixed in place. -var exprPatterns = []struct { - re *regexp.Regexp - prod product -}{ - {regexp.MustCompile(`nodejs\.org/(?:dist|download/release)/v?` + exprValue), node}, - {regexp.MustCompile(`\b(?:nvm|fnm)\s+(?:install|use)\s+(?:--lts=)?["']?` + exprValue), node}, - {regexp.MustCompile(`\bvolta\s+(?:install|pin)\s+node@` + exprValue), node}, - {regexp.MustCompile(`\basdf\s+(?:install|local|global|set)\s+nodejs\s+` + exprValue), node}, - {regexp.MustCompile(`\bmise\s+(?:use|install)\s+(?:-g\s+|--global\s+)?node(?:js)?@` + exprValue), node}, - {regexp.MustCompile(`(?:deb|rpm)\.nodesource\.com/setup_` + exprValue), node}, - {regexp.MustCompile(`^\s*NODE_VERSION:\s*["']?` + exprValue), node}, - {regexp.MustCompile(`bun\.sh/install[^\n]*bun-v` + exprValue), bun}, - {regexp.MustCompile(`^\s*BUN_VERSION:\s*["']?` + exprValue), bun}, - {regexp.MustCompile(`dotnet-install\.(?:sh|ps1)\b[^\n]*(?:--version|-Version)\s+` + exprValue), dotnet}, -} +// unresolvedRe finds a value the scan does not resolve: a variable, a +// command substitution, a template or a parameter. +var unresolvedRe = regexp.MustCompile("\\$[A-Za-z_{(]|`|<<") -// commentLine reports a line that is a comment in the files the text -// patterns read (#: shell, Dockerfile, YAML, TOML, Makefile, Python; -// //: JavaScript, TypeScript, C#, Go, Java, Kotlin, Bicep, Terraform). -func commentLine(l string) bool { +// commentLine reports a line that is a comment in rel's language: # in +// shell, Dockerfile, YAML, TOML, Makefile, Python and Terraform; // in +// JavaScript, TypeScript, C#, Go, Java, Kotlin, Bicep and Terraform. In +// JavaScript and TypeScript a leading # is a private field. +func commentLine(rel, l string) bool { t := strings.TrimLeft(l, " \t") + switch path.Ext(strings.ToLower(rel)) { + case ".ts", ".js", ".mjs", ".cjs", ".java", ".cs", ".go", ".kt", ".bicep": + return strings.HasPrefix(t, "//") + case ".py": + return strings.HasPrefix(t, "#") + } return strings.HasPrefix(t, "#") || strings.HasPrefix(t, "//") } +// dockerScope is what a Dockerfile's stages need to resolve an ARG: the +// FROM lines (0-based), and the lines that declare each ARG without a value. +type dockerScope struct { + froms []int + declared map[string][]int +} + +func newDockerScope(lines []string) dockerScope { + ds := dockerScope{declared: map[string][]int{}} + for i, l := range lines { + f := strings.Fields(l) + if len(f) < 2 { + continue + } + switch strings.ToUpper(f[0]) { + case "FROM": + ds.froms = append(ds.froms, i) + case "ARG": + if !strings.Contains(f[1], "=") { + ds.declared[f[1]] = append(ds.declared[f[1]], i) + } + } + } + return ds +} + +// stage returns the FROM line that starts line i's stage, or -1 before any. +func (ds dockerScope) stage(i int) int { + start := -1 + for _, f := range ds.froms { + if f <= i { + start = f + } + } + return start +} + +// value returns the assignment of name that line i reads, or ok false: in a +// file without stages the last one above it; in a Dockerfile stage the last +// one in the stage, or the global ARG (above the first FROM) when the stage +// declares the ARG. +func (ds dockerScope) value(assigned map[string][][3]int, name string, i int) ([3]int, bool) { + start := ds.stage(i) + var got [3]int + ok := false + for _, a := range assigned[name] { + if a[0] < i && a[0] > start { + got, ok = a, true + } + } + if ok || start < 0 { + return got, ok + } + declared := false + for _, d := range ds.declared[name] { + declared = declared || (d > start && d < i) + } + if !declared { + return got, false + } + for _, a := range assigned[name] { + if a[0] < ds.froms[0] { + got, ok = a, true + } + } + return got, ok +} + +// sharedARG reports a variable a by-hand edit is safer for: set in more +// than one place, or read by a FROM, where moving it changes another stage +// or the base image. +func (ds dockerScope) sharedARG(lines []string, assigned map[string][][3]int, name string) bool { + if len(assigned[name]) > 1 { + return true + } + for _, f := range ds.froms { + if strings.Contains(lines[f], "$"+name) || strings.Contains(lines[f], "${"+name) { + return true + } + } + return false +} + // versionVar judges a version variable set from another variable: by the -// value that variable was last set to above it in the file, edited there; -// else by a ${X:-default}'s default; else it is listed as not checked (a -// build argument or environment value from outside the file). -func (s *scanner) versionVar(rel string, lines []string, i int, m []int, assigned map[string][][3]int) { +// value that variable holds there (in a Dockerfile, in the line's stage), +// edited where it is set; else by a ${X:-default}'s default; else it is +// listed as not checked. A value the scan does not evaluate is listed too. +func (s *scanner) versionVar(rel string, lines []string, i int, m []int, assigned map[string][][3]int, ds dockerScope) { l := lines[i] vv := versionVars[l[m[2]:m[3]]] desc := fmt.Sprintf("%s (%s)", l[m[2]:m[3]], path.Base(rel)) + tok := l[m[4]:m[5]] + if !unresolvedRe.MatchString(tok) { + return // a literal: the text patterns judge it + } + r := varRefRe.FindStringSubmatchIndex(tok) + if r == nil { + s.expression(rel, i+1, desc, tok) + return + } name := "" switch { - case m[6] >= 0: - name = l[m[6]:m[7]] - case m[12] >= 0: - name = l[m[12]:m[13]] - } - if at := assigned[name]; len(at) > 0 { - var last [3]int // line, start and end of the value - for _, a := range at { - if a[0] < i { - last = a - } - } - if last[2] > 0 { - v := lines[last[0]][last[1]:last[2]] - j := judgeValue(vv.prod, v, false) - if j.vd == notJudged { - s.unresolved(rel, i+1, vv.prod.rule()) - return - } - p := pin{prod: vv.prod, source: vv.source, desc: desc, file: rel, line: i + 1, editFile: rel, editLine: last[0] + 1, col: -1, j: j, via: true} - if k := strings.Index(v, j.current); j.current != "" && k >= 0 { - p.col = last[1] + k - } - s.add(p) + case r[2] >= 0: + name = tok[r[2]:r[3]] + case r[4] >= 0: + name = tok[r[4]:r[5]] + } + if a, ok := ds.value(assigned, name, i); ok { + v := lines[a[0]][a[1]:a[2]] + j := judgeValue(vv.prod, v, false) + if j.vd == notJudged { + s.expression(rel, i+1, desc, tok) return } + p := pin{prod: vv.prod, source: vv.source, desc: desc, file: rel, line: i + 1, editFile: rel, editLine: a[0] + 1, col: -1, j: j, via: true} + if k := strings.Index(v, j.current); j.current != "" && k >= 0 { + p.col = a[1] + k + } + if p.col >= 0 && ds.sharedARG(lines, assigned, name) { + p.col, p.notes = -1, fmt.Sprintf("%s is set in more than one place or read by a FROM, so moving it changes another stage or the base image", name) + } + s.add(p) + return } - if m[8] >= 0 && m[10] >= 0 && m[11] > m[10] { - v := l[m[10]:m[11]] + if r[8] >= 0 { + v := tok[r[8]:r[9]] j := judgeValue(vv.prod, v, false) if j.vd == notJudged { - s.unresolved(rel, i+1, vv.prod.rule()) + s.expression(rel, i+1, desc, tok) return } p := pin{prod: vv.prod, source: vv.source, desc: desc, file: rel, line: i + 1, editFile: rel, editLine: i + 1, col: -1, j: j} if k := strings.Index(v, j.current); j.current != "" && k >= 0 { - p.col = m[10] + k + p.col = m[4] + r[8] + k } s.add(p) return } - s.expression(rel, i+1, desc, l[m[4]:m[5]]) - s.unresolved(rel, i+1, vv.prod.rule()) + s.expression(rel, i+1, desc, tok) } // sha256Re finds a pinned checksum, which a download's version change would @@ -624,9 +702,11 @@ func (s *scanner) textPatterns(rel string, b []byte) { // Variables the file sets to a release, by line: a version variable // that reads one is judged by it. var assigned map[string][][3]int + var ds dockerScope if !src { + ds = newDockerScope(lines) for i, l := range lines { - if commentLine(l) { + if commentLine(rel, l) { continue } for _, m := range assignRe.FindAllStringSubmatchIndex(l, -1) { @@ -642,17 +722,12 @@ func (s *scanner) textPatterns(rel string, b []byte) { if i%4096 == 0 && s.ctx != nil && s.ctx.Err() != nil { return } - if commentLine(l) { + if commentLine(rel, l) { continue } if !src { - if m := versionVarExprRe.FindStringSubmatchIndex(l); m != nil { - s.versionVar(rel, lines, i, m, assigned) - } - for _, ep := range exprPatterns { - if ep.re.MatchString(l) { - s.unresolved(rel, i+1, ep.prod.rule()) - } + if m := versionVarRe.FindStringSubmatchIndex(l); m != nil { + s.versionVar(rel, lines, i, m, assigned, ds) } } for _, tp := range textPatterns { @@ -664,6 +739,9 @@ func (s *scanner) textPatterns(rel string, b []byte) { continue } v := l[m[2]:m[3]] + if m[3] < len(l) && strings.ContainsRune("$`{(%", rune(l[m[3]])) { + continue // only the start of a value the scan does not resolve (24$SUFFIX) + } desc := fmt.Sprintf("%s (%s)", tp.desc, path.Base(rel)) if tp.line { s.judge(rel, i+1, tp.prod.rule(), tp.source)