@vaultcompass/conductor 0.2.4 → 0.4.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.
package/dist/run.js CHANGED
@@ -1,11 +1,12 @@
1
1
  // One run across every enabled gate.
2
2
  import { compareFindings } from './envelope.js';
3
- import { composeExitCode } from './exit-codes.js';
4
- import { preparationFailed, runGate } from './gate-runner.js';
3
+ import { EXIT_COULD_NOT_RUN, composeExitCode } from './exit-codes.js';
4
+ import { gateProgramRefused, preparationFailed, refuseHeadControlledBinary, runGate, } from './gate-runner.js';
5
5
  import { resolveBaseRef } from './intent-base.js';
6
- import { prepareIntent } from './intent-prepare.js';
6
+ import { frozenNativeContractPath, prepareIntent, } from './intent-prepare.js';
7
7
  import { GATE_ROLES, enabledGates, runsAtStage } from './policy.js';
8
8
  import { ResolveError, resolveGateBinary } from './resolve.js';
9
+ import { POLICY_PROPOSAL_LINE } from './trust-base.js';
9
10
  /**
10
11
  * Whether this run is the pull-request shaped one.
11
12
  *
@@ -22,10 +23,19 @@ function isPullRequestShaped(options, env) {
22
23
  }
23
24
  return resolveBaseRef({ ...(options.base === undefined ? {} : { base: options.base }), env }) !== null;
24
25
  }
25
- /** The intent-guard binary, or null when there is none to prepare with. */
26
+ /**
27
+ * The intent-guard binary, or null when there is none to prepare with.
28
+ *
29
+ * SAME SKIP AS runGate's, and it is not decoration: preparation SPAWNS this
30
+ * binary, before runGate has looked at anything. Resolving it out of
31
+ * node_modules on a pull-request run would execute a program the head chose,
32
+ * three times, before the program check the boundary rests on had run once.
33
+ */
26
34
  function intentBinary(gate, options) {
27
35
  try {
28
- return resolveGateBinary(gate, options.repoRoot, options.pathValue);
36
+ return resolveGateBinary(gate, options.repoRoot, options.pathValue, {
37
+ skipNodeModules: options.trustBase !== undefined,
38
+ });
29
39
  }
30
40
  catch (err) {
31
41
  // A ResolveError means the policy named a command that is not there.
@@ -36,13 +46,21 @@ function intentBinary(gate, options) {
36
46
  return null;
37
47
  }
38
48
  }
39
- export function runAll(policy, options) {
49
+ /**
50
+ * The three lists a stage filter and a `--gate` flag produce between them.
51
+ *
52
+ * Factored out because the trust-base refusal below needs the same partition:
53
+ * a run that could not read its policy from the base ref still has to report
54
+ * the gates it did not run and the stage each of them sits at, or the report
55
+ * of the most serious failure this tool has is thinner than the report of an
56
+ * ordinary one.
57
+ */
58
+ function partitionGates(policy, requested) {
40
59
  const enabled = enabledGates(policy);
41
60
  // Partitioned before anything is spawned, and before any binary is even
42
61
  // looked for: a gate that will not run at this stage must not be able to
43
62
  // fail the run by being uninstalled here. An intent gate that lives only
44
63
  // on the CI image is the ordinary case, not an error.
45
- const requested = options.stage;
46
64
  const gates = requested === undefined ? enabled : enabled.filter((gate) => runsAtStage(gate.stage, requested));
47
65
  const deferred = requested === undefined
48
66
  ? []
@@ -52,7 +70,100 @@ export function runAll(policy, options) {
52
70
  // Read off the policy rather than off the enabled list, because these gates
53
71
  // are exactly the ones the override took out of it. In role order, so a
54
72
  // report's ordering never depends on the order the flags were typed.
55
- const excluded = GATE_ROLES.map((role) => policy.gates[role]).filter((gate) => gate !== undefined && gate.excludedByCli).map((gate) => ({ role: gate.role, product: gate.product }));
73
+ const excluded = GATE_ROLES.map((role) => policy.gates[role])
74
+ .filter((gate) => gate !== undefined && gate.excludedByCli)
75
+ .map((gate) => ({ role: gate.role, product: gate.product }));
76
+ return { gates, deferred, excluded };
77
+ }
78
+ /**
79
+ * The run that never happened, because the trust base could not be judged
80
+ * against.
81
+ *
82
+ * EVERY ENABLED GATE IS COULD-NOT-RUN, which is the fail-closed half of
83
+ * pull-request mode. A base ref that will not resolve is not a reason to fall
84
+ * back to the head's policy: falling back to the head is the behaviour this
85
+ * release removes, and it would be reachable by anybody who could make the
86
+ * base ref unfetchable.
87
+ *
88
+ * TWO THINGS HERE ARE DELIBERATELY NOT READ OFF THE POLICY, and both are the
89
+ * point rather than shortcuts. The policy handed in is the HEAD's, used only
90
+ * as an inventory so the report can name the gates that did not run; it
91
+ * cannot be trusted, so:
92
+ *
93
+ * - Every synthesized outcome is ENFORCED, whatever the file says. The
94
+ * `enforce` flag is itself a control input, and the file it lives in is
95
+ * the one that could not be read from the base. A head policy setting
96
+ * `enforce: false` everywhere must not be able to turn this into exit 0.
97
+ * - The exit code is written here rather than composed. A head policy
98
+ * enabling NO gate at all would otherwise compose to 0 over an empty list,
99
+ * which would report a run that checked nothing as a clean one.
100
+ */
101
+ export function refusedTrustBase(policy, ref, detail, options) {
102
+ const { gates, deferred, excluded } = partitionGates(policy, options.stage);
103
+ const outcomes = gates.map((gate) => preparationFailed({ ...gate, enforce: true }, `the trust base could not be used: ${detail}`));
104
+ const findings = outcomes.flatMap((outcome) => outcome.findings).sort(compareFindings);
105
+ const byProduct = {};
106
+ const bySeverity = {};
107
+ for (const finding of findings) {
108
+ byProduct[finding.product] = (byProduct[finding.product] ?? 0) + 1;
109
+ bySeverity[finding.severity] = (bySeverity[finding.severity] ?? 0) + 1;
110
+ }
111
+ return {
112
+ schemaVersion: 1,
113
+ generatedAt: (options.now?.() ?? new Date()).toISOString(),
114
+ gates: outcomes,
115
+ deferred,
116
+ skipped: [],
117
+ excluded,
118
+ findings,
119
+ // policyChanged is unknowable: the base side of the comparison is the
120
+ // thing that could not be read. False rather than a third state, because
121
+ // no proposal is reported on a run where nothing was judged. The refusal
122
+ // itself is carried, and it is what both renderers lead with.
123
+ trustBase: { ref, policyChanged: false, refusal: detail },
124
+ proposals: [],
125
+ summary: {
126
+ blocking: findings.filter((finding) => finding.blocking).length,
127
+ byProduct,
128
+ bySeverity,
129
+ },
130
+ exitCode: EXIT_COULD_NOT_RUN,
131
+ };
132
+ }
133
+ /**
134
+ * Every proposed control change, the umbrella's own policy first.
135
+ *
136
+ * The umbrella's line comes first because it is the one that decides what the
137
+ * others even are: a pull request that rewrites `.guardrails.yaml` is
138
+ * proposing to change which gates run at all, and reading that after a gate's
139
+ * own contract line would bury it.
140
+ */
141
+ function collectProposals(outcomes, trustBase) {
142
+ const proposals = [];
143
+ if (trustBase?.policyChanged === true) {
144
+ proposals.push({ product: 'conductor', role: null, line: POLICY_PROPOSAL_LINE });
145
+ }
146
+ for (const outcome of outcomes) {
147
+ for (const line of outcome.trustBase?.proposals ?? []) {
148
+ proposals.push({ product: outcome.product, role: outcome.role, line });
149
+ }
150
+ }
151
+ return proposals;
152
+ }
153
+ /**
154
+ * The `intentContract` option for a run with no preparation, or nothing.
155
+ *
156
+ * A small helper rather than an inline conditional because the spread at the
157
+ * call site is already three lines, and because "nothing" has to be an empty
158
+ * object rather than an undefined property: the option is optional and
159
+ * `exactOptionalPropertyTypes` refuses an explicit undefined.
160
+ */
161
+ function nativeContractOption(repoRoot) {
162
+ const contract = frozenNativeContractPath(repoRoot);
163
+ return contract === null ? {} : { intentContract: contract };
164
+ }
165
+ export function runAll(policy, options) {
166
+ const { gates, deferred, excluded } = partitionGates(policy, options.stage);
56
167
  const env = options.env ?? {};
57
168
  const skipped = [];
58
169
  const cleanups = [];
@@ -72,6 +183,21 @@ export function runAll(policy, options) {
72
183
  // twice, once as a failed preparation and once as a missing gate,
73
184
  // would read as two problems where there is one.
74
185
  if (binary !== null) {
186
+ // BEFORE ANYTHING IS SPAWNED, and that ordering is the whole of it.
187
+ // runGate makes this check for every other gate and makes it first;
188
+ // for this one the preparation gets there earlier and runs the gate
189
+ // three times, so the check has to be made here as well or the
190
+ // boundary begins after the program the pull request chose has
191
+ // already run. Same builder as runGate's, so the enforce override
192
+ // cannot drift between the two places that produce this outcome.
193
+ const trustBaseRef = options.trustBase?.ref;
194
+ if (trustBaseRef !== undefined) {
195
+ const refusal = refuseHeadControlledBinary(options.repoRoot, trustBaseRef, binary);
196
+ if (refusal !== null) {
197
+ outcomes.push(gateProgramRefused(gate, trustBaseRef, refusal, binary));
198
+ continue;
199
+ }
200
+ }
75
201
  const prepared = prepareIntent({
76
202
  repoRoot: options.repoRoot,
77
203
  binary,
@@ -91,7 +217,15 @@ export function runAll(policy, options) {
91
217
  continue;
92
218
  }
93
219
  if (prepared.kind === 'failed') {
94
- outcomes.push(preparationFailed(gate, `the intent gate could not be prepared at the ${prepared.step} step: ${prepared.detail}`));
220
+ outcomes.push(preparationFailed(
221
+ // ENFORCED under a trust base, by the same argument as
222
+ // `refusedTrustBase` below: `enforce` is itself a control
223
+ // input, this gate produced no findings for it to be a
224
+ // decision about, and a pull-request run where the intent
225
+ // gate could not be prepared is one where nothing judged the
226
+ // intent. Reading the flag here let a base policy with
227
+ // enforce: false report the failure and still exit 0.
228
+ trustBaseRef === undefined ? gate : { ...gate, enforce: true }, `the intent gate could not be prepared at the ${prepared.step} step: ${prepared.detail}`));
95
229
  continue;
96
230
  }
97
231
  intent = prepared.preparation;
@@ -104,6 +238,16 @@ export function runAll(policy, options) {
104
238
  pathValue: options.pathValue,
105
239
  ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
106
240
  ...(intent === undefined ? {} : { intent }),
241
+ // For a run with no preparation: which contract the child will read
242
+ // out of the repository itself. Looked up only for the gate it is
243
+ // about, so no other gate pays for the two stat calls.
244
+ ...(intent !== undefined || gate.role !== 'intent'
245
+ ? {}
246
+ : nativeContractOption(options.repoRoot)),
247
+ // Offered to every child. runGate decides which ones can take it,
248
+ // so a gate with no pull-request mode yet is not handed a flag it
249
+ // would reject, and the reason it was withheld is on the outcome.
250
+ ...(options.trustBase === undefined ? {} : { trustBase: options.trustBase.ref }),
107
251
  }));
108
252
  }
109
253
  }
@@ -138,6 +282,8 @@ export function runAll(policy, options) {
138
282
  skipped,
139
283
  excluded,
140
284
  findings,
285
+ trustBase: options.trustBase ?? null,
286
+ proposals: collectProposals(outcomes, options.trustBase),
141
287
  summary: {
142
288
  blocking: findings.filter((finding) => finding.blocking).length,
143
289
  byProduct,
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Why this ref cannot be a trust base, or null when it can.
3
+ *
4
+ * A string rather than a thrown error, because the caller does not print it
5
+ * and stop: every enabled gate becomes could-not-run carrying this sentence,
6
+ * so the report names the gates that did not run rather than only the ref
7
+ * that was wrong.
8
+ *
9
+ * The four sentences mirror intent-guard's own refusals, which the umbrella
10
+ * would otherwise meet second-hand as a child's exit 2. Refusing here means
11
+ * the umbrella never spawns a child at all on a base it has already decided
12
+ * it cannot judge against, and it means the two gates give a user the same
13
+ * answer to the same mistake.
14
+ */
15
+ export declare function refuseTrustBaseRef(repoRoot: string, ref: string): string | null;
16
+ /**
17
+ * The policy file's contents at a ref, or null when that ref carries none.
18
+ *
19
+ * `git show`, never a checkout switch and never a read from the working
20
+ * tree. The `./` is load-bearing for the same reason it is in intent-guard:
21
+ * it makes git resolve the path relative to the working directory, which is
22
+ * the repository root here, rather than to wherever the repository root would
23
+ * be from somewhere else.
24
+ */
25
+ export declare function readPolicyAtRef(repoRoot: string, ref: string): string | null;
26
+ /**
27
+ * Whether two policy files differ in what they SAY.
28
+ *
29
+ * Compared as parsed documents rather than as bytes, so a reflowed list, a
30
+ * changed quote style or an edited comment is not reported as a proposal to
31
+ * change the rules; a report that cries wolf on whitespace is a report
32
+ * reviewers learn to skip. When either side will not parse, the raw text is
33
+ * compared instead, which is the fail-closed direction: an unparseable head
34
+ * policy is reported as a change rather than quietly matching.
35
+ *
36
+ * BOTH SIDES COME FROM `git show`, base and head alike, and that is not an
37
+ * accident of implementation. intent-guard read its head side from the
38
+ * working tree with a call that follows symlinks, so a pull request that
39
+ * replaced a control file with a link compared equal to the base and was
40
+ * reported as changing nothing. One reader for both sides is the only way the
41
+ * two can be compared on equal terms, and it also means an uncommitted local
42
+ * edit is not reported as something the pull request proposes.
43
+ */
44
+ export declare function policyDiffers(base: string | null, head: string | null): boolean;
45
+ /** The one line the report prints when the head proposes a different policy. */
46
+ export declare const POLICY_PROPOSAL_LINE = "policy changed in this pull request";
47
+ /**
48
+ * One path's tree entry at a ref, or null when the ref has no such path.
49
+ *
50
+ * `ls-tree` rather than `git show`, because the BLOB ID is the thing being
51
+ * compared and `show` prints contents without telling you what kind of entry
52
+ * produced them. The mode comes with it, so a regular file can be told from a
53
+ * symlink, a submodule or a directory in the same read.
54
+ */
55
+ export declare function treeEntryAt(repoRoot: string, ref: string, relativePath: string): {
56
+ mode: string;
57
+ type: string;
58
+ sha: string;
59
+ } | null;
60
+ /**
61
+ * Why this gate's PROGRAM cannot be trusted on a pull-request run, or null.
62
+ *
63
+ * Reading the rules from the base ref is worth nothing if the pull request
64
+ * chooses the program that applies them, and it can, three ways that all look
65
+ * ordinary in a diff:
66
+ *
67
+ * - A base policy whose `command:` points INSIDE the repository, at
68
+ * something like `vendor/vault-guard`. The path came from the base and is
69
+ * therefore approved; the FILE AT THAT PATH is whatever the head commit
70
+ * put there. The umbrella then runs the pull request's own program, is
71
+ * told the scan was clean, and reports a clean scan.
72
+ *
73
+ * - No `command:` at all. Resolution prefers the repository's own
74
+ * `node_modules/.bin` over PATH, deliberately, so that a project pin beats
75
+ * a global install. A head that commits `node_modules/.bin/vault-guard`
76
+ * shadows the real gate, and a stub that answers `--version` with a
77
+ * plausible number passes every check the umbrella makes. The composite
78
+ * action installs nothing, so the plant survives an install step.
79
+ *
80
+ * - A base-approved WRAPPER. `vendor/vault-guard` is byte for byte what the
81
+ * base approved and is the path the policy names; it execs
82
+ * `vendor/impl.sh`, which the head rewrote. Nothing in the diff touches
83
+ * the path the policy names, so a per-file check waves it through. This
84
+ * one was found by a reviewer after the first two were closed, and it is
85
+ * why the unit of approval is a directory rather than a file.
86
+ *
87
+ * THE RULE. A program is acceptable when it is outside the working tree
88
+ * entirely: on PATH, or an absolute `command:` somewhere else on the machine.
89
+ * A pull request cannot write those. A program INSIDE the working tree is
90
+ * acceptable only when BOTH hold: it is a tracked regular file whose blob is
91
+ * IDENTICAL at the trust base and at HEAD, AND the tree object id of its
92
+ * CONTAINING DIRECTORY is identical at those two refs. The first is the same
93
+ * base-versus-head test the rules themselves get, applied to the thing that
94
+ * enforces them; the second extends it to everything beside the program,
95
+ * which is what the wrapper shape needs and what a per-file test cannot give.
96
+ *
97
+ * A tree object id covers a whole subtree in one comparison, so this needs no
98
+ * knowledge of what a wrapper calls. WHAT IS VETTED IS THE PROGRAM FILE AND
99
+ * ITS DIRECTORY SUBTREE AND NOTHING ELSE: anything the program reaches
100
+ * outside that directory is not vetted, so an in-repo gate has to be
101
+ * self-contained within its own directory. That limit is stated in the README
102
+ * in those words, because an adopter has to be able to satisfy it.
103
+ *
104
+ * A PROGRAM AT THE REPOSITORY ROOT IS REFUSED. There the containing directory
105
+ * is the whole repository, so the comparison is the root tree and every pull
106
+ * request that changed anything differs, which is every pull request.
107
+ * Refusing with the remedy in the message beats a rule that silently means
108
+ * "no pull request may change anything".
109
+ *
110
+ * NOTHING HERE READS THE WORKING TREE. Both sides come from `git ls-tree`, so
111
+ * an uncommitted local edit cannot make a file look approved and a tracked
112
+ * file cannot be vouched for by a copy on disk that git has never seen.
113
+ *
114
+ * NODE_MODULES IS NEVER BASE-APPROVED, and the reason is worth stating
115
+ * because "but the lockfile is committed" is the obvious objection. What is
116
+ * under `node_modules` is chosen by the head's own manifest and lockfile and
117
+ * installed by a step that runs before this one; git has no record of those
118
+ * bytes at either ref, so `ls-tree` finds nothing and the rule refuses. That
119
+ * is the correct answer rather than a limitation: a pull request that edits
120
+ * its lockfile to pull a different build of a gate has chosen its own judge
121
+ * just as surely as one that commits a stub.
122
+ *
123
+ * BOTH THE PROGRAM'S OWN PATH AND ITS REALPATH ARE VETTED, because a
124
+ * head-committed symlink is a choice of program too. An in-repo symlink is
125
+ * refused on its OWN entry, before its target matters: it is either untracked
126
+ * or its tree entry is a link rather than a regular file, and either refuses.
127
+ * Vetting the target is what catches a link whose own path is outside the
128
+ * tree pointing into it; it never decides the in-repo case.
129
+ */
130
+ export declare function refuseHeadControlledProgram(repoRoot: string, trustBase: string, programPath: string): string | null;
131
+ /**
132
+ * Whether a gate's reported version is at least `minimum`.
133
+ *
134
+ * Numeric per component, not a string comparison, or "1.10.0" would sort
135
+ * below "1.4.0". A version that cannot be read at all answers FALSE, which is
136
+ * the safe direction for the one thing this decides: whether to hand a child
137
+ * a flag an older build of it would reject outright. A gate that refused an
138
+ * unknown flag would exit non-zero with no JSON, which the umbrella reports
139
+ * as could-not-run, so guessing high turns a working run into a broken one
140
+ * for every repository pinning an older gate.
141
+ */
142
+ export declare function atLeastVersion(version: string | null, minimum: string): boolean;