diff --git a/.github/osv-scanner.toml b/.github/osv-scanner.toml index 9264e1e5..6c46cdf9 100644 --- a/.github/osv-scanner.toml +++ b/.github/osv-scanner.toml @@ -92,3 +92,27 @@ reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about t id = "GHSA-w4fh-qvv9-3v23" ignoreUntil = 2026-12-14 reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about an MCP server checking bearer tokens, which semgrep scan never starts" + +# Two more, published 2026-11-20 and read 2026-11-24. semgrep 1.186.0, the +# newest that day, still asks for mcp==1.29.0 and for wcmatch~=8.3, so no set +# pip can install holds either fix (mcp 1.30.0, wcmatch 11.2). +# +# The mcp one is about an MCP client over HTTP sending its OAuth credentials +# to an authorization server the MCP server names. semgrep scan starts no MCP +# client and holds no OAuth credentials. +# +# The wcmatch one is a slow match: a pattern with several stars takes minutes +# to reject a crafted name of 255 bytes. semgrep matches its include and +# exclude patterns against the paths of the tree it scans, so the only names +# it sees are the files of the change under review. The most a crafted name +# can do is slow the scan of the change that adds it, and the job's +# timeout-minutes of 15 ends that. The job holds no secret. +[[IgnoredVulns]] +id = "GHSA-qx49-fqc8-xw99" +ignoreUntil = 2026-12-14 +reason = "semgrep pins mcp==1.29.0 in every release, and the advisory is about an MCP client sending OAuth credentials, which semgrep scan never starts" + +[[IgnoredVulns]] +id = "GHSA-53pm-wgxf-c6qf" +ignoreUntil = 2026-12-14 +reason = "semgrep asks for wcmatch~=8.3 and the fix is in 11.2. The advisory is a slow match of crafted file names, and semgrep scan only matches the paths of the tree it scans, under a 15 minute job timeout" diff --git a/.github/scripts/tool_versions.py b/.github/scripts/tool_versions.py index ac5254ff..bbfc5bba 100644 --- a/.github/scripts/tool_versions.py +++ b/.github/scripts/tool_versions.py @@ -56,6 +56,7 @@ import os import pathlib import re +import shlex import sys import time import urllib.request @@ -224,20 +225,62 @@ def renderer(now): return [(RENDERER_PROJECT, pinned) + due(pinned, released, now)] -def npm_packages(texts, now): - """`npm install package@version` - asked of the npm registry.""" - # An npm install that names no version is a failure, not a line skipped: - # without this a pin taken off the command would take the package off this - # check with it, and the run would stay green (review of #205). +# The options of npm install the workflows pass a value to, so the word after +# one is that value and not a package. +NPM_VALUE_OPTIONS = {"--prefix", "--registry", "--tag", "--cache", "-C"} + +# What starts an argument that names files of this run rather than a package of +# the registry: a path, or a shell variable holding one. +LOCAL_ARGUMENT = (".", "/", "~", "$") + + +def npm_pins(texts): + """Every registry package an `npm install` in the workflows names, with its pin. + + Only a command counts: a line, or a part of one after &&, ||, ; or |, whose + first two words are `npm install`. A sentence that mentions npm install is + not one. `echo "... make npm install give people an older tfg"` in npm.yml + stopped this whole check on 2026-11-16 and 2026-11-23 before it read a pin. + + An argument that is a path or a variable installs files this run built, so + there is no registry to ask about it. A registry package that names no + version is a failure, not a line skipped: without this a pin taken off the + command would take the package off this check with it, and the run would + stay green (review of #205). + """ found = {} for name, text in texts.items(): for line in text.splitlines(): - if "npm install" not in line or line.lstrip().startswith("#"): + command = re.sub(r"^(-\s*)?run:\s*", "", line.strip()) + if command.startswith("#"): continue - m = re.search(r"\s([@\w./-]+)@(\d[\w.+-]*)\s*$", line) - if not m: - raise RuntimeError(f"{name} runs an npm install that pins no version: {line.strip()}") - found[m.group(1)] = m.group(2) + for part in re.split(r"&&|\|\||;|\|", command): + if part.split()[:2] != ["npm", "install"]: + continue + try: + words = shlex.split(part)[2:] + except ValueError as exc: + raise RuntimeError(f"{name} runs an npm install this cannot read ({exc}): {line.strip()}") from exc + value_next = False + for word in words: + if value_next: + value_next = False + continue + if word in NPM_VALUE_OPTIONS: + value_next = True + continue + if word.startswith("-") or word.startswith(LOCAL_ARGUMENT): + continue + m = re.fullmatch(r"(@?[\w./-]+)@(\d[\w.+-]*)", word) + if not m: + raise RuntimeError(f"{name} runs an npm install that pins no version for {word}: {line.strip()}") + found[m.group(1)] = m.group(2) + return found + + +def npm_packages(texts, now): + """`npm install package@version` - asked of the npm registry.""" + found = npm_pins(texts) rows = [] for package, pinned in sorted(found.items()): times = ask(f"https://registry.npmjs.org/{package}")["time"] @@ -276,22 +319,31 @@ def main(): now = datetime.datetime.now(datetime.timezone.utc) texts = workflow_text() rows = [] + failed = 0 + # Every check runs even after one fails. A failure that ended the run left + # every pin after it unread, and on 2026-11-16 and 2026-11-23 that was all + # of them while the job said only what the first failure was. for check in (lambda: go_tools(texts, now), lambda: go_toolchain(texts), lambda: renderer(now), lambda: npm_packages(texts, now), lambda: held(texts)): try: rows.extend(check()) except Exception as exc: # noqa: BLE001 - any failure here has to be loud + failed += 1 print(f"FAIL: {exc}") - print("Run the workflow again. If it fails the same way, the registry or the pin") - print("named above has changed shape, and this script has to follow it.") - return 1 for name, pinned, state, _ in rows: print(f" {name:<42} {pinned:<10} {state}") behind = [(name, pinned, to) for name, pinned, _, to in rows if to] print() + if failed: + print(f"{failed} check(s) failed, and the pins they read are not in the list above.") + print("Run the workflow again. If it fails the same way, the registry or the pin") + print("named above has changed shape, and this script has to follow it.") + print() if not behind: + if failed: + return 1 print(f"all {len(rows)} pin(s) are current or held on purpose") return 0 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index a0cba95d..90831ccf 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -111,9 +111,6 @@ jobs: github.event.workflow_run.head_repository.full_name == github.repository) runs-on: ubuntu-latest timeout-minutes: 10 - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} steps: # The rule below is right about the shape and the condition above is the # answer to it: this job only runs for a push, on this repository, so the @@ -152,5 +149,48 @@ jobs: with: path: web/public - - id: deployment + # The deployment is a job of its own, after the one that uploaded the site. + # deploy-pages finds the artifact by its name, and on 2026-11-24 it twice + # listed the sample-files artifact of the earlier job and not the + # github-pages one uploaded a moment before in the same job, so both runs + # failed with every file ready (actions/deploy-pages#451 reports the same, + # and upload-pages-artifact's artifact id cannot be passed to it instead). + # + # The lookup is also asked again, twice, after a wait. A lookup that finds + # nothing creates no deployment, and asking again in the same job uploads + # nothing, while re-running the failed job uploads a second github-pages + # artifact and then fails on finding two. + # + # No checkout and nothing of the repository runs here. It needs no if of its + # own: when the publish job is skipped, this one is too. + deploy: + needs: publish + permissions: + pages: write + id-token: write + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: + name: github-pages + url: ${{ steps.third.outputs.page_url || steps.second.outputs.page_url || steps.first.outputs.page_url }} + steps: + - id: first + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 + continue-on-error: true + + - name: wait before asking again + if: steps.first.outcome == 'failure' + run: sleep 30 + + - id: second + if: steps.first.outcome == 'failure' + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 + continue-on-error: true + + - name: wait longer before the last try + if: steps.first.outcome == 'failure' && steps.second.outcome == 'failure' + run: sleep 60 + + - id: third + if: steps.first.outcome == 'failure' && steps.second.outcome == 'failure' uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/internal/guard/mutationcoverage_test.go b/internal/guard/mutationcoverage_test.go index 94c07fa4..a3e3602d 100644 --- a/internal/guard/mutationcoverage_test.go +++ b/internal/guard/mutationcoverage_test.go @@ -276,6 +276,13 @@ var provenByProbe = map[string]string{ "TestTheSampleFilesPageOffersAFileOfEveryFormat": "a canary of its own - a planted set missing a format and two " + "sections, with an undamaged corrupt file, has to give every gap. Broken by hand on 2026-11-23 by taking the webp " + "target out of web/samples/samples.yaml, and by taking the checksum-check line out of pages.yml: red both times.", + "TestTheToolVersionCheckReadsNpmInstallAsACommand": "a canary of its own - an npm install that names no version " + + "has to fail the check. Broken by hand on 2026-11-24 by reading npm install as any text holding the words again: " + + "red on the message in npm.yml that stopped the weekly runs of 2026-11-16 and 2026-11-23.", + "TestOneFailingToolVersionCheckLeavesTheOthersRunning": "its canary is the planted failure of the first check. " + + "Broken by hand on 2026-11-24 by ending the run at the first failure again: red, the pins after it unprinted.", + "TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry": "a canary of its own - one job that uploads and " + + "deploys once has to give two problems. Broken by hand on 2026-11-24 by the pages.yml of main that day: red three times.", "TestAReleaseCandidateIsSentNowhereButGitHub": "a canary of its own - a which step that sends whatever it is " + "given has to fail the same cases. Broken by hand on 2026-11-23 by the npm.yml, pypi.yml and docker.yml of " + "main before the change: red six times, each of the three sending a published release candidate and taking " + diff --git a/internal/guard/pagesdeploy_test.go b/internal/guard/pagesdeploy_test.go new file mode 100644 index 00000000..eb84ea92 --- /dev/null +++ b/internal/guard/pagesdeploy_test.go @@ -0,0 +1,119 @@ +package guard + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/goccy/go-yaml" +) + +// pagesStep is the part of a workflow step this guard reads. +type pagesStep struct { + ID string `yaml:"id"` + Uses string `yaml:"uses"` + ContinueOnError bool `yaml:"continue-on-error"` +} + +// pagesJob is the part of a workflow job this guard reads. +type pagesJob struct { + Needs any `yaml:"needs"` + Steps []pagesStep `yaml:"steps"` +} + +// pagesDeployProblems is what is wrong with how a workflow uploads and deploys +// the site: nothing when the deployment runs in a job of its own, after the +// job that uploads, and asks for the artifact more than once. +func pagesDeployProblems(body []byte) []string { + var workflow struct { + Jobs map[string]pagesJob `yaml:"jobs"` + } + if err := yaml.Unmarshal(body, &workflow); err != nil { + return []string{"the workflow does not parse: " + err.Error()} + } + uploads, deploys := map[string]bool{}, map[string][]pagesStep{} + for name, job := range workflow.Jobs { + for _, s := range job.Steps { + switch { + case strings.HasPrefix(s.Uses, "actions/upload-pages-artifact@"): + uploads[name] = true + case strings.HasPrefix(s.Uses, "actions/deploy-pages@"): + deploys[name] = append(deploys[name], s) + } + } + } + if len(uploads) == 0 || len(deploys) == 0 { + return []string{"no job uploads the site or none deploys it, so there is nothing here to check"} + } + var problems []string + for name, steps := range deploys { + if uploads[name] { + problems = append(problems, "the job "+name+" uploads the site and deploys it, and in one job the "+ + "lookup by name misses the artifact uploaded a moment before") + } + needs := map[string]bool{} + switch n := workflow.Jobs[name].Needs.(type) { + case string: + needs[n] = true + case []any: + for _, v := range n { + if s, ok := v.(string); ok { + needs[s] = true + } + } + } + for up := range uploads { + if !needs[up] { + problems = append(problems, "the job "+name+" does not wait for "+up+", which uploads what it deploys") + } + } + if len(steps) < 2 { + problems = append(problems, "the job "+name+" asks for the artifact once, and a lookup that misses it fails the whole run") + continue + } + for _, s := range steps[:len(steps)-1] { + if !s.ContinueOnError { + problems = append(problems, "try "+s.ID+" of "+name+" ends the job when it fails, so the tries after it never run") + } + } + if steps[len(steps)-1].ContinueOnError { + problems = append(problems, "the last try of "+name+" may fail without failing the job, so a site that never went out would look published") + } + } + return problems +} + +// The site is deployed in a job of its own, after the upload, with more than +// one try. +// +// Measured on 2026-11-24: two runs in a row on main failed at deploy-pages +// with every file ready. It listed the sample-files artifact of the earlier +// job and not the github-pages one the same job had uploaded a moment before +// (actions/deploy-pages#451). Re-running the failed job cannot recover it, +// because the re-run uploads a second github-pages artifact. +// +// Its own canary: the job as it stood on main that day, uploading and +// deploying once in the same job, has to be reported. +func TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry(t *testing.T) { + canary := []byte(`jobs: + publish: + steps: + - uses: actions/upload-pages-artifact@abc + - id: deployment + uses: actions/deploy-pages@abc +`) + got := pagesDeployProblems(canary) + if len(got) < 2 { + t.Fatalf("the canary, one job that uploads and deploys once, gave %d problem(s) and has two: %v", len(got), got) + } + + path := filepath.Join(repoRoot(t), ".github", "workflows", "pages.yml") + body, err := os.ReadFile(path) + if err != nil { + t.Skipf("the publishing workflow is not here: %v", err) + } + for _, p := range pagesDeployProblems(body) { + t.Error(p) + } +} diff --git a/internal/guard/toolversions_test.go b/internal/guard/toolversions_test.go new file mode 100644 index 00000000..4ad4a053 --- /dev/null +++ b/internal/guard/toolversions_test.go @@ -0,0 +1,165 @@ +package guard + +import ( + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// toolVersionsDriver runs one function of .github/scripts/tool_versions.py +// without the network, so what the weekly job reads out of the workflows can +// be asked here. It prints JSON: {"pins": {...}} or {"error": "..."}. +const toolVersionsDriver = ` +import json, sys +sys.path.insert(0, sys.argv[1]) +import tool_versions +texts = json.load(open(sys.argv[2], encoding="utf-8")) +if texts is None: + texts = tool_versions.workflow_text() +try: + print(json.dumps({"pins": tool_versions.npm_pins(texts)})) +except RuntimeError as exc: + print(json.dumps({"error": str(exc)})) +` + +// npmPinsOf asks the script which npm pins it reads out of texts, or out of +// the real workflows when texts is nil. +func npmPinsOf(t *testing.T, python string, texts map[string]string) (map[string]string, string) { + t.Helper() + dir := t.TempDir() + in := filepath.Join(dir, "texts.json") + body, err := json.Marshal(texts) + if err != nil { + t.Fatalf("building the texts: %v", err) + } + if err := os.WriteFile(in, body, 0o600); err != nil { + t.Fatalf("writing the texts: %v", err) + } + scripts := filepath.Join(repoRoot(t), ".github", "scripts") + out, err := exec.Command(python, "-B", "-c", toolVersionsDriver, scripts, in).CombinedOutput() + if err != nil { + t.Fatalf("running tool_versions.npm_pins: %v\n%s", err, out) + } + var answer struct { + Pins map[string]string `json:"pins"` + Error string `json:"error"` + } + if err := json.Unmarshal(out, &answer); err != nil { + t.Fatalf("reading what tool_versions.npm_pins printed: %v\n%s", err, out) + } + return answer.Pins, answer.Error +} + +// The weekly check reads npm install as a command, not as words in a sentence. +// +// Measured on 2026-11-24: the runs of 2026-11-16 and 2026-11-23 failed on +// `echo "::error::... would make npm install give people an older tfg"` in +// npm.yml, and that one failure ended the run before it read a single pin, so +// for two weeks the job checked nothing while saying only that. +// +// Its own canary: an install that names no version must still fail, because a +// pin taken off a command would otherwise take the package off the check. +func TestTheToolVersionCheckReadsNpmInstallAsACommand(t *testing.T) { + python := pythonForGate(t) + + real, failure := npmPinsOf(t, python, nil) + if failure != "" { + t.Fatalf("the weekly check fails on the workflows as they are: %s", failure) + } + if len(real) == 0 { + t.Fatal("the weekly check found no npm pin in the workflows, so it would compare nothing with the registry") + } + + for _, c := range []struct { + why string + line string + pins map[string]string + fails bool + }{ + {"a message that mentions npm install", + `echo "::error::staging it would make npm install give people an older tfg"`, map[string]string{}, false}, + {"a step name that mentions npm", + `- name: install from the files, the way npm installs from the registry`, map[string]string{}, false}, + {"files this run built", + `npm install --no-audit --no-fund "../tarballs/$platform" "$main"`, map[string]string{}, false}, + {"a pin after an option that takes a value", + `npm install --prefix "$RUNNER_TEMP/mailparser" mailparser@3.10.0`, map[string]string{"mailparser": "3.10.0"}, false}, + {"a scoped pin after another command", + `run: cd web && npm install @scope/pkg@1.2.3`, map[string]string{"@scope/pkg": "1.2.3"}, false}, + {"an install that names no version", `npm install mailparser`, nil, true}, + {"an install that names no version after run:", `- run: npm install --prefix x mailparser`, nil, true}, + } { + pins, failure := npmPinsOf(t, python, map[string]string{"x.yml": "steps:\n " + c.line + "\n"}) + if c.fails { + if failure == "" { + t.Errorf("%s: %q passed, and a package without a version has to fail the check", c.why, c.line) + } else if !strings.Contains(failure, "pins no version") { + t.Errorf("%s: %q failed for another reason: %s", c.why, c.line, failure) + } + continue + } + if failure != "" { + t.Errorf("%s: %q failed the check: %s", c.why, c.line, failure) + continue + } + if len(pins) != len(c.pins) { + t.Errorf("%s: %q gave the pins %v, and it has %v", c.why, c.line, pins, c.pins) + continue + } + for k, v := range c.pins { + if pins[k] != v { + t.Errorf("%s: %q gave the pins %v, and it has %v", c.why, c.line, pins, c.pins) + } + } + } + t.Logf("%d npm pin(s) in the workflows: %v", len(real), real) +} + +// One check that fails does not hide the others. +// +// Before 2026-11-24 the first failure ended the run, so every pin read after +// it went unread. The canary is the failure itself: the first check is made +// to fail and the pins of every check after it must still be printed. +func TestOneFailingToolVersionCheckLeavesTheOthersRunning(t *testing.T) { + python := pythonForGate(t) + driver := ` +import sys +sys.path.insert(0, sys.argv[1]) +import tool_versions as tv +def broken(*a): + raise RuntimeError("planted failure") +tv.workflow_text = lambda: {} +tv.go_tools = broken +tv.go_toolchain = lambda texts: [("go toolchain", "1.0", "current", None)] +tv.renderer = lambda now: [("renderer", "2.0", "current", None)] +tv.npm_packages = lambda texts, now: [("pkg (npm)", "3.0", "current", None)] +tv.held = lambda texts: [("python", "4.0", "held", None)] +sys.exit(tv.main()) +` + scripts := filepath.Join(repoRoot(t), ".github", "scripts") + out, err := exec.Command(python, "-B", "-c", driver, scripts).CombinedOutput() + code := 0 + if err != nil { + var exit *exec.ExitError + if !errors.As(err, &exit) { + t.Fatalf("running tool_versions.main: %v\n%s", err, out) + } + code = exit.ExitCode() + } + if code != 1 { + t.Errorf("a failed check ended the run with %d, and it has to end with 1\n%s", code, out) + } + said := string(out) + if !strings.Contains(said, "FAIL: planted failure") { + t.Errorf("the failed check is not named in what the run printed:\n%s", said) + } + for _, pin := range []string{"go toolchain", "renderer", "pkg (npm)", "python"} { + if !strings.Contains(said, pin) { + t.Errorf("the run did not print %q after the first check failed, so one failure hid it:\n%s", pin, said) + } + } +}