@vaultcompass/conductor 0.8.0 → 0.8.1

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.
@@ -21,10 +21,17 @@
21
21
  // mirrored on purpose so the two gates cannot disagree about what a trust
22
22
  // base is:
23
23
  //
24
- // - READS ONLY, AND NEVER INTO THE REPOSITORY. `git rev-parse` and
25
- // `git show`, both of which only read. No checkout switch, no worktree, no
26
- // stash, no write of any kind. An umbrella that moved somebody's HEAD to
27
- // do its job would be a worse bug than the one it fixes.
24
+ // - READS ONLY, AND NEVER INTO THE REPOSITORY. This file runs read-only git:
25
+ // rev-parse, show-ref, rev-list, ls-tree and cat-file. No checkout switch,
26
+ // no worktree, no stash, no write of any kind. An umbrella that moved
27
+ // somebody's HEAD to do its job would be a worse bug than the one it fixes.
28
+ //
29
+ // Every function here that hands git a revision refuses a dash-leading one
30
+ // itself, before git sees it, and ends the revision list with "--" where
31
+ // the command takes paths, so git always reads the revision as a revision
32
+ // and every path as a path. One reader (`readFileAtRef`) looks a path up
33
+ // in the ref's tree and reads the blob by its id. --end-of-options is not
34
+ // used: git rev-parse only accepts it from git 2.30.
28
35
  //
29
36
  // - FAIL CLOSED ON THE REF. A ref that will not resolve is could-not-run for
30
37
  // every enabled gate. It is never a reason to fall back to the head,
@@ -64,11 +71,10 @@
64
71
  // RUN proceeds, so the caller can still learn the trees matched
65
72
  // (`headTreeEqualsBase` below) and run only the gates whose input is
66
73
  // history rather than the tree.
67
- import { spawnSync } from 'node:child_process';
68
74
  import { realpathSync } from 'node:fs';
69
75
  import path from 'node:path';
70
76
  import { parse as parseYaml } from 'yaml';
71
- import { POLICY_FILE_NAME } from './policy.js';
77
+ import { gitComplaint, runGit } from './git.js';
72
78
  /**
73
79
  * The private, fully spelled ref the composite action fetches the base branch
74
80
  * into (action.yml, gates step). Nothing else writes it and no short name can
@@ -77,36 +83,48 @@ import { POLICY_FILE_NAME } from './policy.js';
77
83
  * otherwise choose the commit the rules are read from.
78
84
  */
79
85
  export const PRIVATE_TRUST_BASE_REF = 'refs/conductor/trust-base';
