Files
msd-core/tests/update-workflow.test.cjs
Tom Boucher 69e7afd0c7 chore(#3212): bounded quantifiers over document content — prohibition with teeth — Phase 4 (#3441)
* feat(#3415): ship local/no-unbounded-quantifier, burn down ReDoS class

Phase 4 of epic #3212 (ADR-3212 §5/§7, the final phase). New rule flags
an unbounded */+/{n,} quantifier over a broad character class
([\s\S], dotAll ., or a 1-2-unit negated class like [^\n]/[^)\n] — the
exact #2128-fixed shape) applied to a regex whose match target is
data-flow-traced to readFileSync content.

eslint-rules/lib/readfilesync-trace.cjs extracts the data-flow tracer
shared with no-crlf-fragile-split (Phase 2) rather than a second copy
— no-crlf-fragile-split refactored onto it with zero behavior change,
parity-tested.

Real triage, not 798 mechanical edits: the ADR's census (2026-08-08)
screened every unbounded quantifier in the tree unscoped. Correctly
scoped to readFileSync-derived content (matching Phase 2's own G2/G3
scoping), the rule found 162 real hits across two detection waves — the
second wave (93) surfaced only after a genuine off-by-one bug in this
rule's own first draft was caught while writing its RuleTester tests
and fixed (the bug silently missed every directly-quantified [\s\S]*
with no gap before the quantifier — exactly the class this rule exists
to catch). 3 hits landed in production src/ (commands.cts, milestone.cts,
roadmap.cts) and were each empirically timed against adversarial input
(matching #2128's own measured-not-assumed precedent) — all confirmed
linear-time/benign, left unbounded with a measured-evidence comment
rather than mechanically bounded. The remaining 159 are test-file
fixture parsing (test-author-controlled, fixed-size content, not
adversarial input) — each suppressed with a specific, non-generic
reason. Zero functional behavior changed anywhere in this diff.

tests/no-pending-3212-markers.test.cjs locks the epic's own closing
invariant (ADR §7: "assert zero pending #3212 markers remain") — ground
truth confirmed trivially true today (no phase left any such marker
behind), now regression-locked going forward.

Design: .gsd/phase/chore-3415-prohibition-with-teeth/40-design.md
Test matrix: .gsd/phase/chore-3415-prohibition-with-teeth/50-test-matrix.md

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#3415): correct rule category mislabel, add CI test-scope entry

An orthogonal Standards-axis review found eslint-rules/no-unbounded-quantifier.cjs
mistakenly carried meta.docs.category: 'Portability', copied from a sibling
rule without realizing what that implied: docs/contributing/cross-platform-
portability-rules.md governs an ADR-1703 rule family under a hard "zero
escape hatches" contract (tests/portability-rule-disable-ban.test.cjs's
PROTECTED_RULES bans eslint-disable for those rules entirely). This rule is
not part of that family — it's ADR-3212 (ReDoS/CWE-1333), a different epic —
and its eslint-disable-next-line suppressions (159 of them, added earlier
this same phase after empirical benign-verification) are an intentional,
correct design, not a bypass. Corrected to category: 'Best Practices',
matching the actual precedent (no-adhoc-regex-escape.cjs, Phase 1 of the
same epic, which is also correctly outside PROTECTED_RULES), and the rule's
own docstring now states this explicitly so a future reader doesn't have to
re-derive it.

Also registers a new scripts/ci-test-scope.cjs bucket so editing this rule
or the shared eslint-rules/lib/readfilesync-trace.cjs helper re-runs their
own test suites under targeted CI selection — was previously unregistered
and invisible to that fast-path (this PR's own gsd-test checkpoint runs the
full suite regardless, so this only affects future narrowly-scoped PRs).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#3415): bound no-unbounded-quantifier's own scanner (CWE-1333, ironic)

Security review found the rule meant to catch algorithmic-complexity bugs
had one of its own: hasUnboundedBroadQuantifier's negated-class inner
scan walked from each `[^` occurrence to the next `]` (or EOF) with no
bound, while the outer loop only ever advanced by one character — O(n²)
total work on a pattern with many unclosed `[^` runs. Runs unconditionally
inside checkPattern on any `new RegExp('literal string')` argument in any
linted file, before the (cheap) readFileSync data-flow gate — so a single
crafted string literal, no valid regex syntax required, could make
`npm run lint` / CI hang.

Empirically confirmed both the bug and the fix: pre-fix, n=4000/8000/
16000/32000 chars took 30.8/115.6/463.8/1874.3ms (~4x work per 2x n,
quadratic); extrapolated, the 300000-char repro from the finding would
run ~165s. Post-fix (bail the inner scan once units exceeds the rule's
own 1-2-unit scope, rather than continuing to hunt for a closing `]`),
the same 300000-char input runs in 8.7ms via the real rule module,
independently reconfirmed at 18ms via a fresh Linter.verify() call.

New regression row in tests/no-unbounded-quantifier.rule.test.cjs
asserts the RuleTester run on a 50000-char adversarial pattern
completes and returns a defined result — no wall-clock assertion
(CLAUDE.md Clock Seams / local/no-elapsed-assertion).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#3415): triage 3 new sites, re-raise ceiling after upstream batch

next merged 12 more PRs during this PR's review. Two consequences:

- tests/edit-phase.test.cjs (fix #3262, unrelated) added 3 new
  content.match(/<tag>([\s\S]*?)<\/tag>/) reads of this repo's own
  workflow .md content — the same Class A pattern as the ~159 sites
  already triaged elsewhere in this PR. Suppressed with the same
  established reason.
- lint-allow-test-rule-refs' ratchet ceiling needed re-raising again
  (301 -> 303) for the same reason as the two prior bumps: organic
  growth from unrelated, already-reviewed PRs landing concurrently,
  not a defect in this branch's own diff.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 10:02:28 -04:00

237 lines
11 KiB
JavaScript

/**
* Regression (#498, adversarial-review finding): the custom-file backup step in
* update.md must derive RUNTIME_DIR from GSD_DIR.
*
* The get_installed_version step was rewritten to call `gsd-tools update-context`
* and now emits GSD_DIR (the resolved config dir) instead of the old probe-loop
* variables LOCAL_DIR / GLOBAL_DIR. The backup_custom_files step still read
* LOCAL_DIR / GLOBAL_DIR, which are no longer assigned anywhere — so RUNTIME_DIR
* went empty for every LOCAL/GLOBAL install and detect-custom-files was skipped.
* Because the update then runs a clean install that wipes managed dirs
* (commands/gsd, gsd-core), user-added files inside those dirs could be
* deleted without the intended backup.
*
* This locks the fix: RUNTIME_DIR comes from GSD_DIR, and the dead LOCAL_DIR /
* GLOBAL_DIR references are gone.
*
* Source-text-is-the-product: update.md's bash blocks ARE the deployed /gsd:update
* program; asserting their shape is asserting on the deployed contract.
*/
// allow-test-rule: source-text-is-the-product (#3338)
// update.md's bash blocks ARE the deployed /gsd:update program; asserting
// their shape is asserting on the deployed contract. The data-loss behavior
// only manifests against a real install during a clean reinstall, which CI
// does not perform.
'use strict';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const UPDATE_MD = path.join(__dirname, '..', 'gsd-core', 'workflows', 'update.md');
function codeOnly(file) {
// Strip fenced-block prose is unnecessary here; we assert on the whole doc
// but ignore markdown comment prose by only matching shell-assignment forms.
return fs.readFileSync(file, 'utf8');
}
describe('#498 regression: update.md backup uses GSD_DIR, not the removed LOCAL_DIR/GLOBAL_DIR', () => {
const src = codeOnly(UPDATE_MD);
test('RUNTIME_DIR is assigned from GSD_DIR', () => {
assert.match(
src,
/RUNTIME_DIR="\$GSD_DIR"/,
'backup_custom_files must set RUNTIME_DIR="$GSD_DIR" (the resolved config dir from update-context)',
);
});
test('no shell assignment reads the removed LOCAL_DIR/GLOBAL_DIR probe variables', () => {
// The get_installed_version rewrite no longer assigns LOCAL_DIR/GLOBAL_DIR.
// Any RUNTIME_DIR="$LOCAL_DIR" / "$GLOBAL_DIR" would silently resolve to empty.
assert.doesNotMatch(
src,
/="\$(LOCAL_DIR|GLOBAL_DIR)"/,
'update.md still reads LOCAL_DIR/GLOBAL_DIR, which get_installed_version no longer sets — backup will be skipped',
);
});
test('detect-custom-files stays gated on a non-empty RUNTIME_DIR', () => {
assert.match(
src,
/\[ -n "\$RUNTIME_DIR" \][\s\S]*?detect-custom-files --config-dir "\$RUNTIME_DIR"/,
'backup must still skip when RUNTIME_DIR is empty (UNKNOWN scope)',
);
});
});
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/issue-815-update-next-channel.test.cjs (#3338 H3 Wave 6)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe('folded:issue-815-update-next-channel', () => {
// allow-test-rule: source-text-is-the-product (#3338)
// Reads product workflow/command markdown to verify the --next RC channel
// contract.
// Issue #815: `/gsd-update --next` (alias `--rc`) must thread the @next dist-tag
// through the whole update flow (version check + install) while leaving the
// default @latest path unchanged.
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ROOT815 = path.join(__dirname, '..');
const WF = fs.readFileSync(path.join(ROOT815, 'gsd-core', 'workflows', 'update.md'), 'utf8');
const CMD = fs.readFileSync(path.join(ROOT815, 'commands', 'gsd', 'update.md'), 'utf8');
test('issue #815: workflow parses --next/--rc into a TAG channel', () => {
assert.match(WF, /--next/);
assert.match(WF, /--rc/);
assert.match(WF, /TAG="next"/);
assert.match(WF, /TAG="latest"/);
});
test('issue #815: version check threads the tag through check-latest-version.cjs', () => {
// The script path is double-quoted in the shell command, so the line is:
// node "$GSD_DIR/gsd-core/bin/check-latest-version.cjs" --json --tag "$TAG"
// The closing " on the script path sits between .cjs and --json.
assert.match(WF, /check-latest-version\.cjs"? --json --tag "\$TAG"/);
});
test('issue #815: install uses the selected tag, not a hardcoded @latest', () => {
const robust = WF.match(/npx -y --package=@opengsd\/gsd-core@"\$TAG" -- gsd-core/g) || [];
assert.ok(robust.length >= 3, `expected >=3 tag-parameterized npx invocations, found ${robust.length}`);
assert.doesNotMatch(WF, /--package=@opengsd\/gsd-core@latest -- gsd-core/,
'install lines must not hardcode @latest once --next exists');
assert.doesNotMatch(WF, /--package=@opengsd\/gsd-core@(?:latest|next|beta|canary|rc) -- gsd-core/,
'install lines must use the $TAG variable, never a hardcoded dist-tag literal');
});
test('issue #815: command documents --next/--rc and routes it to the update workflow', () => {
assert.match(CMD, /--next/);
assert.match(CMD, /--rc/);
assert.match(CMD, /argument-hint:.*--next/);
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-2470-update-md-claude-path.test.cjs — consolidation epic #1969 (B4 #1973)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-2470-update-md-claude-path (consolidation epic #1969 B4 #1973)", () => {
// allow-test-rule: source-text-is-the-product (see #2470)
// Workflow .md / agent .md / command .md / reference .md files — their text
// IS what the runtime loads. Testing text content tests the deployed contract.
// Per CONTRIBUTING.md exception matrix.
/**
* Regression test for #2470.
*
* update.md is installed into every runtime directory including .gemini, .codex,
* .opencode, etc. The installer's scanForLeakedPaths() uses the regex
* /(?:~|\$HOME)\/\.claude\b/g to detect unresolved .claude path references after
* copyWithPathReplacement() runs. The replacer handles "~/.claude/" (trailing slash)
* but not "~/.claude" (bare, no trailing slash) — so any bare reference in
* update.md would slip through and trigger the installer warning for non-Claude runtimes.
*/
const { test: __t2470, describe: __d2470 } = require('node:test');
const assert2470 = require('node:assert/strict');
const fs2470 = require('fs');
const path2470 = require('path');
const UPDATE_MD_2470 = path2470.join(__dirname, '..', 'gsd-core', 'workflows', 'update.md');
__d2470('update.md — no bare ~.claude path references (#2470)', () => {
const content = fs2470.readFileSync(UPDATE_MD_2470, 'utf-8');
__t2470('update.md does not contain bare ~/\\.claude (without trailing slash)', () => {
// This is the exact pattern from the installer's scanForLeakedPaths():
// /(?:~|\$HOME)\/\.claude\b/g
// The replacer handles ~/\.claude\/ (with trailing slash) but misses bare ~/\.claude
// so we must not have bare references in the source file.
const matches = content.match(/(?:~|\$HOME)\/\.claude(?!\/)/g);
assert2470.strictEqual(
matches,
null,
`update.md must not contain bare ~/.claude (without trailing slash) — installer scanner flags these as unresolved path refs: ${JSON.stringify(matches)}`
);
});
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-3130-update-npx-robust-invocation.test.cjs — consolidation epic #1969 (B4 #1973)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-3130-update-npx-robust-invocation (consolidation epic #1969 B4 #1973)", () => {
// allow-test-rule: source-text-is-the-product (see #3130)
// Reads product workflow markdown (update.md) to verify structural
// invocation contract.
// Regression guard for bug #3130.
//
// Two failure modes were observed with the pre-fix npx invocation form:
// 1. Cache-stale: bare `npx -y @opengsd/gsd-core@<tag>` hits npx's local
// cache and may pull an older version instead of the target tag.
// 2. Token-routing: Bash-tool wrappers misroute the `@` token in
// `@opengsd/gsd-core@<tag>`, causing npm to error with
// "Unknown command: @opengsd/gsd-core@<tag>".
//
// The robust form is:
// npx -y --package=@opengsd/gsd-core@"$TAG" -- gsd-core $ARGS
//
// `--package=` forces a fresh registry fetch, bypassing the npx cache.
// `--` clearly delineates npx flags from the run-command, preventing
// Bash-tool @-token misrouting.
// `$TAG` is a shell variable (latest by default, next under --next/--rc),
// set by the parse_update_channel step (#815).
const { test: __t3130 } = require('node:test');
const assert3130 = require('node:assert/strict');
const fs3130 = require('node:fs');
const path3130 = require('node:path');
const ROOT_3130 = path3130.join(__dirname, '..');
const UPDATE_WF_3130 = path3130.join(ROOT_3130, 'gsd-core', 'workflows', 'update.md');
const src3130 = fs3130.readFileSync(UPDATE_WF_3130, 'utf8');
__t3130('bug #3130: update.md contains no bare npx invocations (cache-stale form)', () => {
// Any occurrence of `npx -y @opengsd/gsd-core@<something>` without `--package=`
// is the stale form that triggers the two failure modes.
// eslint-disable-next-line local/no-unbounded-quantifier -- parses maintainer-authored update.md workflow, bounded prose, not adversarial input
const stale = (src3130.match(/npx -y @opengsd\/gsd-core@\S+[^\r\n]*/g) || []);
assert3130.deepEqual(
stale,
[],
`Stale npx forms found in update.md (must use --package= form): ${stale.join('; ')}`,
);
});
__t3130('bug #3130: update.md has >=3 robust npx invocations (--package= + -- separator)', () => {
// Three sibling invocations: local, global, and unknown/fallback.
// The tag is now a $TAG variable (latest by default, next under --next/--rc).
const robust = (src3130.match(/npx -y --package=@opengsd\/gsd-core@\S+ -- gsd-core/g) || []);
assert3130.ok(
robust.length >= 3,
`Expected >=3 robust npx invocations in update.md, found ${robust.length}`,
);
});
});
}