@vaultcompass/conductor 0.4.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,12 @@
1
1
  // Running one gate as a child process.
2
2
  //
3
3
  // Wrapper, not library: nothing here imports any gate's own package. That
4
- // is what keeps the umbrella from taking three exact version pins and
5
- // needing a release of its own every time one of the three ships, and it is
4
+ // is what keeps the umbrella from taking exact version pins on five tools
5
+ // and needing a release of its own every time one of them ships, and it is
6
6
  // what makes "this gate ran and exited N, output unparsed" an available
7
- // outcome instead of a build error.
7
+ // outcome instead of a build error. What differs per tool (how the version
8
+ // is asked, where the JSON comes from, what each exit means, the timeout)
9
+ // is data in src/products.ts, not branches here.
8
10
  //
9
11
  // The one non-obvious constraint, and it came from running the tools rather
10
12
  // than from reading them: the CHILD'S WORKING DIRECTORY MUST BE THE
@@ -16,15 +18,20 @@
16
18
  // --project, so setting cwd correctly is the single approach that is right
17
19
  // for all three.
18
20
  import { spawnSync } from 'node:child_process';
21
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
22
+ import { tmpdir } from 'node:os';
23
+ import path from 'node:path';
19
24
  import { NormalizeError } from './envelope.js';
20
- import { normalizeDepGuard, normalizeFailedGate, normalizeIntentGuard, normalizeMisconfiguredGate, normalizeMissingGate, normalizeUnparseableGate, normalizeVaultGuard, } from './normalize.js';
25
+ import { normalizeDepGuard, normalizeFailedGate, normalizeGitleaks, normalizeIntentGuard, normalizeMisconfiguredGate, normalizeMissingGate, normalizeOsvScanner, normalizeUnparseableGate, normalizeVaultGuard, } from './normalize.js';
21
26
  import { renderOptionFlags } from './policy.js';
27
+ import { ExternalConfigError, materializeExternalConfig, nestedConfigProposals, } from './external-config.js';
28
+ import { profileFor } from './products.js';
22
29
  import { atLeastVersion, refuseHeadControlledProgram } from './trust-base.js';
23
30
  import { ResolveError, candidateNames, nodeModulesCandidate, resolveGateBinary, } from './resolve.js';
24
31
  /**
25
32
  * The first version of each gate that understands `--trust-base`.
26
33
  *
27
- * A TABLE rather than a boolean, because the three gates get pull-request
34
+ * A TABLE rather than a boolean, because the three family gates got pull-request
28
35
  * mode in three separate releases and the umbrella has to keep working
29
36
  * against every combination in the meantime. A product missing from this
30
37
  * table has no pull-request mode yet and is never handed the flag; a product
@@ -43,10 +50,19 @@ export const TRUST_BASE_MIN_VERSION = {
43
50
  'intent-guard': '1.4.0',
44
51
  'vault-guard': '1.7.0',
45
52
  'dep-guard': '0.6.0',
46
- // All three products are in. The table stays a table rather than becoming
47
- // a boolean: a fourth role can arrive without one, and the "no
48
- // pull-request mode yet" branch below is what keeps that gate from being
49
- // handed a flag it would reject.
53
+ // The two external tools have no --trust-base and are never handed one.
54
+ // For them the umbrella itself provides pull-request mode: it scopes the
55
+ // history to base..HEAD and hands over the config (and gitleaks' ignore
56
+ // file) read from the base ref (src/external-config.ts). So the entry here
57
+ // is their command-line floor, the same value as `minVersion` in
58
+ // src/products.ts, and being in the table is what makes an unreadable
59
+ // version a refusal on a pull request rather than a quiet withholding.
60
+ gitleaks: '8.19.0',
61
+ 'osv-scanner': '2.0.0',
62
+ // The table stays a table rather than becoming a boolean: a new role can
63
+ // arrive without pull-request mode, and the "no pull-request mode yet"
64
+ // branch below is what keeps that gate from being handed a flag it would
65
+ // reject.
50
66
  };
51
67
  /**
52
68
  * Whether this gate can be handed `--trust-base`, and why not when it cannot.
@@ -223,16 +239,36 @@ export function gateArgs(gate, staged, intent,
223
239
  * `decideTrustBase`; nothing here re-decides it, so a gate that cannot take
224
240
  * the flag is never handed one by a second opinion written in this switch.
225
241
  */