80
- function refExists(repoRoot, fullRef) {
81
- const child = spawnSync('git', ['show-ref', '--verify', '--quiet', fullRef], {
82
- cwd: repoRoot,
83
- encoding: 'utf8',
84
- });
85
- return child.error === undefined && child.status === 0;
86
+ /**
87
+ * The object a fully spelled ref EXACTLY names, keeping "no such ref" apart
88
+ * from "git could not answer". `show-ref --verify` looks at that ref and
89
+ * nothing else: it does not run git's name-resolution rules, so a tag stored
90
+ * as refs/tags/refs/conductor/trust-base is never taken for
91
+ * refs/conductor/trust-base. With --quiet it exits 1 for a ref that is not
92
+ * there and something else for a failure, which is the split this needs.
93
+ */
94
+ export function exactRefLookup(repoRoot, fullRef) {
95
+ if (fullRef.startsWith('-')) {
96
+ return { kind: 'error', detail: `refusing "${fullRef}": it starts with "-"` };
97
+ }
98
+ const probe = runGit(repoRoot, ['show-ref', '--verify', '--quiet', fullRef]);
99
+ if (probe.error === undefined && probe.status === 1) {
100
+ return { kind: 'absent' };
101
+ }
102
+ if (probe.error !== undefined || probe.status !== 0) {
103
+ return { kind: 'error', detail: `cannot read ${fullRef}: ${gitComplaint(probe)}` };
104
+ }
105
+ const read = runGit(repoRoot, ['show-ref', '--verify', '--hash', fullRef]);
106
+ const value = read.stdout.trim();
107
+ if (read.error !== undefined || read.status !== 0 || !/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(value)) {
108
+ return { kind: 'error', detail: `cannot read ${fullRef}: ${gitComplaint(read)}` };
109
+ }
110
+ return { kind: 'ref', oid: value };
86
111
  }
87
112
  /**
88
113
  * The object id a fully spelled ref EXACTLY names, or null when there is no
89
- * such ref. `show-ref --verify` looks at that ref and nothing else: it does
90
- * not run git's name-resolution rules, so a tag stored as
91
- * refs/tags/refs/conductor/trust-base is never taken for
92
- * refs/conductor/trust-base.
114
+ * such ref or it cannot be read. For callers where both mean "cannot use
115
+ * it"; a caller that would fall back to something else on absence uses
116
+ * `exactRefLookup` instead, so an unreadable ref never takes that fallback.
93
117
  */
94
118
  export function exactRefObject(repoRoot, fullRef) {
95
- const child = spawnSync('git', ['show-ref', '--verify', '--hash', fullRef], {
96
- cwd: repoRoot,
97
- encoding: 'utf8',
98
- });
99
- if (child.error !== undefined || child.status !== 0) {
100
- return null;
101
- }
102
- const value = (child.stdout ?? '').trim();
103
- return /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(value) ? value : null;
119
+ const lookup = exactRefLookup(repoRoot, fullRef);
120
+ return lookup.kind === 'ref' ? lookup.oid : null;
104
121
  }
105
122
  /**
106
123
  * A caller-given trust base that starts with "-", or null. Git allows a tag
107
124
  * named refs/tags/--output=x, and such a name handed to git as an argument is
108
- * read as an option, not a revision. Refused before any git call sees it; the
109
- * git calls below also pass --end-of-options as a second line of defence.
125
+ * read as an option, not a revision. Refused before any git call sees it; each
126
+ * git-calling function below refuses one again itself, so no caller can skip
127
+ * the check.
110
128
  */
111
129
  export function refuseDashLeadingRef(ref) {
112
130
  if (!ref.startsWith('-')) {
@@ -147,7 +165,20 @@ noun = 'the trust base') {
147
165
  isFullObjectId(name)) {
148
166
  return null;
149
167
  }
150
- const matches = [`refs/tags/${name}`, `refs/heads/${name}`, `refs/remotes/${name}`].filter((full) => refExists(repoRoot, full));
168
+ const matches = [];
169
+ for (const full of [`refs/tags/${name}`, `refs/heads/${name}`, `refs/remotes/${name}`]) {
170
+ const lookup = exactRefLookup(repoRoot, full);
171
+ if (lookup.kind === 'error') {
172
+ // Could not tell whether the name is shadowed, so it cannot be trusted
173
+ // as spelled. Refused with git's own reason rather than read as absent.
174
+ return (`refusing "${ref}" as ${noun}: whether the name "${name}" is ambiguous could not be ` +
175
+ `checked (${lookup.detail}). Pass the ref spelled in full, for example ` +
176
+ 'refs/remotes/origin/main. Nothing was checked.');
177
+ }
178
+ if (lookup.kind === 'ref') {
179
+ matches.push(full);
180
+ }
181
+ }
151
182
  if (matches.length <= 1) {
152
183
  return null;
153
184
  }
@@ -164,6 +195,11 @@ noun = 'the trust base') {
164
195
  * rather than repeating the command line that failed.
165
196
  */
166
197
  export function resolveRev(repoRoot, rev, kind) {
198
+ // A dash-leading rev is an option to git, not a revision. Refused here,
199
+ // inside the function that calls git, so no caller can skip it.
200
+ if (rev.startsWith('-')) {
201
+ return null;
202
+ }
167
203
  // A refs/ name is NEVER handed to git's name resolution: rev-parse would
168
204
  // try refs/tags/<name> when the ref itself is absent, so a pushed tag named
169
205
  // refs/conductor/trust-base would stand in for the private ref. The exact
@@ -177,14 +213,13 @@ export function resolveRev(repoRoot, rev, kind) {
177
213
  }
178
214
  target = exact;
179
215
  }
180
- const child = spawnSync('git', ['rev-parse', '--verify', '--quiet', '--end-of-options', `${target}^{${kind}}`], {
181
- cwd: repoRoot,
182
- encoding: 'utf8',
183
- });
216
+ // No "--" here: rev-parse --verify takes exactly one revision and reads it
217
+ // only as a revision.
218
+ const child = runGit(repoRoot, ['rev-parse', '--verify', '--quiet', `${target}^{${kind}}`]);
184
219
  if (child.error !== undefined || child.status !== 0) {
185
220
  return null;
186
221
  }
187
- const value = (child.stdout ?? '').trim();
222
+ const value = child.stdout.trim();
188
223
  return value === '' ? null : value;
189
224
  }
190
225
  /**
@@ -198,14 +233,14 @@ export function resolveRev(repoRoot, rev, kind) {
198
233
  * branch first and the pull request's own head second.
199
234
  */
200
235
  function headParents(repoRoot) {
201
- const child = spawnSync('git', ['rev-list', '--parents', '-n', '1', 'HEAD'], {
202
- cwd: repoRoot,
203
- encoding: 'utf8',
204
- });
236
+ // "--" ends the revisions, so HEAD is read as a revision whatever files the
237
+ // working tree holds. A failure stays an empty list, which refuses the
238
+ // equal-tree exception: the fail-closed direction.
239
+ const child = runGit(repoRoot, ['rev-list', '--parents', '-n', '1', 'HEAD', '--']);
205
240
  if (child.error !== undefined || child.status !== 0) {
206
241
  return [];
207
242
  }
208
- const line = (child.stdout ?? '').trim();
243
+ const line = child.stdout.trim();
209
244
  if (line === '') {
210
245
  return [];
211
246
  }
@@ -364,7 +399,20 @@ export function refuseTrustBaseForPullRequest(repoRoot, ref, githubBaseRef) {
364
399
  // name when the ref is absent.
365
400
  const expectedRef = `refs/remotes/origin/${githubBaseRef}`;
366
401
  const expectedCommit = resolveRev(repoRoot, expectedRef, 'commit');
367
- const privateCommit = resolveRev(repoRoot, PRIVATE_TRUST_BASE_REF, 'commit');
402
+ // The private ref decides which reference applies, so a private ref git
403
+ // could not read is never taken for an absent one: the remote-tracking ref
404
+ // is the reference only when the private ref is truly absent.
405
+ const privateLookup = exactRefLookup(repoRoot, PRIVATE_TRUST_BASE_REF);
406
+ if (privateLookup.kind === 'error') {
407
+ return (`cannot verify "${ref}" as the trust base: ${privateLookup.detail}. Check that git can ` +
408
+ `read the repository and that the action's fetch of the base branch into ` +
409
+ `${PRIVATE_TRUST_BASE_REF} succeeded. Nothing was checked.`);
410
+ }
411
+ const privateCommit = privateLookup.kind === 'absent' ? null : resolveRev(repoRoot, PRIVATE_TRUST_BASE_REF, 'commit');
412
+ if (privateLookup.kind === 'ref' && privateCommit === null) {
413
+ return (`cannot verify "${ref}" as the trust base: ${PRIVATE_TRUST_BASE_REF} exists but does not ` +
414
+ 'name a commit. Nothing was checked.');
415
+ }
368
416
  // THE ACTION PASSES A FULL COMMIT ID, never a ref name (a full object id is
369
417
  // not subject to name resolution). It is accepted only when it IS the
370
418
  // private ref's commit (the authority, fetched and verified by the action's
@@ -431,27 +479,57 @@ export function refuseTrustBaseForPullRequest(repoRoot, ref, githubBaseRef) {
431
479
  `trusted. Pass ${expectedRef} or ${PRIVATE_TRUST_BASE_REF} instead. Nothing was checked.`);
432
480
  }
433
481
  /**
434
- * The policy file's contents at a ref, or null when that ref carries none.
482
+ * How a control file that cannot be read at the base is cleared, as one
483
+ * sentence for every refusal that names one. The pull request that fixes the
484
+ * file is judged against the same base, so it cannot pass this check itself.
485
+ */
486
+ export function unreadableBaseRemedy(relativePath) {
487
+ return (`To clear it, make ${relativePath} a regular file on the base branch, with no symbolic ` +
488
+ 'link or submodule in the directories above it. The pull request ' +
489
+ 'that does so is judged against this same base, so it has to be merged by someone ' +
490
+ 'allowed to merge without this check passing.');
491
+ }
492
+ /**
493
+ * One file's contents at a ref, with absent, present and unreadable kept
494
+ * apart. THE ONE READER for every file the umbrella takes from a ref.
435
495
  *
436
- * `git show`, never a checkout switch and never a read from the working
437
- * tree. The `./` is load-bearing for the same reason it is in intent-guard:
438
- * it makes git resolve the path relative to the working directory, which is
439
- * the repository root here, rather than to wherever the repository root would
440
- * be from somewhere else.
496
+ * Two steps. `git ls-tree <ref> -- ./<path>` looks the path up in the ref's
497
+ * tree: a listing that succeeds and names nothing is ABSENT, and a listing
498
+ * that fails is an ERROR. The entry must be a regular file; a symlink, a
499
+ * directory or a submodule at the path, or at any directory above it, is an
500
+ * ERROR, never read as its link target or as nothing. Then
501
+ * `git cat-file blob <id>` reads the blob by the id the listing named, and a
502
+ * failure there is an ERROR too. The path is only ever a path and the
503
+ * revision only ever a revision, so a file name can never be read as part of
504
+ * a revision, and absent, present and unreadable are three separate answers.
505
+ *
506
+ * No caller turns an ERROR into empty text or into a default. An error is
507
+ * could-not-run: the trusted file exists, or may, and nothing was judged
508
+ * against it.
509
+ *
510
+ * The `./` makes git resolve the path relative to the working directory,
511
+ * which is the repository root here.
441
512
  */
442
- export function readPolicyAtRef(repoRoot, ref) {
443
- if (ref.startsWith('-')) {
444
- return null;
445
- }
446
- const child = spawnSync('git', ['show', '--end-of-options', `${ref}:./${POLICY_FILE_NAME}`], {
447
- cwd: repoRoot,
448
- encoding: 'utf8',
449
- maxBuffer: 32 * 1024 * 1024,
450
- });
451
- if (child.error !== undefined || child.status !== 0) {
452
- return null;
453
- }
454
- return child.stdout ?? '';
513
+ export function readFileAtRef(repoRoot, ref, relativePath) {
514
+ const listed = treeEntryAt(repoRoot, ref, relativePath);
515
+ if (listed.kind !== 'entry') {
516
+ return listed;
517
+ }
518
+ if (listed.type !== 'blob' || !isRegularFileMode(listed.mode)) {
519
+ return {
520
+ kind: 'error',
521
+ detail: `${relativePath} is not a regular file at "${ref}" (git lists it with mode ${listed.mode}), ` +
522
+ 'so there is no file to read there',
523
+ };
524
+ }
525
+ const blob = runGit(repoRoot, ['cat-file', 'blob', listed.sha]);
526
+ if (blob.error !== undefined || blob.status !== 0) {
527
+ return {
528
+ kind: 'error',
529
+ detail: `${relativePath} is listed at "${ref}" but its contents could not be read: ${gitComplaint(blob)}`,
530
+ };
531
+ }
532
+ return { kind: 'file', text: blob.stdout };
455
533
  }
456
534
  /**
457
535
  * Whether two policy files differ in what they SAY.
@@ -463,7 +541,7 @@ export function readPolicyAtRef(repoRoot, ref) {
463
541
  * compared instead, which is the fail-closed direction: an unparseable head
464
542
  * policy is reported as a change rather than quietly matching.
465
543
  *
466
- * BOTH SIDES COME FROM `git show`, base and head alike, and that is not an
544
+ * BOTH SIDES COME FROM `readFileAtRef`, base and head alike, and that is not an
467
545
  * accident of implementation. intent-guard read its head side from the
468
546
  * working tree with a call that follows symlinks, so a pull request that
469
547
  * replaced a control file with a link compared equal to the base and was
@@ -488,33 +566,62 @@ export function policyDiffers(base, head) {
488
566
  /** The one line the report prints when the head proposes a different policy. */
489
567
  export const POLICY_PROPOSAL_LINE = 'policy changed in this pull request';
490
568
  /**
491
- * One path's tree entry at a ref, or null when the ref has no such path.
569
+ * One path's tree entry at a ref, keeping "the ref has no such path" apart
570
+ * from "git could not list it".
492
571
  *
493
572
  * `ls-tree` rather than `git show`, because the BLOB ID is the thing being
494
573
  * compared and `show` prints contents without telling you what kind of entry
495
574
  * produced them. The mode comes with it, so a regular file can be told from a
496
575
  * symlink, a submodule or a directory in the same read.
576
+ *
577
+ * Only a listing that SUCCEEDS and names nothing is absent. ls-tree exiting
578
+ * non-zero (a ref that will not resolve, a tree it cannot read) is a read
579
+ * this run cannot make, and so is a path with a symlink or a submodule at
580
+ * any directory above it in the ref's tree: what the path means there is
581
+ * decided outside the tree, so it is an error, never absent.
497
582
  */
498
583
  export function treeEntryAt(repoRoot, ref, relativePath) {
499
584
  if (ref.startsWith('-')) {
500
- return null;
585
+ return {
586
+ kind: 'error',
587
+ detail: `refusing "${ref}": it starts with "-", which git would read as an option rather than a revision`,
588
+ };
589
+ }
590
+ const segments = relativePath.split('/').filter((segment) => segment !== '' && segment !== '.');
591
+ for (let depth = 1; depth < segments.length; depth += 1) {
592
+ const parent = segments.slice(0, depth).join('/');
593
+ const listed = listOne(repoRoot, ref, parent);
594
+ if (listed.kind !== 'entry') {
595
+ return listed;
596
+ }
597
+ if (listed.mode === '120000' || listed.mode === '160000') {
598
+ return {
599
+ kind: 'error',
600
+ detail: `${parent} is a ${listed.mode === '120000' ? 'symbolic link' : 'submodule'} at "${ref}", ` +
601
+ `so ${relativePath} cannot be read there as a file in the tree`,
602
+ };
603
+ }
604
+ if (listed.type !== 'tree') {
605
+ return { kind: 'absent' };
606
+ }
501
607
  }
502
- const child = spawnSync('git', ['ls-tree', '--end-of-options', ref, '--', `./${relativePath}`], {
503
- cwd: repoRoot,
504
- encoding: 'utf8',
505
- });
608
+ return listOne(repoRoot, ref, relativePath);
609
+ }
610
+ /** One `ls-tree` listing of exactly this path. */
611
+ function listOne(repoRoot, ref, relativePath) {
612
+ const child = runGit(repoRoot, ['ls-tree', ref, '--', `./${relativePath}`]);
506
613
  if (child.error !== undefined || child.status !== 0) {
507
- return null;
614
+ return { kind: 'error', detail: `cannot list ${relativePath} at "${ref}": ${gitComplaint(child)}` };
508
615
  }
509
- const line = (child.stdout ?? '').split('\n').find((entry) => entry.trim().length > 0);
616
+ const line = child.stdout.split('\n').find((entry) => entry.trim().length > 0);
510
617
  if (line === undefined) {
511
- return null;
618
+ return { kind: 'absent' };
512
619
  }
513
620
  const [mode, type, sha] = line.split(/\s+/);
514
621
  if (mode === undefined || type === undefined || sha === undefined) {
515
- return null;
622
+ return { kind: 'error', detail: `cannot read the listing of ${relativePath} at "${ref}"` };
516
623
  }
517
- return { mode, type, sha };
624
+ return { kind: 'entry', mode, type, sha };
518
625
  }
519
626
  /** The two modes that mean an ordinary file git will hand back. */
520
627
  function isRegularFileMode(mode) {
@@ -568,7 +675,9 @@ function treeShaAt(repoRoot, ref, relativeDir) {
568
675
  return resolveRev(repoRoot, ref, 'tree');
569
676
  }
570
677
  const entry = treeEntryAt(repoRoot, ref, relativeDir);
571
- return entry === null || entry.type !== 'tree' ? null : entry.sha;
678
+ // Absent, unreadable or not a directory all mean "not the approved tree",
679
+ // which refuses the program: the fail-closed direction for each.
680
+ return entry.kind !== 'entry' || entry.type !== 'tree' ? null : entry.sha;
572
681
  }
573
682
  /**
574
683
  * Why this gate's PROGRAM cannot be trusted on a pull-request run, or null.
@@ -658,8 +767,16 @@ export function refuseHeadControlledProgram(repoRoot, trustBase, programPath) {
658
767
  }
659
768
  for (const candidate of candidates) {
660
769
  const relative = path.relative(repoReal, candidate).split(path.sep).join('/');
661
- const base = treeEntryAt(repoRoot, trustBase, relative);
662
- const head = treeEntryAt(repoRoot, 'HEAD', relative);
770
+ const baseEntry = treeEntryAt(repoRoot, trustBase, relative);
771
+ const headEntry = treeEntryAt(repoRoot, 'HEAD', relative);
772
+ for (const listed of [baseEntry, headEntry]) {
773
+ if (listed.kind === 'error') {
774
+ return (`the gate program at ${relative} could not be checked against "${trustBase}": ` +
775
+ `${listed.detail}. Nothing was checked by this gate.`);
776
+ }
777
+ }
778
+ const base = baseEntry.kind === 'entry' ? baseEntry : null;
779
+ const head = headEntry.kind === 'entry' ? headEntry : null;
663
780
  if (base === null || head === null) {
664
781
  return (`the ${trustBase === '' ? 'base' : `"${trustBase}"`} ref does not track the gate program ` +
665
782
  `at ${relative}, so it is a file this pull request controls and running it would let the ` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vaultcompass/conductor",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "Umbrella installer and combined report over the independently installable guardrail gates.",
6
6
  "keywords": [