diff --git a/.claude/hooks/verify-on-stop.mjs b/.claude/hooks/verify-on-stop.mjs index 9036624..8c29a36 100644 --- a/.claude/hooks/verify-on-stop.mjs +++ b/.claude/hooks/verify-on-stop.mjs @@ -48,7 +48,7 @@ const TESTS = [ [/^knowledge\/|^bin\/knowledge-|^bin\/lib\/knowledge\.mjs$/, ["knowledge-parity", "knowledge-report"]], [/^blueprint\/sync\.json$|^bin\/(lib\/)?template-sync|^bin\/sync-parity\.mjs$|^workflow-templates\//, ["template-sync", "sync-parity"]], // What the public repository publishes from these must stay counts only. - [/^\.github\/workflows\/(freshness|template-sync)\.yml$|^bin\/template-sync\.mjs$/, ["freshness-public"]], + [/^\.github\/workflows\/(freshness|template-sync)\.yml$|^bin\/template-sync(-pr\.sh|\.mjs)$/, ["freshness-public", "sync-log-public"]], [/^bin\/new-repo\.sh$/, ["new-repo"]], // The guard starters in blueprint/files/ and the push guard's helper are copies of, or used by, the hooks. [/^\.claude\/hooks\/|^bin\/lib\/signed-range\.mjs$|^blueprint\/files\//, ["harness-"]], diff --git a/CLAUDE.md b/CLAUDE.md index 4a13da5..243327c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,7 +38,7 @@ Needs `gh` (repo admin) and `jq`. Validate edits with `bash -n bin/apply-repo-ba ## Blueprint script internals -- This repository is public: `org-audit.yml` publishes counts only (`org-audit.sh --public`), and so does the `copies` job of `freshness.yml` (`template-sync.mjs --public`). Never put per-repository drift, or which copy is behind, in an issue, summary, logs or artifacts: `guard-public-issues.mjs` denies both kinds of line for an org repository name. +- This repository is public: `org-audit.yml` publishes counts only (`org-audit.sh --public`), and so does the `copies` job of `freshness.yml` (`template-sync.mjs --public`). The log of `template-sync.yml` has counts only too: in a workflow run (`GITHUB_ACTIONS=true`) `template-sync.mjs --write` prints `refreshed N copies` and `template-sync-pr.sh` how many files and bytes, and their errors name no file, branch, title or `gh` text; by hand they print the full detail. What a public log still shows is the repository name (from the step environment, the token action and checkout), that a leg ran for it, and the URL of the pull request the script prints itself. `tests/sync-log-public.test.mjs` runs both scripts through their failure paths to hold this. Never put per-repository drift, or which copy is behind, in an issue, summary, logs or artifacts: `guard-public-issues.mjs` denies both kinds of line for an org repository name. - Exit codes: 0 clean, 1 drift in `--check`, 2 usage or a missing tool, 3 any failed call (`trap 'exit 3' ERR`). Keep 1 for drift only: `org-audit.yml` reads 3 as "could not be checked". - `settle LABEL CURRENT DESIRED METHOD PATH [BODY]` is the single compare-then-act primitive: both sides are `jq -S`-normalized and compared; only on mismatch does it diff/print/apply. `pick` reduces live API JSON to just the keys the blueprint file names — so **a blueprint JSON file owns exactly the keys it lists**; adding a key extends what's enforced, keys not listed are never touched. - Rulesets are matched to live ones **by `name`** (POST if absent, PUT by id if present) and compared after `normalize_ruleset` (rules sorted by `type`). Renaming a ruleset in a file creates a second ruleset rather than renaming the old one. diff --git a/bin/template-sync-pr.sh b/bin/template-sync-pr.sh index 41784b5..71c4521 100755 --- a/bin/template-sync-pr.sh +++ b/bin/template-sync-pr.sh @@ -55,12 +55,26 @@ title='ci: refresh workflow copies from the org templates' title_mixed='chore: refresh copies of the org templates and starters' here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" max_bytes=1000000 +# In a workflow run the log of this public repository is readable by anyone. Say how many files and +# bytes, never which files: that is which copy is behind. A run by hand prints the full detail. +ci=0 +if [[ "${GITHUB_ACTIONS:-}" == true ]]; then ci=1; fi die() { printf 'error: %s\n' "$*" >&2 exit 1 } +# A failed `gh` call names the repository, the branch or the pull request title in its message. In a +# workflow that log is public, so the call's stderr is dropped and the script says only that it failed. +gh_() { + if [[ "$ci" == 1 ]]; then + gh "$@" 2>/dev/null || die "a GitHub call failed" + else + gh "$@" + fi +} + cd "$dir" git rev-parse --is-inside-work-tree >/dev/null 2>&1 || die "$dir is not a git checkout" @@ -68,7 +82,7 @@ git rev-parse --is-inside-work-tree >/dev/null 2>&1 || die "$dir is not a git ch # checkout holds no credential. git add -A if git diff --cached --quiet; then - printf '%s: every copy is current: nothing to do\n' "$repo" + if [[ "$ci" == 1 ]]; then printf 'every copy is current: nothing to do\n'; else printf '%s: every copy is current: nothing to do\n' "$repo"; fi exit 0 fi @@ -89,13 +103,24 @@ while IFS= read -r changed; do other+="$changed " fi done < <(git diff --cached --name-only --no-renames) -[[ -z "$other" ]] || die "these changes are neither a workflow file nor a starter a sync may refresh, so none is sent: $other" +if [[ -n "$other" ]]; then + if [[ "$ci" == 1 ]]; then + die "$(wc -w <<<"$other" | tr -d ' ') change(s) are neither a workflow file nor a starter a sync may refresh, so none is sent" + fi + die "these changes are neither a workflow file nor a starter a sync may refresh, so none is sent: $other" +fi [[ "$only_workflows" -eq 1 ]] || title="$title_mixed" # Only a change to a file the repository already has: a sync refreshes, never adds or removes. nonmod="$(git diff --cached --raw --no-renames | awk '$5 != "M" { print $5, $NF }')" -[[ -z "$nonmod" ]] || die "a sync only modifies existing files, got: $nonmod" +if [[ -n "$nonmod" ]]; then + if [[ "$ci" == 1 ]]; then die "a sync only modifies existing files, got $(wc -l <<<"$nonmod" | tr -d ' ') that are not"; fi + die "a sync only modifies existing files, got: $nonmod" +fi bad_mode="$(git diff --cached --raw --no-renames | awk '$2 != "100644" { print $2, $NF }')" -[[ -z "$bad_mode" ]] || die "these files are not plain 100644 files, so the API cannot commit them: $bad_mode" +if [[ -n "$bad_mode" ]]; then + if [[ "$ci" == 1 ]]; then die "$(wc -l <<<"$bad_mode" | tr -d ' ') file(s) are not plain 100644 files, so the API cannot commit them"; fi + die "these files are not plain 100644 files, so the API cannot commit them: $bad_mode" +fi work="$(mktemp -d)" trap 'rm -rf "$work"' EXIT @@ -114,27 +139,39 @@ done < <(git diff --cached --name-only --no-renames -z) ((total <= max_bytes)) || die "the change adds $total bytes, over the $max_bytes the API call is kept to" # Same files, same content: same branch, so a repeated run finds its own pull request. branch="$prefix$(printf '%s' "$fingerprint" | git hash-object --stdin | cut -c1-12)" -printf '%s: %d file(s), %d bytes: %s\n' "$repo" "${#files[@]}" "$total" "${files[*]}" +if [[ "$ci" == 1 ]]; then + printf '%d file(s), %d bytes\n' "${#files[@]}" "$total" +else + printf '%s: %d file(s), %d bytes: %s\n' "$repo" "${#files[@]}" "$total" "${files[*]}" +fi if [[ "$dry_run" == 1 ]]; then - git diff --cached --stat --no-renames - printf 'dry run: would commit %s to %s and open "%s"\n' "$branch" "$repo" "$title" + if [[ "$ci" == 1 ]]; then + printf 'dry run: would commit and open a pull request\n' + else + git diff --cached --stat --no-renames + printf 'dry run: would commit %s to %s and open "%s"\n' "$branch" "$repo" "$title" + fi exit 0 fi -default="$(gh api "repos/$repo" --jq .default_branch)" -base="$(gh api "repos/$repo/git/ref/heads/$default" --jq .object.sha)" +default="$(gh_ api "repos/$repo" --jq .default_branch)" +base="$(gh_ api "repos/$repo/git/ref/heads/$default" --jq .object.sha)" [[ "$(git rev-parse HEAD)" == "$base" ]] || die "$default moved while the run was working: run it again" -existing="$(gh pr list -R "$repo" --head "$branch" --state all --json state --jq 'map(.state) | join(",")')" +existing="$(gh_ pr list -R "$repo" --head "$branch" --state all --json state --jq 'map(.state) | join(",")')" if [[ -n "$existing" ]]; then - printf '%s already has a pull request for these files (%s): not opening another\n' "$repo" "$existing" + if [[ "$ci" == 1 ]]; then + printf 'a pull request for these files already exists (%s): not opening another\n' "$existing" + else + printf '%s already has a pull request for these files (%s): not opening another\n' "$repo" "$existing" + fi exit 0 fi # A branch with no pull request is what a run that failed half way leaves. gh api -X DELETE "repos/$repo/git/refs/heads/$branch" >/dev/null 2>&1 || true -gh api -X POST "repos/$repo/git/refs" -f "ref=refs/heads/$branch" -f "sha=$base" >/dev/null +gh_ api -X POST "repos/$repo/git/refs" -f "ref=refs/heads/$branch" -f "sha=$base" >/dev/null # shellcheck disable=SC2016 # the dollar signs are GraphQL variables query='mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid } } }' if ! jq -n \ @@ -146,12 +183,15 @@ if ! jq -n \ message: {headline: $title, body: $signoff}, expectedHeadOid: $oid, fileChanges: {additions: $additions}}}}' | - gh api graphql --input - >"$work/commit.json"; then + gh api graphql --input - >"$work/commit.json" 2>"$work/commit.err"; then gh api -X DELETE "repos/$repo/git/refs/heads/$branch" >/dev/null 2>&1 || true + if [[ "$ci" == 1 ]]; then die "could not commit the files"; fi + cat "$work/commit.err" >&2 die "could not commit to $branch" fi if jq -e '.errors' "$work/commit.json" >/dev/null 2>&1; then gh api -X DELETE "repos/$repo/git/refs/heads/$branch" >/dev/null 2>&1 || true + if [[ "$ci" == 1 ]]; then die "the API refused the commit ($(jq '.errors | length' "$work/commit.json") error(s))"; fi die "the API refused the commit: $(jq -c '.errors' "$work/commit.json")" fi @@ -163,7 +203,7 @@ body="$( printf 'Each file is the current template or starter for this repository. For a workflow, **the action pins are the template'"'"'s**: a pin can be tied to an input in the same file, so they move together. Dependabot here keeps them current afterwards. Read the diff, as a template change can alter what a workflow does. The required checks run on this pull request as on any other.\n\n' printf 'Opened by `template-sync.yml` in `monte3l/.github`. Rules: [Workflow template sync](https://github.com/monte3l/.github/blob/main/blueprint/README.md#workflow-template-sync).\n' )" -url="$(gh pr create -R "$repo" --head "$branch" --base "$default" --title "$title" --body "$body")" +url="$(gh_ pr create -R "$repo" --head "$branch" --base "$default" --title "$title" --body "$body")" printf 'opened %s\n' "$url" new_number="${url##*/}" @@ -171,10 +211,21 @@ new_number="${url##*/}" # from the current files, but only when the bot alone committed to it. while IFS=$'\t' read -r number; do [[ "$number" != "$new_number" ]] || continue - authors="$(gh pr view "$number" -R "$repo" --json commits --jq '[.commits[].authors[].login] | unique | join(",")')" + authors="$(gh_ pr view "$number" -R "$repo" --json commits --jq '[.commits[].authors[].login] | unique | join(",")')" if [[ "$authors" == "$bot" ]]; then - gh pr close "$number" -R "$repo" --delete-branch --comment "Superseded by $url, which refreshes the same files from the current templates." + if [[ "$ci" == 1 ]]; then + # `gh pr close` reports the pull request's title and the deleted branch: say neither in a public log. + gh pr close "$number" -R "$repo" --delete-branch --comment "Superseded by $url, which refreshes the same files from the current templates." >/dev/null 2>&1 || + die "could not close an older pull request" + printf 'closed an older pull request\n' + else + gh pr close "$number" -R "$repo" --delete-branch --comment "Superseded by $url, which refreshes the same files from the current templates." + fi else - printf 'left #%s open: it has commits by %s\n' "$number" "$authors" + if [[ "$ci" == 1 ]]; then + printf 'left an older pull request open: it has commits by someone else\n' + else + printf 'left #%s open: it has commits by %s\n' "$number" "$authors" + fi fi -done < <(gh pr list -R "$repo" --state open --author "app/monte3l-sync" --json number,headRefName --jq ".[] | select(.headRefName | startswith(\"$prefix\")) | .number") +done < <(gh_ pr list -R "$repo" --state open --author "app/monte3l-sync" --json number,headRefName --jq ".[] | select(.headRefName | startswith(\"$prefix\")) | .number") diff --git a/bin/template-sync.mjs b/bin/template-sync.mjs index a04b9eb..8d80d1d 100755 --- a/bin/template-sync.mjs +++ b/bin/template-sync.mjs @@ -47,6 +47,13 @@ * summary and its logs are readable by anyone. It cannot be combined with --json or * --write, which carry names. * + * In a workflow (GITHUB_ACTIONS=true) the log of a public repository must not say + * which file of which repository is behind. So an error message there names no + * repository, file or `gh` text, whatever the options (the plan job runs it with + * --json), and a --write run prints only how many copies it refreshed. A copy held + * back for its job names is not mentioned there either. The same run by hand prints + * the full table and the full messages. + * * It must not be able to report "nothing found" by failing quietly, because a * workflow closes its tracking issue on that. So it stops with exit 3 when a * repository cannot be read in full (private, renamed, missing) and with exit 2 @@ -94,6 +101,14 @@ for (let i = 0; i < args.length; i++) { } if (publicOutput && (asJson || writeDir !== null)) fail(2, `--public prints counts only, so it cannot be combined with --json or --write\n${USAGE}`); if (writeDir !== null && (only === null || only.length !== 1)) fail(2, `--write needs --repos with exactly one repository\n${USAGE}`); +// In a workflow run (GITHUB_ACTIONS=true) the log of a public repository is readable by anyone, and which +// file of which repository is behind must stay out of it. So under CI an error message names no repository, +// file or `gh` text (`redact`), and a --write leg prints only how many copies it refreshed (`ciWrite`). +// A run by hand keeps the full table and the full messages, which is the audit view. +const inCi = process.env.GITHUB_ACTIONS === "true"; +const redact = publicOutput || inCi; +const ciWrite = writeDir !== null && inCi; +let written = 0; for (const name of [owner, ...(only ?? [])]) if (!NAME_RE.test(name)) fail(2, `not an owner or repository name: ${name}`); const run = (cmd, argv) => execFileSync(cmd, argv, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 16 * 1024 * 1024 }); @@ -183,10 +198,10 @@ function assertReadable(repo) { try { info = JSON.parse(run("gh", ["api", `repos/${owner}/${repo}`, "--jq", "{private, archived}"])); } catch (error) { - if (missing(error)) fail(3, `${publicOutput ? "a repository" : `${owner}/${repo}`} does not exist, or this token cannot see it`); + if (missing(error)) fail(3, `${redact ? "a repository" : `${owner}/${repo}`} does not exist, or this token cannot see it`); throw error; } - if (info.private) fail(3, `${publicOutput ? "a repository" : `${owner}/${repo}`} is private, and this token reads public repositories only`); + if (info.private) fail(3, `${redact ? "a repository" : `${owner}/${repo}`} is private, and this token reads public repositories only`); } const repos = Object.keys(config.repos).filter((name) => only === null || only.includes(name)).sort(); @@ -226,7 +241,7 @@ try { try { current = render(versions[unit.source].current, params); } catch (error) { - fail(3, `${unit.source}: ${error.message}`); + fail(3, redact ? "a template could not be rendered (run it by hand for the detail)" : `${unit.source}: ${error.message}`); } const old = []; for (const version of versions[unit.source].old) { @@ -248,7 +263,9 @@ try { const { unit, found, current } = copy; // Only a workflow has jobs: a starter has no required check to rename. if (unit.kind === "workflow" && jobNames(found.text).join("\n") !== jobNames(current).join("\n")) { - console.error(`template-sync: left out ${repo} ${unit.name}.yml: the refresh would change its job names, which a required check depends on. A person does this one`); + // A copy held back for its job names says so by hand only: in a public log it would tell an outsider + // which repository renamed a required check. The pull request body says a rename is never refreshed. + if (!redact) console.error(`template-sync: left out ${repo} ${unit.name}.yml: the refresh would change its job names, which a required check depends on. A person does this one`); continue; } const target = path.join(writeDir, found.path); @@ -257,12 +274,13 @@ try { // repository that checks its licence headers inline fails on a workflow that lost them. const refreshed = keepHeader(current, found.text); writeFileSync(target, refreshed.endsWith("\n") ? refreshed : `${refreshed}\n`); + written++; } } } } catch (error) { // The message of a failed `gh` call usually holds the repository's path, so a public run leaves it out. - fail(3, publicOutput ? "a read failed (run without --public for the detail)" : `a read failed: ${String(error.stderr ?? error.message).trim().split("\n")[0]}`); + fail(3, publicOutput ? "a read failed (run without --public for the detail)" : redact ? "a read failed (run it by hand for the detail)" : `a read failed: ${String(error.stderr ?? error.message).trim().split("\n")[0]}`); } const stale = results.filter((r) => r.managed && r.state === "STALE"); @@ -287,7 +305,7 @@ const publicSummary = () => { return lines; }; if (findingsFile) { - const lines = publicOutput ? publicSummary() : findings; + const lines = publicOutput || ciWrite ? publicSummary() : findings; writeFileSync(findingsFile, lines.length === 0 ? "" : `${lines.join("\n")}\n`); } @@ -301,6 +319,9 @@ if (publicOutput) { console.log(`unmanaged copies: ${countOf(results.filter((r) => !r.managed && r.state !== "MISSING"))}`); const summary = publicSummary(); console.log(summary.length === 0 ? "\nfindings: none" : `\nfindings:\n${summary.map((line) => ` ${line}`).join("\n")}`); +} else if (ciWrite) { + // A leg exists only for a repository with a stale copy, so even a "behind" count would add nothing to say. + console.log(`refreshed ${plural(written, "copy", "copies")}`); } else if (asJson) { console.log(JSON.stringify({ results, mismatches }, null, 2)); } else { diff --git a/blueprint/README.md b/blueprint/README.md index 0e976d9..118a1ad 100644 --- a/blueprint/README.md +++ b/blueprint/README.md @@ -355,6 +355,29 @@ one. The repository is public and a name would tell an outsider where to aim. Ru `node bin/template-sync.mjs` with `gh` access for the full comparison. Eleven verbatim starters are compared the same way, see [Starters](#starters). +The log of `template-sync.yml` follows the same rule, and a test drives both scripts +through every path it can reach to hold it (`tests/sync-log-public.test.mjs`). In a +workflow run (`GITHUB_ACTIONS=true`): + +- `template-sync.mjs --write` prints only `refreshed N copies`. Its error messages, in + the plan job too, name no repository, file, template or `gh` text. +- A copy held back because its refresh would rename a job is not mentioned in the log. +- `template-sync-pr.sh` prints how many files and bytes, never which files, versions, + branch, title or commit author. A refusal says how many changes it refused, and a + failed `gh` call says only that it failed, with its own message dropped. + +Run by hand, both print the full detail and the full messages: that is the audit view. +What a public log still shows: + +| What | Why | +| --- | --- | +| The repository being refreshed | The step environment, the token action's inputs and `actions/checkout` print it, not these scripts. The names are already public in `sync.json`. | +| That a leg ran for it | A leg exists only for a repository with a stale copy, so its existence says that one is behind. Not which file, how far, or why. | +| The URL of the pull request it opened | The script prints it, and it holds the repository name. The pull request is public in the other repository. | + +A failure that is not one of those cases, such as an uncaught error from `jq`, can still +print what the tool prints. The script does not trap every exit. + The template is first **rendered** for the repository: `https://PROJECT.monte3l.com` becomes its site, and a block between `# sync:if FLAG` and `# sync:end` stays only in a repository that has that flag in `sync.json`. Then the two are diff --git a/tests/harness-hooks.test.mjs b/tests/harness-hooks.test.mjs index f5d4ec9..4f79875 100644 --- a/tests/harness-hooks.test.mjs +++ b/tests/harness-hooks.test.mjs @@ -147,8 +147,9 @@ describe("verify-on-stop planning", () => { assert.deepEqual(plan(["knowledge/wiki/x.md"]).names.sort(), ["knowledge-parity", "knowledge-report"]); assert.ok(plan(["workflow-templates/dco.yml"]).names.includes("template-sync")); assert.deepEqual(plan(["bin/new-repo.sh"]).names, ["new-repo"]); - for (const f of [".github/workflows/freshness.yml", ".github/workflows/template-sync.yml", "bin/template-sync.mjs"]) { + for (const f of [".github/workflows/freshness.yml", ".github/workflows/template-sync.yml", "bin/template-sync.mjs", "bin/template-sync-pr.sh"]) { assert.ok(plan([f]).names.includes("freshness-public"), f); + assert.ok(plan([f]).names.includes("sync-log-public"), f); } // The push guard's helper and the guard starters are what the harness tests run. assert.ok(plan(["bin/lib/signed-range.mjs"]).names.includes("harness-")); @@ -157,6 +158,7 @@ describe("verify-on-stop planning", () => { assert.equal(plan(["docs/ROADMAP.md"]).check, true); const root = path.resolve(hooks, "../.."); assert.ok(testFiles(root, ["freshness-public"]).some((f) => f.endsWith("freshness-public.test.mjs"))); + assert.ok(testFiles(root, ["sync-log-public"]).some((f) => f.endsWith("sync-log-public.test.mjs"))); const files = testFiles(root, plan([".claude/hooks/x.mjs"]).names); assert.ok(files.every((f) => path.basename(f).startsWith("harness-"))); assert.ok(files.length >= 2); diff --git a/tests/sync-log-public.test.mjs b/tests/sync-log-public.test.mjs new file mode 100644 index 0000000..7b81c3b --- /dev/null +++ b/tests/sync-log-public.test.mjs @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 Enrico Lionello (enri3l) and Giulia Montevecchi (giulmonte), monte3l +// SPDX-License-Identifier: MIT + +// The log of the template-sync `open` job is readable by anyone: this repository is public (CLAUDE.md, "counts +// only"). Behavioural ratchet: bin/template-sync-pr.sh runs in a workflow (GITHUB_ACTIONS=true) against a stub +// `gh` that puts a distinctive repository name, file path, branch, title and author into everything it prints, +// including every error, and through every path the stub can reach, the success, the existing pull request, the +// older pull request that is closed or left open, and each failure. None of those strings may reach stdout or +// stderr. The one thing the script prints on its own is the URL of the pull request it opened, which holds the +// repository name, so that line is taken out before the check. The same run by hand must still show them, which +// proves the stub would have caught a leak. A small static check backs it up: a new `$` expansion in a print +// statement has to be reviewed here. +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; + +const root = path.join(import.meta.dirname, ".."); +const script = path.join(root, "bin", "template-sync-pr.sh"); + +const REPO = "m3l-zzleak-repo"; +const FILE = ".github/workflows/zzleak-wf.yml"; +const URL_LINE = new RegExp(`^opened https://github\\.com/monte3l/${REPO}/pull/7$`, "m"); +/** What must never reach a public log. The branch is `chore/template-sync-` plus a hash. */ +const FORBIDDEN = ["ZZLEAK", "zzleak-wf", FILE, "chore/template-sync-", "refresh workflow copies", "refresh copies of the org", "zzleak-author", REPO]; + +const git = (cwd, ...args) => + execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false", ...args], { cwd, encoding: "utf8" }); + +// A stub gh. Every message holds the whole command line, so the repository, the branch and the title are in it. +const STUB = `#!/usr/bin/env bash +args="$*" +fail() { echo "gh: $STUB_FAIL failed: ZZLEAK zzleak-wf.yml zzleak-author $args" >&2; exit 1; } +case "$args" in + "api repos/"*"/git/ref/heads/"*) [[ "$STUB_FAIL" == base ]] && fail; printf '%s\\n' "$STUB_BASE_SHA" ;; + "api -X DELETE "*) ;; + "api -X POST "*) [[ "$STUB_FAIL" == ref ]] && fail; exit 0 ;; + "api graphql"*) + cat >/dev/null + case "$STUB_GRAPHQL" in + fail) fail ;; + errors) echo '{"errors":[{"message":"ZZLEAK zzleak-wf.yml m3l-zzleak-repo chore/template-sync-"}]}' ;; + *) echo '{"data":{"createCommitOnBranch":{"commit":{"oid":"abc"}}}}' ;; + esac ;; + "api repos/"*) [[ "$STUB_FAIL" == default ]] && fail; echo main ;; + "pr list"*"--head"*) [[ "$STUB_FAIL" == existing ]] && fail; printf '%s' "$STUB_EXISTING" ;; + "pr list"*"--author"*) if [[ -n "$STUB_OLD_PR" ]]; then printf '%s\\n' "$STUB_OLD_PR"; fi ;; + "pr view"*) [[ "$STUB_FAIL" == view ]] && fail; printf '%s\\n' "$STUB_OLD_AUTHORS" ;; + "pr create"*) [[ "$STUB_FAIL" == create ]] && fail; echo "https://github.com/monte3l/m3l-zzleak-repo/pull/7" ;; + "pr close"*) + [[ "$STUB_FAIL" == close ]] && fail + echo "✓ Closed pull request monte3l/m3l-zzleak-repo#3 (ZZLEAK refresh workflow copies from the org templates)" + echo "✓ Deleted branch chore/template-sync-ZZLEAK" >&2 ;; + *) echo "unexpected: $args" >&2; exit 1 ;; +esac +`; + +/** + * A consumer checkout with a committed workflow and `after` written over it, then the script run for real (not + * DRY_RUN) against the stub. `after` maps a path to its new text, or to { text, mode }. + */ +function run({ after = { [FILE]: "name: v2\n" }, env = {}, ci = true, dry = false } = {}) { + const dir = mkdtempSync(path.join(tmpdir(), "sync-log-")); + git(dir, "init", "-q"); + mkdirSync(path.join(dir, ".github", "workflows"), { recursive: true }); + writeFileSync(path.join(dir, FILE), "name: v1\n"); + writeFileSync(path.join(dir, "README.md"), "# x\n"); + git(dir, "add", "-A"); + git(dir, "commit", "-q", "-m", "base"); + for (const [rel, value] of Object.entries(after)) { + mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); + const { text, mode } = typeof value === "string" ? { text: value } : value; + writeFileSync(path.join(dir, rel), text); + if (mode) chmodSync(path.join(dir, rel), mode); + } + const bin = mkdtempSync(path.join(tmpdir(), "stub-gh-")); + writeFileSync(path.join(bin, "gh"), STUB); + chmodSync(path.join(bin, "gh"), 0o755); + const result = spawnSync("bash", [script, `monte3l/${REPO}`, dir], { + encoding: "utf8", + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + GH_TOKEN: "stub", + GITHUB_ACTIONS: ci ? "true" : "", + DRY_RUN: dry ? "1" : "", + STUB_BASE_SHA: git(dir, "rev-parse", "HEAD").trim(), + STUB_FAIL: "", + STUB_GRAPHQL: "", + STUB_EXISTING: "", + STUB_OLD_PR: "", + STUB_OLD_AUTHORS: "", + ...env, + }, + }); + return { status: result.status, out: result.stdout, err: result.stderr }; +} + +/** The text the log would carry, without the one line the script writes about the pull request it opened. */ +const logOf = (r) => `${r.out.replace(URL_LINE, "")}\n${r.err}`; +const assertClean = (r, what) => { + const log = logOf(r); + for (const forbidden of FORBIDDEN) assert.ok(!log.includes(forbidden), `${what}: the log names "${forbidden}":\n${log}`); +}; + +const BOT = "monte3l-sync[bot]"; + +test("the success path opens a pull request and closes an older one of the bot, and says neither which file nor which branch", () => { + const r = run({ env: { STUB_OLD_PR: "3", STUB_OLD_AUTHORS: BOT } }); + assert.equal(r.status, 0, r.err); + assert.match(r.out, URL_LINE, "the script prints the URL of the pull request itself"); + assert.match(r.out, /^1 file\(s\), \d+ bytes$/m); + assert.match(r.out, /closed an older pull request/); + assertClean(r, "success"); +}); + +test("an older pull request with a human's commits is left open without naming the human", () => { + const r = run({ env: { STUB_OLD_PR: "3", STUB_OLD_AUTHORS: "zzleak-author" } }); + assert.equal(r.status, 0, r.err); + assert.match(r.out, /left an older pull request open/); + assertClean(r, "left open"); +}); + +test("an existing pull request for the same files is reported without the repository", () => { + const r = run({ env: { STUB_EXISTING: "MERGED" } }); + assert.equal(r.status, 0, r.err); + assert.match(r.out, /a pull request for these files already exists \(MERGED\)/); + assertClean(r, "existing"); +}); + +test("nothing to do is reported without the repository", () => { + const r = run({ after: {} }); + assert.equal(r.status, 0, r.err); + assert.equal(r.out, "every copy is current: nothing to do\n"); +}); + +test("a dry run in a workflow says nothing about the files, the branch or the diff", () => { + const r = run({ dry: true }); + assert.equal(r.status, 0, r.err); + assertClean(r, "dry run"); +}); + +// Every failure, each with the stub putting its own text into the message. +const FAILURES = [ + ["the default branch cannot be read", { STUB_FAIL: "default" }], + ["the base commit cannot be read", { STUB_FAIL: "base" }], + ["the existing pull request cannot be listed", { STUB_FAIL: "existing" }], + ["the branch cannot be created", { STUB_FAIL: "ref" }], + ["the commit call fails", { STUB_GRAPHQL: "fail" }], + ["the commit call answers with errors", { STUB_GRAPHQL: "errors" }], + ["the pull request cannot be created", { STUB_FAIL: "create" }], + ["an older pull request cannot be read", { STUB_OLD_PR: "3", STUB_OLD_AUTHORS: BOT, STUB_FAIL: "view" }], + ["an older pull request cannot be closed", { STUB_OLD_PR: "3", STUB_OLD_AUTHORS: BOT, STUB_FAIL: "close" }], +]; +for (const [what, env] of FAILURES) { + test(`in a workflow, when ${what}, the log says it failed and names nothing`, () => { + const r = run({ env }); + assert.notEqual(r.status, 0, "the run fails"); + assert.match(logOf(r), /error: .+/, "and says so"); + assertClean(r, what); + }); +} + +// A change set the script refuses: it says how many, never which. +test("in a workflow a path that is not allowed is counted, not named", () => { + const r = run({ after: { [FILE]: "name: v2\n", "zzleak-other/secret.txt": "x\n" } }); + assert.notEqual(r.status, 0); + assert.match(r.err, /1 change\(s\) are neither a workflow file nor a starter/); + assertClean(r, "not allowed"); +}); + +test("in a workflow a file that is added, not modified, is counted, not named", () => { + const r = run({ after: { [FILE]: "name: v2\n", ".github/workflows/zzleak-new.yml": "name: n\n" } }); + assert.notEqual(r.status, 0); + assert.match(r.err, /only modifies existing files, got 1 that are not/); + assertClean(r, "added"); +}); + +test("in a workflow a file that is not a plain file is counted, not named", () => { + const r = run({ after: { [FILE]: { text: "name: v2\n", mode: 0o755 } } }); + assert.notEqual(r.status, 0); + assert.match(r.err, /1 file\(s\) are not plain 100644 files/); + assertClean(r, "mode"); +}); + +// By hand the detail is there: the stub's text does reach the log, so the checks above could have failed. +test("by hand the same failures show the repository, the file, the branch and the message", () => { + const graphql = run({ ci: false, env: { STUB_GRAPHQL: "fail" } }); + assert.notEqual(graphql.status, 0); + assert.match(graphql.err, /ZZLEAK/, "gh's own message"); + assert.match(graphql.err, /could not commit to chore\/template-sync-/); + const other = run({ ci: false, after: { [FILE]: "name: v2\n", "zzleak-other/secret.txt": "x\n" } }); + assert.match(other.err, /zzleak-other\/secret\.txt/); + const ok = run({ ci: false, env: { STUB_OLD_PR: "3", STUB_OLD_AUTHORS: BOT } }); + assert.equal(ok.status, 0, ok.err); + assert.match(ok.out, new RegExp(`monte3l/${REPO}: 1 file\\(s\\), \\d+ bytes: ${FILE.replaceAll(".", "\\.")}`)); + assert.match(ok.out, /ZZLEAK/, "gh pr close's own report"); +}); + +// A backstop for what the stub cannot reach. A `$` expansion in a statement that prints is either reviewed here +// as safe in a public log, or it is by-hand only and must sit in the `else` of the `$ci` check (or follow an +// `if [[ "$ci" == 1 ]]` that ends in its own message). A new expansion fails this test until it is placed. +const lines = readFileSync(script, "utf8").split("\n"); +const PRINTS = /\b(printf|echo|cat|tee|die)\b|>&2/; +/** Safe in a public log: constants, counts, the URL the script prints itself, and gh's stderr only under `$ci`. */ +const SAFE = new Set([ + "${0##*/}", "$*", "$@", "$dir", "$ci", "$total", "$max_bytes", "${#files[@]}", "$url", "$existing", "$prefix", "$default", "$base", + "$(git rev-parse HEAD)", "$(wc -w <<<\"$other\" | tr -d ' ')", "$(wc -l <<<\"$nonmod\" | tr -d ' ')", "$(wc -l <<<\"$bad_mode\" | tr -d ' ')", + "$(jq '.errors | length' \"$work/commit.json\")", "$(printf '%s' \"$fingerprint\" | git hash-object --stdin | cut -c1-12)", "$work", +]); +// The usage error names the argument it was given, before anything runs: it is not a repository the sync found. +const ARGUMENT_ERROR = /is not a monte3l repository/; +// The body of the pull request is public in the other repository, not a log. +const PR_BODY = /for path in "\$\{files\[@\]\}"; do printf/; + +test("every expansion in a print statement is reviewed as safe, or sits on the by-hand side of the $ci check", () => { + let scanned = 0; + lines.forEach((line, i) => { + if (line.trim().startsWith("#") || !PRINTS.test(line) || PR_BODY.test(line) || ARGUMENT_ERROR.test(line)) return; + const expansions = [...line.matchAll(/\$(?:\{[^}]*\}|\((?:[^()]|\([^()]*\))*\)|[A-Za-z_]\w*|\*|@)/g)].map((m) => m[0]); + const unreviewed = expansions.filter((e) => !SAFE.has(e)); + if (unreviewed.length === 0) return; + scanned++; + const before = lines.slice(Math.max(0, i - 9), i).map((l) => l.trim()); + const oneLiner = /\$ci" == 1 \]\]; then .*; else /.test(line); + const afterElse = before.includes("else"); + const afterCiMessage = before.slice(-4).some((l) => /if \[\[ "\$ci" == 1 \]\]; then/.test(l)); + assert.ok(oneLiner || afterElse || afterCiMessage, `line ${i + 1} prints ${unreviewed.join(" ")} outside the by-hand side of $ci: ${line.trim()}`); + }); + assert.ok(scanned >= 8, "the scan found the by-hand lines: the patterns are stale"); +}); + +test("template-sync.mjs decides what an error says from GITHUB_ACTIONS in one place", () => { + const text = readFileSync(path.join(root, "bin", "template-sync.mjs"), "utf8"); + assert.equal((text.match(/process\.env\.GITHUB_ACTIONS/g) ?? []).length, 1, "one decision, not several"); + assert.match(text, /const redact = publicOutput \|\| inCi;/); +}); diff --git a/tests/template-sync-cli.test.mjs b/tests/template-sync-cli.test.mjs index 1a19ccd..269755a 100644 --- a/tests/template-sync-cli.test.mjs +++ b/tests/template-sync-cli.test.mjs @@ -78,13 +78,18 @@ esac return { dir, bin }; } -function runSync({ dir, bin }, ...args) { +// A run by hand: GITHUB_ACTIONS is cleared, because these tests also run in a workflow, where it is "true" +// and a --write run prints counts only. +const runSync = (setup, ...args) => runSyncIn("", setup, ...args); +const runSyncInCi = (setup, ...args) => runSyncIn("true", setup, ...args); + +function runSyncIn(githubActions, { dir, bin }, ...args) { const out = path.join(dir, "out"); const findings = path.join(dir, "findings.txt"); const result = spawnSync("node", [path.join(dir, "bin", "template-sync.mjs"), "--repos", "m3l-x", "--findings", findings, ...args.map((a) => (a === "OUT" ? out : a))], { cwd: dir, encoding: "utf8", - env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, GITHUB_ACTIONS: githubActions }, }); return { status: result.status, out: result.stdout, err: result.stderr, written: (rel) => (existsSync(path.join(out, rel)) ? readFileSync(path.join(out, rel), "utf8") : null), findings: existsSync(findings) ? readFileSync(findings, "utf8") : null }; } @@ -453,3 +458,96 @@ esac assert.match(failed.err, /a read failed \(run without --public/); assert.doesNotMatch(failed.err, /m3l-x/); }); + +// The log of a public repository is readable by anyone. A --write run in a workflow (GITHUB_ACTIONS=true) says +// how many copies it refreshed and never which file is behind or by how many versions. By hand it still +// prints the full table, which is the audit view. +test("a --write run in a workflow prints counts only, and still writes the file", () => { + const env = setup({ consumer: { ".github/workflows/t.yml": WORKFLOW, "conf/x.toml": V1 } }); + const r = runSyncInCi(env, "--write", "OUT"); + assert.equal(r.status, 0, r.err); + assert.equal(r.written("conf/x.toml"), V2, "the refresh is still written"); + assert.equal(r.out, "refreshed 1 copy\n", "nothing else: not a table, not a count of what is behind"); + for (const secret of ["conf/x.toml", "x.toml", "m3l-x", "version behind", "S1"]) { + assert.ok(!r.out.includes(secret), `stdout names "${secret}"`); + assert.ok(!r.err.includes(secret), `stderr names "${secret}"`); + assert.ok(!r.findings.includes(secret), `the findings file names "${secret}"`); + } + // The log says nothing about what is behind or held back. The findings file is not a log: it holds counts. + for (const hint of ["behind", "left out"]) { + assert.ok(!r.out.includes(hint) && !r.err.includes(hint), `the log says "${hint}"`); + } +}); + +test("the same --write run by hand still prints the table and the finding line", () => { + const env = setup({ consumer: { ".github/workflows/t.yml": WORKFLOW, "conf/x.toml": V1 } }); + const r = runSync(env, "--write", "OUT"); + assert.equal(r.status, 0, r.err); + assert.match(r.out, /x\.toml\s+S1/); + assert.match(r.out, /m3l-x: conf\/x\.toml is 1 version behind its starter/); + assert.equal(r.findings, "m3l-x: conf/x.toml is 1 version behind its starter\n"); +}); + +test("a workflow left out for its job names is said by hand and not mentioned in a workflow", () => { + const env = setup({ consumer: { ".github/workflows/t.yml": WORKFLOW } }); + // The template now has another job name than the copy, which still matches an older version of it. + put(env.dir, "workflow-templates/t.yml", "name: t\njobs:\n a:\n name: B\n"); + git(env.dir, "commit", "-q", "-am", "rename the job"); + const ci = runSyncInCi(env, "--write", "OUT"); + assert.equal(ci.status, 0, ci.err); + assert.equal(ci.written(".github/workflows/t.yml"), null, "a refresh that renames a job is not written"); + assert.equal(ci.err, "", "a rename hold would tell an outsider which repository renamed a required check"); + assert.equal(ci.out, "refreshed 0 copies\n"); + const hand = runSync(env, "--write", "OUT"); + assert.match(hand.err, /left out m3l-x t\.yml/); +}); + +test("a failed read in a workflow names no repository", () => { + const env = setup({ consumer: { ".github/workflows/t.yml": WORKFLOW } }); + writeFileSync(path.join(env.bin, "gh"), `#!/usr/bin/env bash\n[[ "$1" == "--version" ]] && { echo "gh version stub"; exit 0; }\necho "gh: repos/monte3l/m3l-x failed (HTTP 500)" >&2\nexit 1\n`); + const ci = runSyncInCi(env, "--write", "OUT"); + assert.equal(ci.status, 3); + assert.doesNotMatch(ci.err, /m3l-x/); + const hand = runSync(env, "--write", "OUT"); + assert.match(hand.err, /m3l-x/); +}); + +// Behavioural: every failure the CLI can reach, in a workflow, whatever the options. The stub gh puts a +// distinctive repository name, path and message into everything it says, so a message that passes `gh`'s text +// or a name through shows up. The plan job runs the CLI with --json and no --write, so that is covered too. +const LEAKS = ["ZZLEAK", "m3l-x", "monte3l/m3l-x", "zzleak/path.yml"]; +const ghStub = (body) => `#!/usr/bin/env bash\n[[ "$1" == "--version" ]] && { echo "gh version stub"; exit 0; }\n${body}\n`; +const assertNoLeak = (r, what) => { + for (const leak of LEAKS) { + assert.ok(!r.out.includes(leak), `${what}: stdout names "${leak}": ${r.out}`); + assert.ok(!r.err.includes(leak), `${what}: stderr names "${leak}": ${r.err}`); + } +}; + +for (const options of [["--write", "OUT"], ["--json"], ["--check"], []]) { + test(`in a workflow a failure names no repository, path or gh text (${options.join(" ") || "no options"})`, () => { + const failures = { + "a private repository": 'case "$2" in repos/monte3l/m3l-x) printf \'{"private":true,"archived":false}\' ;; *) echo "ZZLEAK private zzleak/path.yml" >&2; exit 1 ;; esac', + "a missing repository": 'echo "gh: Not Found (HTTP 404) repos/monte3l/m3l-x ZZLEAK zzleak/path.yml" >&2; exit 1', + "a failed read": 'case "$2" in repos/monte3l/m3l-x) printf \'{"private":false,"archived":false}\' ;; *) echo "gh: repos/monte3l/m3l-x/contents/zzleak/path.yml failed (HTTP 500) ZZLEAK" >&2; exit 1 ;; esac', + }; + for (const [what, body] of Object.entries(failures)) { + const env = setup({ consumer: { ".github/workflows/t.yml": WORKFLOW } }); + writeFileSync(path.join(env.bin, "gh"), ghStub(body)); + const r = runSyncInCi(env, ...options); + assert.notEqual(r.status, 0, `${what} stops the run`); + assertNoLeak(r, what); + } + }); +} + +test("in a workflow a template that cannot be rendered names no source", () => { + const env = setup({ consumer: { ".github/workflows/t.yml": WORKFLOW } }); + put(env.dir, "workflow-templates/t.yml", "name: t\n# sync:end\njobs:\n a:\n name: A\n"); + git(env.dir, "commit", "-q", "-am", "break the template"); + const ci = runSyncInCi(env, "--json"); + assert.equal(ci.status, 3); + assert.doesNotMatch(ci.err, /t\.yml|workflow-templates|sync:end/); + const hand = runSync(env, "--json"); + assert.match(hand.err, /workflow-templates\/t\.yml/, "by hand the source and the reason are named"); +}); diff --git a/tests/template-sync-pr.test.mjs b/tests/template-sync-pr.test.mjs index 18d4352..1ddb6fa 100644 --- a/tests/template-sync-pr.test.mjs +++ b/tests/template-sync-pr.test.mjs @@ -27,9 +27,11 @@ const git = (cwd, ...args) => * allowed paths can be varied; `repo` is the repository name it is asked about. * @param {Record} before * @param {Record} after - * @param {{ config?: object | string, repo?: string }} [options] + * `ci` runs it as a workflow does (GITHUB_ACTIONS=true), where the log is public. GITHUB_ACTIONS is cleared otherwise, + * because these tests also run in a workflow. + * @param {{ config?: object | string, repo?: string, ci?: boolean }} [options] */ -function sync_(before, after, { config, repo = "m3l-x" } = {}) { +function sync_(before, after, { config, repo = "m3l-x", ci = false } = {}) { const dir = mkdtempSync(path.join(tmpdir(), "consumer-")); git(dir, "init", "-q"); const write = (rel, text, mode) => { @@ -50,7 +52,7 @@ function sync_(before, after, { config, repo = "m3l-x" } = {}) { writeFileSync(path.join(tree, "blueprint", "sync.json"), typeof config === "string" ? config : JSON.stringify(config)); run = path.join(tree, "bin", "template-sync-pr.sh"); } - const result = spawnSync("bash", [run, `monte3l/${repo}`, dir], { encoding: "utf8", env: { ...process.env, DRY_RUN: "1" } }); + const result = spawnSync("bash", [run, `monte3l/${repo}`, dir], { encoding: "utf8", env: { ...process.env, DRY_RUN: "1", GITHUB_ACTIONS: ci ? "true" : "" } }); return { status: result.status, out: result.stdout, err: result.stderr }; } @@ -169,3 +171,32 @@ test("a sync.json that cannot be read stops the script with its own message", () assert.equal(status, 1); assert.match(err, /cannot read the allowed paths from blueprint\/sync\.json/); }); + +// The log of a public repository is readable by anyone: in a workflow the script says how many files and bytes, +// and never which files, since that is which copy is behind. By hand it prints them, for the person auditing. +test("in a workflow the log has the counts and no file path, repository or title", () => { + const { status, out, err } = sync_(BASE, { ".gitleaks.toml": "# new\n", ".editorconfig": "root = false\n" }, { ci: true }); + assert.equal(status, 0, err); + assert.match(out, /^2 file\(s\), \d+ bytes$/m); + for (const named of [".gitleaks.toml", ".editorconfig", "m3l-x", "monte3l/", MIXED_TITLE, "chore/template-sync-"]) { + assert.ok(!out.includes(named), `the log names "${named}": ${out}`); + assert.ok(!err.includes(named), `stderr names "${named}": ${err}`); + } + assert.match(out, /dry run: would commit and open a pull request/); + assert.doesNotMatch(out, /\|\s+\d+ [+-]/, "no `git diff --stat` file table"); +}); + +test("by hand the log names the repository and every file, and shows the diff stat", () => { + const { status, out, err } = sync_(BASE, { ".gitleaks.toml": "# new\n", ".editorconfig": "root = false\n" }); + assert.equal(status, 0, err); + assert.match(out, /monte3l\/m3l-x: 2 file\(s\), \d+ bytes: .*\.gitleaks\.toml/); + assert.match(out, /\.editorconfig/); + assert.match(out, /would commit chore\/template-sync-\w+ to monte3l\/m3l-x and open "/); +}); + +test("in a workflow an unchanged copy says so without naming the repository", () => { + const { status, out } = sync_(BASE, {}, { ci: true }); + assert.equal(status, 0); + assert.equal(out, "every copy is current: nothing to do\n"); + assert.equal(sync_(BASE, {}).out, "monte3l/m3l-x: every copy is current: nothing to do\n"); +});