226
- trustBase) {
242
+ trustBase,
243
+ /** Paths the runner owns for an external tool; the npm gates ignore them. */
244
+ external = {}) {
227
245
  const passthrough = renderOptionFlags(gate.options);
228
246
  const trust = trustBase === undefined ? [] : ['--trust-base', trustBase];
247
+ const config = external.configPath === undefined ? [] : ['--config', external.configPath];
229
248
  switch (gate.product) {
230
- case 'dep-guard':
249
+ case 'dep-guard': {
231
250
  // `scan` takes --trust-base from 0.6.0. It sits beside whatever the
232
251
  // umbrella already passes rather than replacing it: --trust-base says
233
252
  // where the RULES come from and the mode flags say what is scanned,
234
253
  // and a pull-request run passes both.
235
- return [...(staged ? ['--staged'] : []), '--format', 'json', ...trust, ...passthrough];
254
+ //
255
+ // --base is a different flag answering a different question:
256
+ // --trust-base says whose config is trusted, --base says what the
257
+ // change is compared against. On a pull-request run (trustBase
258
+ // decided) they end up pointing at the same ref, because the base
259
+ // branch is both the state the pull request diverged from and the
260
+ // state whose rules were approved -- but dep-guard's own CLI treats
261
+ // them as unrelated flags, so both are passed rather than one
262
+ // implying the other.
263
+ //
264
+ // Never added when staged: dep-guard's CLI refuses --staged together
265
+ // with --base (packages/cli/src/cli.ts, resolveMode), because the two
266
+ // name incompatible comparisons -- the git index versus an arbitrary
267
+ // ref. A staged run already has its own comparison and --trust-base
268
+ // is unaffected, since it answers a different question.
269
+ const base = trustBase !== undefined && !staged ? ['--base', trustBase] : [];
270
+ return [...(staged ? ['--staged'] : []), '--format', 'json', ...trust, ...base, ...passthrough];
271
+ }
236
272
  case 'vault-guard':
237
273
  // No path argument: the CLI defaults it to "." and the umbrella runs
238
274
  // with cwd at the repository root anyway. Passing one would also risk
@@ -277,6 +313,67 @@ trustBase) {
277
313
  ...passthrough,
278
314
  ];
279
315
  }
316
+ case 'gitleaks': {
317
+ if (external.reportPath === undefined) {
318
+ throw new Error('gitleaks needs a report path: it cannot write its report to stdout');
319
+ }
320
+ // --exit-code 3 moves the leak code off 1, which gitleaks also uses for
321
+ // errors, so a crash and a leak stop sharing a number. --log-opts is
322
+ // always set: gitleaks' default is git log --all, which on a checkout
323
+ // with fetch-depth 0 scans every branch, so one branch's secret would
324
+ // redden every other pull request. --staged has no meaning here, and
325
+ // --trust-base is never handed to an external tool: the trust base
326
+ // scopes the history and selects the config, and that is all.
327
+ //
328
+ // --diff-merges=first-parent because `git log -p` shows no diff for a
329
+ // merge commit, so a secret added inside a merge's own changes (an
330
+ // evil merge, a key pasted while resolving a conflict) was never
331
+ // scanned. The price is that a pull request's change shows twice under
332
+ // an Actions-style merge, once in its commit and once in the merge's
333
+ // first-parent diff; normalizeGitleaks collapses those.
334
+ //
335
+ // --log-level info, pinned: the umbrella reads ERR lines to tell a
336
+ // failed scan from a clean one, so a lower level (or a future lower
337
+ // default) would turn a failed scan into a pass. It is reserved too.
338
+ const scope = trustBase === undefined ? 'HEAD' : `${trustBase}..HEAD`;
339
+ return [
340
+ '--report-format',
341
+ 'json',
342
+ '--report-path',
343
+ external.reportPath,
344
+ '--exit-code',
345
+ '3',
346
+ '--redact',
347
+ '--no-banner',
348
+ '--log-level',
349
+ 'info',
350
+ '--log-opts',
351
+ `--diff-merges=first-parent ${scope}`,
352
+ // On a pull request, inline gitleaks:allow comments are ignored: an
353
+ // inline allow lives in the tree being judged, so the pull request
354
+ // controls it. A legitimate allow belongs in the base ref's
355
+ // .gitleaks.toml allowlist or .gitleaksignore, both of which the
356
+ // umbrella already reads from the base. Local runs keep them.
357
+ ...(trustBase === undefined ? [] : ['--ignore-gitleaks-allow']),
358
+ ...config,
359
+ ...(external.ignorePath === undefined ? [] : ['--gitleaks-ignore-path', external.ignorePath]),
360
+ ...passthrough,
361
+ external.scanRoot ?? '.',
362
+ ];
363
+ }
364
+ case 'osv-scanner': {
365
+ // JSON goes to stdout and everything else to stderr, so no report
366
+ // file. No directory walk: each tracked lockfile is named with
367
+ // --lockfile (the runner lists them, src/products.ts
368
+ // OSV_LOCKFILE_NAMES), because osv-scanner's own walk skips anything
369
+ // .gitignore matches, tracked or not. With none there is nothing to
370
+ // hand over, and the runner reports that without spawning the tool.
371
+ if (external.lockfiles === undefined || external.lockfiles.length === 0) {
372
+ throw new Error('osv-scanner needs at least one lockfile: with none, nothing is spawned');
373
+ }
374
+ const lockfiles = external.lockfiles.flatMap((file) => ['--lockfile', file]);
375
+ return ['--format', 'json', ...config, ...lockfiles, ...passthrough];
376
+ }
280
377
  }
