Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions .github/scripts/tool_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,40 @@ def renderer(now):
# the registry: a path, or a shell variable holding one.
LOCAL_ARGUMENT = (".", "/", "~", "$")

# A file name npm installs as a tarball, with or without a path in front. The
# same suffixes npm-package-arg reads as a file rather than a package name.
NPM_TARBALL = re.compile(r"[.](?:tgz|tar[.]gz|tar)$", re.IGNORECASE)


def shell_commands(line):
"""The simple commands of one shell line, each as its list of words.

Split where the shell would split, at &&, ||, ;, | and the like, and never
inside quotes: a quoted path holding a ; is one word, as it is to the shell.
A redirection does not end a command. It and the file it names are left
out, with the number of a stream before it, so in
`npm install >log mailparser` the package is still a word of the install.
"""
lexer = shlex.shlex(line, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
commands, words, target_next = [], [], False
for token in lexer:
if target_next:
target_next = False
continue
if token and set(token) <= set("<>&") and token not in ("&", "&&"):
target_next = True
if words and words[-1].isdigit():
words.pop()
continue
if token and all(c in lexer.punctuation_chars for c in token):
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
commands.append(words)
words = []
continue
words.append(token)
commands.append(words)
return [c for c in commands if c]


def npm_pins(texts):
"""Every registry package an `npm install` in the workflows names, with its pin.
Expand All @@ -252,24 +286,30 @@ def npm_pins(texts):
for name, text in texts.items():
for line in text.splitlines():
command = re.sub(r"^(-\s*)?run:\s*", "", line.strip())
if command.startswith("#"):
# Only a line where npm install can begin a command is read as
# shell. Any other line, a step name with an apostrophe among
# them, is not shell and must not fail the check.
if not re.search(r"(?:^|[;&|(]\s*)npm\s+install\b", command):
continue
for part in re.split(r"&&|\|\||;|\|", command):
if part.split()[:2] != ["npm", "install"]:
try:
commands = shell_commands(command)
except ValueError as exc:
raise RuntimeError(f"{name} runs an npm install this cannot read ({exc}): {line.strip()}") from exc
for words in commands:
if words[: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:
for word in words[2:]:
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):
# A name starting with @ is a scoped package of the
# registry whatever it ends with, as npm-package-arg reads it.
tarball = NPM_TARBALL.search(word) and not word.startswith("@")
if word.startswith("-") or word.startswith(LOCAL_ARGUMENT) or tarball:
continue
m = re.fullmatch(r"(@?[\w./-]+)@(\d[\w.+-]*)", word)
if not m:
Expand Down
14 changes: 8 additions & 6 deletions .github/workflows/pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
# checked against the SHA256SUMS the page was rendered with before it may go
# out, so the sums a visitor reads are the sums of the bytes they download.
# A job of its own, with nothing but read access, because it builds and runs
# repository code and the job that publishes holds pages: write.
# repository code and the job that deploys holds pages: write.
samples:
if: >-
github.event_name == 'workflow_dispatch' ||
Expand Down Expand Up @@ -84,22 +84,24 @@ jobs:

publish:
needs: samples
# Read access only. It uploads the site, and the deploy job after it is the
# one that publishes. configure-pages only reads the Pages settings here.
permissions:
contents: read
pages: write
id-token: write
pages: read
# A dispatch is a person asking on purpose. Everything else has to be CI
# saying the tree is good, ON THIS REPOSITORY, for a push.
#
# The last two conditions were added on 2026-08-27, the day this project
# started taking pull requests, and they close a hole that opened with it.
# This job runs on workflow_run, which fires in the base repository with the
# base repository's permissions - and it holds pages: write. CI runs on
# base repository's permissions - and the deploy job after it, which runs
# only when this one does, holds pages: write. CI runs on
# pull_request, and the branches filter above matches the branch NAME of the
# run that triggered it, which for a fork is a name the fork chose. A fork
# whose branch is called main, opening a pull request that passes CI, would
# otherwise reach this job, and this job publishes web/public to the project
# website.
# otherwise reach this job, and the two jobs publish web/public to the
# project website.
#
# Nothing here executes repository code, so the exposure was defacement
# rather than anything reaching a secret. That is still not a thing to leave
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ because it turns other people's test suites red.
and the outcome to expect, in every language of the site.
- **A page about the tools on the website.** Checking an archive for zip slip
and zip bombs before unpacking it, and checking or writing SHA-256 checksums.
- **Documentation on the website, in English.** Install, getting started,
every command with every flag and its default, every key of a recipe, every
field of the manifest, every setting of every format, the packages for
pytest and Node, and the desktop window screen by screen. The lists come
from the program when the site is built, so they say what the version you
download does. The documentation page in the other languages leads to them,
with a line about each page in your language.
- **Recipes to download.** Ready recipes for an image upload, a document
upload, a spreadsheet import, archives, email, video and sound, a CI smoke
test and ten thousand files, and every preset as a recipe. Each writes into a
folder of its own name, so several can run one after another.

### Changed

Expand Down
9 changes: 5 additions & 4 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,11 @@ could post a summary comment on a pull request, which would need
`pull-requests: write` - that scope is deliberately not granted, because a failing
check already says what the comment would.

Two workflows hold more. The one that publishes the website has `pages: write`
and `id-token: write`. It has a single job, and it runs only for a push to this
repository - a condition added on 2026-08-27 and held by a guard, because the event
it triggers on fires with this repository's permissions. The weekly vulnerability
Two workflows hold more. In the one that publishes the website, only the last
job, which deploys what the jobs before it built and uploaded, has `pages: write`
and `id-token: write`. Those jobs have read access only. The workflow runs only for
a push to this repository - a condition added on 2026-08-27 and held by a guard,
because the event it triggers on fires with this repository's permissions. The weekly vulnerability
scan has `security-events: write`, on its one job, to put its results in the
Security tab. It runs on a schedule or by hand, never for a pull request.

Expand Down
20 changes: 0 additions & 20 deletions internal/guard/commanddeclaration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,6 @@ import (
// generate, so they get guards - and both are asked with a rule rather than a
// list of exceptions, because a list of exceptions is a guard with a hole.

// commandsTheToolPrints is the command names out of tfg --help, which is the
// text the page is a copy of.
//
// Asked of the help rather than of the router beside it on purpose: the help
// is what a visitor compares the page against, so agreeing with anything else
// would prove the wrong thing.
func commandsTheToolPrints(t *testing.T) []string {
t.Helper()
var out, errOut bytes.Buffer
if code := cli.Run(context.Background(), []string{"--help"}, &out, &errOut); code != cli.ExitOK {
t.Fatalf("tfg --help ended with %d rather than %d, so there is no list to compare against",
code, cli.ExitOK)
}
names, err := commandNamesIn(out.String())
if err != nil {
t.Fatalf("reading the command block out of tfg --help: %v", err)
}
return names
}

// commandNamesIn takes the names out of the Commands: block of a help text.
//
// Split on two spaces rather than on the first one, because "recipe fmt" is a
Expand Down
14 changes: 12 additions & 2 deletions internal/guard/mutationcoverage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,18 @@ var provenByProbe = map[string]string{
"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.",
"TestTheSiteIsDeployedInAJobAfterTheUploadWithMoreThanOneTry": "two canaries of its own, the old layout and a retry " +
"reading the conclusion. Broken by hand on 2026-11-24 by main's pages.yml and by that retry: red both times.",
"TestTheCommandReferenceIsReadFromTheHelp": "a canary help of every shape it reads, and one it cannot. Broken by hand " +
"on 2026-11-24 by reading flags only after three spaces: red.",
"TestTheReferenceDescribesEveryKeyFieldAndRecipe": "a canary of an item without a sentence and a sentence without an " +
"item. Broken by hand on 2026-11-24 by taking files[].send_as out of the English reference: red.",
"TestEveryRecipeOfTheGalleryIsValidAndWritesToItsOwnFolder": "a canary recipe writing into another folder. Broken " +
"by hand on 2026-11-24 by pointing ci-smoke.yaml at ./out: red.",
"TestEveryLanguageLeadsToTheEnglishDocumentation": "the canary of the comparison it shares, and English pages must " +
"exist. Broken by hand on 2026-11-24 by taking one guide out of the Polish language file: red.",
"TestEveryHeldBackAdvisoryHasAnEndDateAndAReason": "a canary of its own - an entry without a date and one without " +
"a reason have to give two problems. Broken by hand on 2026-11-24 by taking one ignoreUntil out of the real file: red.",
"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 " +
Expand Down
164 changes: 164 additions & 0 deletions internal/guard/osvexceptions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
package guard

import (
"fmt"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
"time"
)

// osvKeyValue is one key = value line of a TOML table.
var osvKeyValue = regexp.MustCompile(`^([A-Za-z]+)\s*=\s*(.*)$`)

// osvTableHeader is the header of one held back advisory. TOML allows spaces
// inside the brackets and a comment after them.
var osvTableHeader = regexp.MustCompile(`(?m)^[ \t]*\[\[[ \t]*IgnoredVulns[ \t]*\]\][ \t]*(?:#.*)?$`)

// osvExceptionProblems is what is wrong with the held back advisories of an
// OSV-Scanner configuration: an entry without an id, without a date it stops
// working on, or without a reason.
//
// Read line by line rather than with a TOML parser, which this module only has
// as a dependency of a dependency. The file is flat: one [[IgnoredVulns]]
// table per advisory, with one key per line. An entry written any other way,
// as an inline table, is refused rather than skipped, so it cannot slip past.
func osvExceptionProblems(body string) []string {
var problems []string
heads := osvTableHeader.FindAllStringIndex(body, -1)
if mentions := osvMentions(body); mentions != len(heads) {
problems = append(problems, fmt.Sprintf("IgnoredVulns appears on %d line(s) and %d of them are a table header "+
"this reads, so an entry is written in a layout this guard does not check", mentions, len(heads)))
}
for i, h := range heads {
end := len(body)
if i+1 < len(heads) {
end = heads[i+1][0]
}
problems = append(problems, osvEntryProblems(i+1, osvKeys(body[h[1]:end]))...)
}
return problems
}

// osvMentions is how many lines that are not a comment name IgnoredVulns.
func osvMentions(body string) int {
n := 0
for _, line := range strings.Split(body, "\n") {
if !strings.HasPrefix(strings.TrimSpace(line), "#") && strings.Contains(line, "IgnoredVulns") {
n++
}
}
return n
}

// osvKeys is the keys of one table, up to the next header of any table.
func osvKeys(block string) map[string]string {
keys := map[string]string{}
for _, line := range strings.Split(block, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "[") {
break
}
if m := osvKeyValue.FindStringSubmatch(line); m != nil {
keys[m[1]] = strings.TrimSpace(m[2])
}
}
return keys
}

// osvEntryProblems is what is wrong with entry n.
func osvEntryProblems(n int, keys map[string]string) []string {
var problems []string
id, _ := tomlString(keys["id"])
name := strconv.Quote(id)
if id == "" {
name = "entry " + strconv.Itoa(n)
problems = append(problems, name+" names no advisory")
}
until := keys["ignoreUntil"]
if len(until) < 10 {
problems = append(problems, name+" has no ignoreUntil, so it holds the advisory back for good")
} else if _, err := time.Parse(time.DateOnly, until[:10]); err != nil {
problems = append(problems, name+" has an ignoreUntil that is not a date: "+until)
}
if reason, ok := tomlString(keys["reason"]); !ok || strings.TrimSpace(reason) == "" {
problems = append(problems, name+" gives no reason, and the scan prints the reason beside every advisory it holds back")
}
return problems
}

// tomlString is the text of a TOML string value, with what follows it, a
// comment among them, left out. False when the value is not a string.
func tomlString(v string) (string, bool) {
v = strings.TrimSpace(v)
if strings.HasPrefix(v, "'") {
end := strings.Index(v[1:], "'")
return v[1 : 1+max(end, 0)], end >= 0
}
if !strings.HasPrefix(v, `"`) {
return "", false
}
var b strings.Builder
for i := 1; i < len(v); i++ {
switch c := v[i]; {
case c == '\\' && i+1 < len(v):
b.WriteByte(v[i+1])
i++
case c == '"':
return b.String(), true
default:
b.WriteByte(c)
}
}
return "", false
}

// Every advisory the OSV scan holds back has a date it stops working on and a
// reason.
//
// The date is what brings an advisory back: when it passes, the weekly scan
// goes red again and the entry has to be read again. An entry without one holds
// the advisory back for good and nothing says so. The header of the file
// promises a date for every entry, and nothing else checks that promise.
//
// Its own canary: entries without a date, with an empty reason, with spaces in
// the header and with a comment after an empty reason have to be reported, an
// entry with a # inside its reason must not be, and an inline table is refused.
func TestEveryHeldBackAdvisoryHasAnEndDateAndAReason(t *testing.T) {
canary := `[[IgnoredVulns]]
id = "GHSA-aaaa-aaaa-aaaa"
reason = "held back"

[[IgnoredVulns]]
id = "GHSA-bbbb-bbbb-bbbb"
ignoreUntil = 2026-12-14
reason = ""

[[ IgnoredVulns ]]
id = "GHSA-cccc-cccc-cccc"
reason = "held back"

[[IgnoredVulns]]
id = "GHSA-dddd-dddd-dddd"
ignoreUntil = 2026-12-14
reason = "" # explain later

[[IgnoredVulns]]
id = "GHSA-eeee-eeee-eeee"
ignoreUntil = 2026-12-14
reason = "held back # until the fix ships"
`
if got := osvExceptionProblems(canary); len(got) != 4 {
t.Fatalf("the canary, four broken entries and one whole one, gave %d problem(s) and has four: %v", len(got), got)
}
if got := osvExceptionProblems("IgnoredVulns = [{ id = \"GHSA-ffff-ffff-ffff\" }]\n"); len(got) != 1 {
t.Fatalf("an entry written as an inline table was not refused: %v", got)
}

body := readRepoFile(t, filepath.Join(".github", "osv-scanner.toml"))
for _, p := range osvExceptionProblems(body) {
t.Error(p)
}
}
Loading
Loading