281
378
  }
282
379
  /**
@@ -286,8 +383,9 @@ trustBase) {
286
383
  * per-command binaries ignore --version and run the gate instead, so a
287
384
  * probe there would have side effects on the user's repository.
288
385
  */
289
- function probeVersion(binary, repoRoot, timeoutMs) {
290
- if (binary.versionProbe === null) {
386
+ function probeVersion(binary, product, repoRoot, timeoutMs) {
387
+ const spec = profileFor(product).versionProbe;
388
+ if (binary.versionProbe === null || spec === null) {
291
389
  return null;
292
390
  }
293
391
  const probe = spawnSync(binary.versionProbe.command, binary.versionProbe.argv, {
@@ -298,21 +396,57 @@ function probeVersion(binary, repoRoot, timeoutMs) {
298
396
  if (probe.status !== 0 || typeof probe.stdout !== 'string') {
299
397
  return null;
300
398
  }
301
- // All three print a bare version string. Take the first line and accept
302
- // it only if it looks like one, so a future help banner does not end up
303
- // in a SARIF driver's version field.
399
+ // Take the first line and accept it only if the product's pattern matches,
400
+ // so a future help banner does not end up in a SARIF driver's version
401
+ // field. The npm gates print a bare version and their pattern keeps the
402
+ // whole line; an external tool that prefixes its version with its name has
403
+ // a capture group that takes the number alone.
304
404
  const first = probe.stdout.trim().split('\n')[0]?.trim() ?? '';
305
- return /^v?\d+\.\d+\.\d+/.test(first) ? first.replace(/^v/, '') : null;
405
+ const match = spec.pattern.exec(first);
406
+ return match === null ? null : (match[1] ?? match[0]).replace(/^v/, '');
306
407
  }
307
- function normalizeFor(product, parsed, version) {
408
+ /**
409
+ * `context.blocked` is whether the gate's exit said it blocked. The npm gates
410
+ * carry that in their own JSON and ignore it; the external tools' reports do
411
+ * not, so their normalizers take it from here.
412
+ *
413
+ * `context.online` and `context.lockfiles` are read from the umbrella's OWN
414
+ * constructed argv, never from a gate's JSON (issue #72): whether --online
415
+ * was passed and which lockfiles were handed over with --lockfile are
416
+ * questions about what this run asked for, which the umbrella already knows
417
+ * before the child ever answers.
418
+ */
419
+ function normalizeFor(product, parsed, version, context) {
308
420
  switch (product) {
309
421
  case 'dep-guard':
310
- return normalizeDepGuard(parsed, version);
422
+ return normalizeDepGuard(parsed, version, context.online);
311
423
  case 'vault-guard':
312
424
  return normalizeVaultGuard(parsed, version);
313
425
  case 'intent-guard':
314
426
  return normalizeIntentGuard(parsed, version);
427
+ case 'gitleaks':
428
+ return normalizeGitleaks(parsed, version, context.blocked);
429
+ case 'osv-scanner':
430
+ return normalizeOsvScanner(parsed, version, context.blocked, context.roots, context.lockfiles);
431
+ }
432
+ }
433
+ /**
434
+ * The repository root in every spelling a child could print it in: as given,
435
+ * and with symbolic links resolved (a macOS temporary directory is the
436
+ * everyday case: /var is a link to /private/var).
437
+ */
438
+ function rootSpellings(repoRoot) {
439
+ const spellings = [path.resolve(repoRoot)];
440
+ try {
441
+ const real = realpathSync(repoRoot);
442
+ if (!spellings.includes(real)) {
443
+ spellings.push(real);
444
+ }
315
445
  }
446
+ catch {
447
+ // A root that cannot be resolved has one spelling.
448
+ }
449
+ return spellings;
316
450
  }
317
451
  /**
318
452
  * An error's message, never its stack.
@@ -342,15 +476,20 @@ function messageOf(err) {
342
476
  * lives on the base branch, which is the protected side.
343
477
  */
344
478
  function missingGateRemedy(product, skipNodeModules, skipped) {
479
+ const profile = profileFor(product);
480
+ if (!profile.managed) {
481
+ // An external tool is never in node_modules and never installed by the
482
+ // Action, so the pull-request sentence below would send a reader to the
483
+ // wrong place. Its own install instruction applies on every run.
484
+ return ` ${profile.remedy(skipNodeModules)}`;
485
+ }
345
486
  if (!skipNodeModules) {
346
487
  return '';
347
488
  }
348
489
  return (' On a pull-request run node_modules/.bin is not consulted at all: what is installed there ' +
349
490
  'is chosen by the head own manifest and lockfile, so no ref approves it.' +
350
491
  (skipped === null ? '' : ` There is a ${skipped}, and it was skipped for that reason.`) +
351
- ` Install the gate outside the tree with npm install -g @vaultcompass/${product}. The ` +
352
- `conductor Action does exactly that, at the version its ${product}-version input pins, and ` +
353
- 'that pin lives in the workflow file on the base branch.');
492
+ ` ${profile.remedy(true)}`);
354
493
  }
355
494
  /**
356
495
  * Runs one gate. TOTAL: this never throws.
@@ -421,7 +560,7 @@ export function runGate(gate, options) {
421
560
  }
422
561
  }
423
562
  function runGateInner(gate, options, started, progress) {
424
- const timeoutMs = options.timeoutMs ?? 120_000;
563
+ const timeoutMs = options.timeoutMs ?? profileFor(gate.product).timeoutMs;
425
564
  // ONE PLACE DECIDES WHAT PULL-REQUEST MODE IS, and it is the presence of a
426
565
  // trust base. resolve.ts knows nothing about refs, so it is told rather than
427
566
  // asked.
@@ -503,7 +642,30 @@ function runGateInner(gate, options, started, progress) {
503
642
  };
504
643
  }
505
644
  }
506
- const version = probeVersion(binary, options.repoRoot, timeoutMs);
645
+ const version = probeVersion(binary, gate.product, options.repoRoot, timeoutMs);
646
+ // The command-line floor. Only the external tools have one: the umbrella
647
+ // writes flags they grew at a known release (gitleaks' git subcommand,
648
+ // osv-scanner's scan source), and an older build would reject the command
649
+ // line with an exit the umbrella could misread. An UNREADABLE version falls
650
+ // through to the trust-base decision below, which refuses it on a pull
651
+ // request and runs it unverified locally, the same as the npm gates.
652
+ const profile = profileFor(gate.product);
653
+ if (profile.minVersion !== null &&
654
+ version !== null &&
655
+ !atLeastVersion(version, profile.minVersion)) {
656
+ const detail = `${gate.product} ${version} is older than ${profile.minVersion}, the oldest version whose ` +
657
+ `command line this umbrella speaks. Upgrade it to ${profile.minVersion} or later.`;
658
+ return {
659
+ ...base,
660
+ productVersion: version,
661
+ binary,
662
+ durationMs: Date.now() - started,
663
+ couldNotRun: { reason: 'gate-version-unsupported', detail },
664
+ findings: [normalizeFailedGate(gate.role, gate.product, detail)],
665
+ run: EMPTY_RUN,
666
+ diagnostics: [],
667
+ };
668
+ }
507
669
  // AFTER the version probe and BEFORE the command line is built, because the
508
670
  // decision reads the version. That ordering is the whole capability gate:
509
671
  // an intent-guard older than 1.4.0 must not be handed a flag it would
@@ -538,12 +700,198 @@ function runGateInner(gate, options, started, progress) {
538
700
  diagnostics: [],
539
701
  };
540
702
  }
703
+ // A directory of the runner's own for an external tool's working files: the
704
+ // report gitleaks writes. Made under the caller's temporary root when there
705
+ // is one, and removed whatever happens, so a run leaves nothing behind. The
706
+ // npm gates need none, and get none.
707
+ const decidedRef = trustBase === undefined || trustBase.withheld !== null ? undefined : trustBase.ref;
708
+ const needsConfig = decidedRef !== undefined && profile.configFile !== null;
709
+ const workDir = profile.output.kind === 'report-file' || needsConfig
710
+ ? mkdtempSync(path.join(options.tempRoot ?? tmpdir(), 'conductor-gate-'))
711
+ : null;
712
+ try {
713
+ return spawnAndRead({
714
+ gate,
715
+ options,
716
+ started,
717
+ progress,
718
+ base,
719
+ binary,
720
+ version,
721
+ trustBase,
722
+ profile,
723
+ timeoutMs,
724
+ workDir,
725
+ });
726
+ }
727
+ finally {
728
+ if (workDir !== null) {
729
+ rmSync(workDir, { recursive: true, force: true });
730
+ }
731
+ }
732
+ }
733
+ /** Strips ANSI colour codes: gitleaks colours its log even off a terminal. */
734
+ function stripAnsi(text) {
735
+ return text.replace(/\u001b\[[0-9;]*m/g, '');
736
+ }
737
+ /** Builds the command line, runs the gate, and reads what it said. */
738
+ function spawnAndRead(ctx) {
739
+ const { gate, options, started, progress, base, binary, version, trustBase, profile, timeoutMs, workDir } = ctx;
740
+ const external = {};
741
+ if (profile.output.kind === 'report-file' && workDir !== null) {
742
+ external.reportPath = path.join(workDir, `${gate.product}-report${profile.output.extension}`);
743
+ }
744
+ const decidedRef = trustBase === undefined || trustBase.withheld !== null ? undefined : trustBase.ref;
745
+ // The lockfiles a file-fed tool is handed, from the repository's tracked
746
+ // files. On a pull request this is the head's index, read directly and not
747
+ // from the base ref: the lockfiles ARE the tree being judged, and adding,
748
+ // removing or renaming one is visible in the diff, so there is nothing for
749
+ // a base-ref read to protect. A listing that fails is not "no lockfiles".
750
+ const nestedProposals = [];
751
+ if (profile.lockfileNames !== null) {
752
+ const names = new Set(profile.lockfileNames);
753
+ const listing = spawnSync('git', ['ls-files', '-z'], {
754
+ cwd: options.repoRoot,
755
+ encoding: 'utf8',
756
+ maxBuffer: 64 * 1024 * 1024,
757
+ });
758
+ if (listing.status !== 0 || typeof listing.stdout !== 'string') {
759
+ const detail = `the repository's tracked files could not be listed, so ${gate.product} had no ` +
760
+ 'lockfiles to be handed.';
761
+ return {
762
+ ...base,
763
+ productVersion: version,
764
+ binary,
765
+ durationMs: Date.now() - started,
766
+ ...(trustBase === undefined ? {} : { trustBase }),
767
+ couldNotRun: { reason: 'preparation-failed', detail },
768
+ findings: [normalizeFailedGate(gate.role, gate.product, detail)],
769
+ run: EMPTY_RUN,
770
+ diagnostics: [],
771
+ };
772
+ }
773
+ const tracked = listing.stdout.split('\0').filter((file) => file !== '');
774
+ if (decidedRef !== undefined && profile.configFile !== null) {
775
+ nestedProposals.push(...nestedConfigProposals(options.repoRoot, decidedRef, tracked, profile.configFile));
776
+ }
777
+ external.lockfiles = tracked
778
+ // Never a vendored copy under node_modules: that is a dependency's own
779
+ // lockfile, not a statement about what this repository resolves.
780
+ .filter((file) => !file.split('/').includes('node_modules'))
781
+ .filter((file) => names.has(path.posix.basename(file)))
782
+ .sort();
783
+ if (external.lockfiles.length === 0) {
784
+ // Nothing to scan, reported the same way as osv-scanner's own 128 below,
785
+ // without spawning it.
786
+ return {
787
+ ...base,
788
+ productVersion: version,
789
+ binary,
790
+ durationMs: Date.now() - started,
791
+ ...(trustBase === undefined ? {} : { trustBase }),
792
+ exitCode: 0,
793
+ couldNotRun: null,
794
+ findings: [],
795
+ run: EMPTY_RUN,
796
+ diagnostics: [
797
+ {
798
+ code: 'conductor/nothing-to-scan',
799
+ message: `${gate.product} found nothing to scan (no tracked lockfile); treated as clean.`,
800
+ },
801
+ ],
802
+ };
803
+ }
804
+ }
805
+ // On a pull request, the tool's config and ignore file come from the base
806
+ // ref (or a neutral stand-in), never from the head it would otherwise
807
+ // auto-load them from. A head-side change is a proposal, carried the same
808
+ // way an npm gate's own proposals are.
809
+ const configProposals = [...nestedProposals];
810
+ // Where the child runs. The repository root, except for a tool whose base
811
+ // config can name further files relative to its working directory: on a
812
+ // pull request that tool runs from a directory holding the base ref's
813
+ // copies, so no relative path it reads can land in the head tree. Every
814
+ // path the umbrella hands it is absolute, so nothing else depends on it.
815
+ let spawnCwd = options.repoRoot;
816
+ if (decidedRef !== undefined && workDir !== null) {
817
+ const baseline = gate.options['baseline-path'];
818
+ let materialized;
819
+ try {
820
+ materialized = materializeExternalConfig({
821
+ repoRoot: options.repoRoot,
822
+ trustBase: decidedRef,
823
+ profile,
824
+ tempRoot: workDir,
825
+ ...(typeof baseline === 'string' && !path.isAbsolute(baseline) ? { extraFiles: [baseline] } : {}),
826
+ });
827
+ }
828
+ catch (err) {
829
+ if (!(err instanceof ExternalConfigError)) {
830
+ throw err;
831
+ }
832
+ return {
833
+ ...base,
834
+ productVersion: version,
835
+ binary,
836
+ durationMs: Date.now() - started,
837
+ ...(trustBase === undefined ? {} : { trustBase }),
838
+ couldNotRun: { reason: 'preparation-failed', detail: err.message },
839
+ findings: [normalizeFailedGate(gate.role, gate.product, err.message)],
840
+ run: EMPTY_RUN,
841
+ diagnostics: [],
842
+ };
843
+ }
844
+ if (materialized !== null) {
845
+ external.configPath = materialized.path;
846
+ if (materialized.proposal !== null) {
847
+ configProposals.push(materialized.proposal);
848
+ }
849
+ configProposals.push(...materialized.extendProposals);
850
+ if (profile.followsConfigExtend) {
851
+ spawnCwd = materialized.cwd;
852
+ }
853
+ if (materialized.ignore !== null) {
854
+ external.ignorePath = materialized.ignore.dir;
855
+ if (materialized.ignore.proposal !== null) {
856
+ configProposals.push(materialized.ignore.proposal);
857
+ }
858
+ }
859
+ }
860
+ if (profile.ignoreFile?.alsoLoadedFromScanRoot === true) {
861
+ const gitDir = spawnSync('git', ['rev-parse', '--absolute-git-dir'], {
862
+ cwd: options.repoRoot,
863
+ encoding: 'utf8',
864
+ });
865
+ const resolved = typeof gitDir.stdout === 'string' ? gitDir.stdout.trim() : '';
866
+ if (gitDir.status !== 0 || resolved === '') {
867
+ // No git directory means no history to scan and nowhere safe to scan
868
+ // it from. Not a clean result.
869
+ const detail = `the repository's git directory could not be found, so ${gate.product} could not be ` +
870
+ 'pointed away from the head tree on this pull request.';
871
+ return {
872
+ ...base,
873
+ productVersion: version,
874
+ binary,
875
+ durationMs: Date.now() - started,
876
+ ...(trustBase === undefined ? {} : { trustBase }),
877
+ couldNotRun: { reason: 'preparation-failed', detail },
878
+ findings: [normalizeFailedGate(gate.role, gate.product, detail)],
879
+ run: EMPTY_RUN,
880
+ diagnostics: [],
881
+ };
882
+ }
883
+ external.scanRoot = resolved;
884
+ }
885
+ }
886
+ const trustBaseOut = trustBase === undefined || configProposals.length === 0
887
+ ? trustBase
888
+ : { ...trustBase, proposals: [...trustBase.proposals, ...configProposals] };
541
889
  const argv = [
542
890
  ...binary.argvPrefix,
543
- ...gateArgs(gate, options.staged, options.intent, trustBase === undefined || trustBase.withheld !== null ? undefined : trustBase.ref),
891
+ ...gateArgs(gate, options.staged, options.intent, decidedRef, external),
544
892
  ];
545
893
  const child = spawnSync(binary.command, argv, {
546
- cwd: options.repoRoot,
894
+ cwd: spawnCwd,
547
895
  encoding: 'utf8',
548
896
  timeout: timeoutMs,
549
897
  maxBuffer: 64 * 1024 * 1024,
@@ -554,13 +902,17 @@ function runGateInner(gate, options, started, progress) {
554
902
  argv,
555
903
  binary,
556
904
  durationMs: Date.now() - started,
557
- stderr: child.stderr ?? '',
905
+ // Colour codes stripped here, once, so neither the text report nor the
906
+ // gate-failed finding (which carries a summary of this into SARIF and a
907
+ // pull-request comment) shows escape sequences: gitleaks colours its log
908
+ // even when stderr is not a terminal.
909
+ stderr: stripAnsi(child.stderr ?? ''),
558
910
  // Carried on every return path below, the failures included: WHETHER
559
911
  // this gate was in pull-request mode is exactly as interesting when it
560
912
  // could not run as when it could, and the withheld reason is the only
561
913
  // place a report can say a gate read its own rules out of the tree under
562
914
  // judgment.
563
- ...(trustBase === undefined ? {} : { trustBase }),
915
+ ...(trustBaseOut === undefined ? {} : { trustBase: trustBaseOut }),
564
916
  };
565
917
  // Keep the backstop's view current, so an unexpected throw below still
566
918
  // reports which binary ran and what it printed.
@@ -578,11 +930,41 @@ function runGateInner(gate, options, started, progress) {
578
930
  };
579
931
  }
580
932
  const exitCode = child.status;
581
- const stdout = child.stdout ?? '';
582
- // dep-guard's 2 means "could not run the checks at all" and it prints no
583
- // JSON. The other two have no such code, but a signal-killed child or a
584
- // timeout lands here too, and none of those are a clean result.
585
- if (exitCode === null || exitCode > 1) {
933
+ // "Nothing here to scan" is its own exit for osv-scanner (128, a
934
+ // repository with no lockfile). Read as an error it would redden every pull
935
+ // request in a docs-only repository; read as a verdict it would claim a
936
+ // scan that did not happen. So it is clean, and the report says why.
937
+ if (exitCode !== null && profile.exit.nothingToScan.includes(exitCode)) {
938
+ return {
939
+ ...withRun,
940
+ exitCode: 0,
941
+ couldNotRun: null,
942
+ findings: [],
943
+ run: EMPTY_RUN,
944
+ diagnostics: [
945
+ // When lockfiles WERE handed over, this exit means they parsed to no
946
+ // packages at all, which is different news from "no lockfile": a
947
+ // lockfile the tool could not read anything from deserves a look.
948
+ external.lockfiles !== undefined && external.lockfiles.length > 0
949
+ ? {
950
+ code: 'conductor/lockfiles-empty',
951
+ message: `${gate.product} read no packages from ${external.lockfiles.join(', ')} ` +
952
+ `(exit ${exitCode}); treated as clean.`,
953
+ }
954
+ : {
955
+ code: 'conductor/nothing-to-scan',
956
+ message: `${gate.product} found nothing to scan (exit ${exitCode}); treated as clean.`,
957
+ },
958
+ ],
959
+ };
960
+ }
961
+ // The profile says which exits are verdicts. For the npm gates that is 0
962
+ // and 1, exactly as before profiles existed: dep-guard's 2 means "could not
963
+ // run the checks at all" and it prints no JSON. gitleaks is handed
964
+ // --exit-code 3, so its 1 is left meaning an error. A signal-killed child
965
+ // or a timeout lands here too, and none of those are a clean result.
966
+ const blocked = exitCode !== null && profile.exit.blocked.includes(exitCode);
967
+ if (exitCode === null || (!blocked && !profile.exit.clean.includes(exitCode))) {
586
968
  const detail = exitCode === null
587
969
  ? 'the gate did not exit normally (killed, or timed out).'
588
970
  : `the gate exited ${exitCode}, which it uses for "could not run".`;
@@ -599,17 +981,64 @@ function runGateInner(gate, options, started, progress) {
599
981
  diagnostics: [],
600
982
  };
601
983
  }
984
+ // A clean exit that logged an error is not a clean scan. gitleaks 8.30.1
985
+ // swallows a git failure (a base ref the checkout never fetched, a path
986
+ // that is not a repository): it logs the git error at ERR, scans 0
987
+ // commits, writes a report of [], and exits 0. Read by exit code alone
988
+ // that is a pass over nothing on exactly the pull requests where the
989
+ // history was never there to read.
990
+ if (!blocked && profile.stderrError !== null) {
991
+ const pattern = profile.stderrError;
992
+ const errorLine = stripAnsi(withRun.stderr)
993
+ .split('\n')
994
+ .find((line) => pattern.test(line));
995
+ if (errorLine !== undefined) {
996
+ const detail = `${gate.product} exited ${exitCode} but logged an error, so its clean result cannot be ` +
997
+ `trusted: ${errorLine.trim()}`;
998
+ return {
999
+ ...withRun,
1000
+ exitCode,
1001
+ couldNotRun: { reason: 'gate-error', detail },
1002
+ findings: [normalizeFailedGate(gate.role, gate.product, detail, withRun.stderr)],
1003
+ run: EMPTY_RUN,
1004
+ diagnostics: [],
1005
+ };
1006
+ }
1007
+ }
1008
+ let text;
1009
+ if (profile.output.kind === 'report-file') {
1010
+ // The report is where the verdict is. An exit that says clean or blocked
1011
+ // with no report behind it is not either of those.
1012
+ const reportPath = external.reportPath;
1013
+ if (!existsSync(reportPath)) {
1014
+ const detail = `${gate.product} exited ${exitCode} but wrote no report, so there is no verdict to read.`;
1015
+ return {
1016
+ ...withRun,
1017
+ exitCode,
1018
+ couldNotRun: { reason: 'report-missing', detail },
1019
+ findings: [normalizeFailedGate(gate.role, gate.product, detail, withRun.stderr)],
1020
+ run: EMPTY_RUN,
1021
+ diagnostics: [],
1022
+ };
1023
+ }
1024
+ text = readFileSync(reportPath, 'utf8');
1025
+ }
1026
+ else {
1027
+ text = child.stdout ?? '';
1028
+ }
602
1029
  let parsed;
603
1030
  try {
604
- parsed = JSON.parse(stdout);
1031
+ parsed = JSON.parse(text);
605
1032
  }
606
1033
  catch {
607
1034
  // Exit 1 with unparseable stdout is what a rejected config looks like
608
1035
  // from two of the three products, and it is could-not-run rather than
609
1036
  // clean. Reporting it as a policy violation would tell the user their
610
1037
  // code is at fault when their config is.
611
- const detail = `the gate exited ${exitCode} without valid JSON on stdout. ` +
612
- 'A rejected config file looks exactly like this, and it is not a clean result.';
1038
+ const detail = profile.output.kind === 'report-file'
1039
+ ? `the gate exited ${exitCode} and its report is not valid JSON, which is not a clean result.`
1040
+ : `the gate exited ${exitCode} without valid JSON on stdout. ` +
1041
+ 'A rejected config file looks exactly like this, and it is not a clean result.';
613
1042
  return {
614
1043
  ...withRun,
615
1044
  exitCode,
@@ -620,7 +1049,14 @@ function runGateInner(gate, options, started, progress) {
620
1049
  };
621
1050
  }
622
1051
  try {
623
- const normalized = normalizeFor(gate.product, parsed, version);
1052
+ const normalized = normalizeFor(gate.product, parsed, version, {
1053
+ blocked,
1054
+ roots: rootSpellings(options.repoRoot),
1055
+ // The literal flag, read off the argv this run actually spawned with,
1056
+ // not off gate.options: the argv is what dep-guard was actually told.
1057
+ online: argv.includes('--online'),
1058
+ lockfiles: external.lockfiles ?? [],
1059
+ });
624
1060
  return {
625
1061
  ...withRun,
626
1062
  exitCode,