@rightkit/release 0.6.51 → 0.6.54
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/README.md +1 -1
- package/adapter-env.mjs +16 -105
- package/admission-host.mjs +14 -1
- package/bin/darwin/rightkit-swap +0 -0
- package/bin/rightkit-gate.mjs +609 -404
- package/broker-admission.mjs +122 -2
- package/build-launch.mjs +52 -58
- package/build-release.mjs +2 -2
- package/cargo-ledger.mjs +24 -5
- package/cargo-target-shim.mjs +54 -23
- package/cargo-target.mjs +2 -2
- package/carried-adapter-run.mjs +7 -8
- package/carried-cargo-run.mjs +1 -1
- package/ci-compile-admission.mjs +1 -1
- package/clippy-route.mjs +65 -18
- package/compile-inputs.mjs +91 -15
- package/cross-targets.mjs +5 -3
- package/deps-cargo-lock.mjs +1 -1
- package/deterministic-scans.mjs +789 -259
- package/development.mjs +33 -7
- package/direct-receipt.mjs +3 -5
- package/feature-coverage.mjs +45 -9
- package/feature-partition.mjs +204 -0
- package/feature-sets.mjs +113 -0
- package/gate-acceptance.mjs +187 -115
- package/gate-seam.mjs +352 -0
- package/gate-serve.mjs +34 -2
- package/gate-stages.mjs +6 -2
- package/ghsa-audit.mjs +19 -4
- package/heavy-command.mjs +5 -4
- package/install-tauri-authenticode.mjs +73 -4
- package/ios-dev.mjs +3 -3
- package/ios-package-recipe.mjs +6 -6
- package/linux-setup.mjs +3 -2
- package/local-publish.mjs +113 -17
- package/lock-identity.mjs +24 -100
- package/managed-cargo.mjs +3 -3
- package/managed-root-guard.mjs +2 -2
- package/managed-roots.mjs +3 -3
- package/native-adapters.mjs +41 -244
- package/native-helpers.mjs +1 -1
- package/pack-digest.mjs +1 -1
- package/package-recipe-targets.mjs +3 -3
- package/package.json +2 -2
- package/publication-gate.mjs +29 -6
- package/publish-cargo.mjs +4 -5
- package/publish-local-cargo.mjs +77 -1
- package/qualification-verify.mjs +76 -49
- package/receipt-signature.mjs +104 -0
- package/release-switch-registry.json +4 -0
- package/release-switch-scan.mjs +13 -10
- package/rightkit-versions.json +126 -113
- package/scan-digest.mjs +43 -14
- package/seam-broker.mjs +168 -0
- package/snapshot-check.mjs +4 -1
- package/snapshot-dependency-reuse.mjs +1 -1
- package/snapshot-metadata.mjs +24 -35
- package/snapshot.mjs +328 -49
- package/stage-commands.mjs +59 -5
- package/stage-ledger.mjs +2 -2
- package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
- package/stage-sidecar.mjs +3 -3
- package/tauri-bundle-marker.mjs +5 -2
- package/tauri-locked.mjs +1 -1
- package/tool-build.mjs +8 -6
- package/unit-gate.mjs +40 -10
- package/web-build.mjs +6 -0
- package/broker-handshake.mjs +0 -160
- package/broker-wire.mjs +0 -278
- package/build-ownership.mjs +0 -1578
- package/cargo-shapes.mjs +0 -332
- package/cargo-width.mjs +0 -49
- package/carrier-census.mjs +0 -124
- package/clippy-equivalence.mjs +0 -202
- package/freshness-census.mjs +0 -405
- package/handle-revocation.mjs +0 -100
- package/handle-revocation.rust-vector.json +0 -1
- package/handle-revocation.vectors.json +0 -53
- package/legion-freeze-consumer.mjs +0 -241
- package/linux-qualifier.mjs +0 -83
- package/native-tool-planning.mjs +0 -94
- package/owner-process-proof.mjs +0 -14
- package/ownership-mark.mjs +0 -191
- package/ownership-recover.mjs +0 -78
- package/pnpm-adapter-grammar.mjs +0 -226
- package/provenance-verify.mjs +0 -413
- package/snapshot-broker.mjs +0 -808
- package/snapshot-request.mjs +0 -722
- package/unit-list-compile.mjs +0 -356
package/snapshot-broker.mjs
DELETED
|
@@ -1,808 +0,0 @@
|
|
|
1
|
-
// The gate's production seam for a broker snapshot compile (item 7 rows 7.20 to 7.24; GATE-CONTRACT "Broker interface").
|
|
2
|
-
//
|
|
3
|
-
// createSnapshotBroker builds `deps.snapshotBroker` for runScans on a broker host (Mac, Dell): the commit, the snapshot, the
|
|
4
|
-
// build-ownership handle, the declared inputs READ FROM THE SNAPSHOT, the host's enrolled pins (broker-pins.mjs,
|
|
5
|
-
// never the receipt, an environment variable or a flag), the receipt reader and the managed output roots.
|
|
6
|
-
// runBrokerCargo one cargo call reached by a test on the Mac, through the runtime wrapper's broker mode: its own fresh
|
|
7
|
-
// nonce and carrier, `primaryCwd` from the gate's snapshot-to-checkout map, `callingGate` inherited and never
|
|
8
|
-
// forged, the carrier removed after the call, the signed receipt verified, and a ledger record either way.
|
|
9
|
-
// carryBrokerAdapter one pnpm, node or QA step of a snapshot stage (a broker ADAPTER job, rustright#190 snapshot-adapter-v1), carried
|
|
10
|
-
// the same way: its own carrier and nonce, the cwd of the primary checkout that matches the step's snapshot cwd,
|
|
11
|
-
// the signed receipt and its signed list of nested children (the Tauri CLI's compiles) verified, a ledger record.
|
|
12
|
-
// verifyBrokerLedger the gate's own re-verification of every ledgered call from the broker's signed receipt, with the gate's
|
|
13
|
-
// own commit, snapshot, ownership handle and pins (never the wrapper's say-so), and one use per carrier.
|
|
14
|
-
import crypto from "node:crypto";
|
|
15
|
-
import fs from "node:fs";
|
|
16
|
-
import os from "node:os";
|
|
17
|
-
import path from "node:path";
|
|
18
|
-
import { spawnSync } from "./background-process.mjs";
|
|
19
|
-
import { BROKER_CLIENT_UNRESOLVED, resolveBrokerClient, spawnBrokerClient } from "./broker-client.mjs";
|
|
20
|
-
import { loadBrokerPins } from "./broker-pins.mjs";
|
|
21
|
-
import { ATTEST_STAGE_NONCE_ENV, canonicalJson, carriedCallNonce } from "./provenance-verify.mjs";
|
|
22
|
-
import { resolveManagedRoots } from "./managed-roots.mjs";
|
|
23
|
-
import { forwardedAdapterEnv, withoutSigningEnv } from "./adapter-env.mjs";
|
|
24
|
-
import { carriedShapeDecision } from "./cargo-shapes.mjs";
|
|
25
|
-
import { swiftScratchRefusal } from "./swift-scratch.mjs";
|
|
26
|
-
import { removeCarrier, sweepSnapshotRequests } from "./carrier-census.mjs";
|
|
27
|
-
import { DEFAULT_RETRY_WINDOW_MS, RETRYABLE_OUTCOME_CODES, clientGuardMs, diagnoseControlReply, drainFrames, operationDeadlineEnv, operationOutcomeInOutput, overCapProblem, refusalInCapturedOutput, retryPauseMs, sleepSync } from "./broker-wire.mjs";
|
|
28
|
-
import { OWNERSHIP_ENV, OWNERSHIP_FILE_ENV, markCarriedSend, markCarriedUnsent } from "./ownership-mark.mjs";
|
|
29
|
-
import {
|
|
30
|
-
MANAGED_RUST_ENVIRONMENT_KEYS, SNAPSHOT_REQUEST_SCHEMA, SnapshotRequestError, argvSha256, declaredInputDigestProblems, declaredInputDigestsOf, isCallHandleOf, lockedArgv, observedEnvOf, readDeclaredInputs, readRequestRef, verifySnapshotReceipt, writeSnapshotRequest,
|
|
31
|
-
} from "./snapshot-request.mjs";
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* `env` without any managed Rust variable (MANAGED_RUST_ENVIRONMENT_KEYS, the list the client records as `observedEnv`; case-insensitive,
|
|
35
|
-
* as Windows environments are). The broker refuses a carried request whose observed value of one of them differs from the one it manages
|
|
36
|
-
* itself (service.rs validate_managed_rust_environment), and it supplies its own: so a carried call never forwards one, whatever the
|
|
37
|
-
* caller's shell held (CARGO_HOME, RUSTFLAGS, RUSTC_WRAPPER, ...).
|
|
38
|
-
*/
|
|
39
|
-
export function withoutManagedRustEnv(env) {
|
|
40
|
-
const out = withoutSigningEnv(env); // GB-06: signing material (TAURI_SIGNING_*, TAURI_PRIVATE_KEY, TAURI_KEY_PASSWORD) never reaches the client of a carried call
|
|
41
|
-
for (const key of Object.keys(out)) if (MANAGED_RUST_ENVIRONMENT_KEYS.includes(key.toUpperCase())) delete out[key];
|
|
42
|
-
return out;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** The status a refused or unverified call returns to its caller: cargo's own error status. */
|
|
46
|
-
export const BROKER_REFUSAL_STATUS = 101;
|
|
47
|
-
export const CALLING_GATE_ENV = "RUSTRIGHT_CALLING_GATE";
|
|
48
|
-
|
|
49
|
-
/** The managed `ws` roots a broker pins its generation targets under (BROKER-CONTRACT output pinning). */
|
|
50
|
-
/** The broker pins outputs under its build directory (`<data root>/build-control`, `rightkit-build-control` on a host that has not migrated): `buildControl` is the resolver's. */
|
|
51
|
-
export const brokerOutputRoots = ({ buildControl }) => [path.join(buildControl, "ws")];
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* The longest a read waits for a job that is still live although its client already exited (A7). The client can return before the broker
|
|
55
|
-
* has started the job (a race seen at 16 lanes), so one STATUS read of a live job is not a verdict: the read then follows the job with
|
|
56
|
-
* `rustright attach <id>` (the client's WATCH: it blocks until the job ends and rides out a broker restart; never a poll) and reads STATUS again.
|
|
57
|
-
*/
|
|
58
|
-
export const LIVE_WAIT_MS = 300_000;
|
|
59
|
-
const liveWaitOptions = (env, ms) => ({ ...statusOptions(env), timeout: ms });
|
|
60
|
-
const isLiveRead = (e) => e?.diagnosis?.kind === "live";
|
|
61
|
-
const stillLive = (e, waitedMs) => Object.assign(new SnapshotRequestError(e.code, `${e.message}; the read also waited up to ${Math.round(waitedMs / 1000)} s with \`rustright attach\` (WATCH) for the terminal state and the job was still live`), { diagnosis: e.diagnosis });
|
|
62
|
-
|
|
63
|
-
/** The broker's receipt of one request, read through the RustRight client (`rustright status <id>`), synchronously; a live job is waited for once, bounded (LIVE_WAIT_MS). */
|
|
64
|
-
export function receiptSync({ client, requestId, env, spawn = spawnSync, platform = process.platform, liveWaitMs = LIVE_WAIT_MS }) {
|
|
65
|
-
const read = () => receiptFromReply(spawnBrokerClient(spawn, client, ["status", requestId], statusOptions(env), { platform }), requestId);
|
|
66
|
-
try { return read(); } catch (e) {
|
|
67
|
-
if (!isLiveRead(e) || !(liveWaitMs > 0)) throw e;
|
|
68
|
-
// The attach result is not the verdict (its stream is not a receipt): whatever it ends with, the terminal state is read back by STATUS.
|
|
69
|
-
spawnBrokerClient(spawn, client, ["attach", requestId], liveWaitOptions(env, liveWaitMs), { platform });
|
|
70
|
-
try { return read(); } catch (again) { throw isLiveRead(again) ? stillLive(again, liveWaitMs) : again; }
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
const statusOptions = (env) => ({ encoding: "utf8", env, timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
|
|
74
|
-
|
|
75
|
-
/** The receipt one `rustright status <id>` reply carries, or the typed throw (shared by the synchronous and the asynchronous read). */
|
|
76
|
-
function receiptFromReply(r, requestId) {
|
|
77
|
-
const failedRun = () => new SnapshotRequestError("receipt", `rustright status ${requestId} failed (${r.error?.message ?? `exit ${r.status}`})`);
|
|
78
|
-
if (r.error) throw failedRun();
|
|
79
|
-
let doc;
|
|
80
|
-
// A refused or unavailable reply may arrive with a nonzero exit (the client exits 125 on a REJECTED result): its typed body is still diagnosed (GB-84).
|
|
81
|
-
try { doc = JSON.parse(String(r.stdout)); } catch { throw r.status !== 0 ? failedRun() : new SnapshotRequestError("receipt", `rustright status ${requestId} printed no JSON`); }
|
|
82
|
-
// The status envelope is `{type:"STATUS", id, state, ..., receipt}`: `receipt` is null while the job is live and full once it is
|
|
83
|
-
// terminal. A null receipt after the cargo process exited is not a verdict at once: the caller waits for the terminal state once (receiptSync:
|
|
84
|
-
// `rustright attach`, bounded, never a poll), and a job still live after that is a clear error, never a retry.
|
|
85
|
-
// GB-53: an over-cap outcome is a typed truncation, never a missing-field mystery.
|
|
86
|
-
const over = overCapProblem(doc);
|
|
87
|
-
if (over) throw new SnapshotRequestError(over.code, `rustright status ${requestId}: ${over.message}`);
|
|
88
|
-
// GB-84: the typed envelope is judged BEFORE any receipt validation (diagnoseControlReply, RustRight's own rule, vector control-status-vectors.v1.json). Only a terminal
|
|
89
|
-
// reply with a receipt of this request is a build outcome; a live, unavailable, refused or malformed reply keeps the broker's state, code and identity, is never green, and
|
|
90
|
-
// is reconciled by the durable request id (the gate never resubmits because a diagnosis improved).
|
|
91
|
-
const diagnosis = diagnoseControlReply(doc, requestId);
|
|
92
|
-
const typed = (code, message) => Object.assign(new SnapshotRequestError(code, message), { diagnosis });
|
|
93
|
-
switch (diagnosis.kind) {
|
|
94
|
-
case "terminal": if (r.status !== 0) throw failedRun(); return diagnosis.receipt;
|
|
95
|
-
case "live": throw typed("receipt-not-ready", `rustright status ${requestId} reports the job ${diagnosis.state} with no receipt yet, although its cargo process exited; the gate does not poll or resubmit, so this call is unverified and the request id ${requestId} is the durable handle to reconcile it`);
|
|
96
|
-
case "unavailable": throw typed("broker-unavailable", `rustright status ${requestId}: the broker's front gate cannot serve now (${diagnosis.reason}); the request id ${requestId} is kept for reconciliation, nothing is resubmitted`);
|
|
97
|
-
case "refused": throw typed(`broker-refused-${diagnosis.refusal}`, `rustright status ${requestId}: the broker refused the reply (${diagnosis.code ?? "no code"}: ${diagnosis.message || diagnosis.refusal})${diagnosis.refusal === "suspended" ? "; the job runs again after the broker restarts: ask again then, by this id" : diagnosis.refusal === "paused" ? "; admission is paused, nothing was spawned" : ""}`);
|
|
98
|
-
default: throw typed("receipt", `rustright status ${requestId}: the reply is not a valid status for this request (${diagnosis.message})`);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* `deps.snapshotBroker` for a production run on a broker host. Throws when anything the compile owes cannot be established:
|
|
104
|
-
* no build ownership, no RustRight client, no pins (an app repository without an enrollment), a malformed declared-inputs manifest.
|
|
105
|
-
* There is no way to hand it pins: tests build their own object and inject it as `deps.snapshotBroker`.
|
|
106
|
-
*/
|
|
107
|
-
export function createSnapshotBroker({ env = process.env, platform = process.platform, checkout, commit, snapshot, ownership, client, gateFile, dataRoot, spawn = spawnSync, loadPins = loadBrokerPins, lease = null }) {
|
|
108
|
-
const need = (ok, why) => { if (!ok) throw new SnapshotRequestError("broker", why); };
|
|
109
|
-
need(checkout && path.isAbsolute(checkout), "the primary checkout must be an absolute path");
|
|
110
|
-
need(commit?.sha && commit?.tree, "the commit and its tree are required");
|
|
111
|
-
need(snapshot?.path && path.isAbsolute(snapshot.path) && snapshot.expectedTree === commit.tree, "the snapshot needs an absolute path and the commit's tree as expectedTree");
|
|
112
|
-
need(ownership && typeof ownership.handle === "string" && ownership.handle && typeof ownership.markBrokerSubmit === "function", "a broker snapshot compile needs the gate's build ownership (handle and submit hook)");
|
|
113
|
-
need(typeof client === "string" && (platform === "win32" ? path.win32 : path).isAbsolute(client), "a broker snapshot compile needs the RustRight client (`rustright`) by absolute path");
|
|
114
|
-
// The client the carried map hands every child is the executable itself: on win32 the `rustright.cmd` shim is resolved here, once,
|
|
115
|
-
// so no child re-resolves (or spawns) a .cmd (broker-client.mjs). A shim of any other shape refuses with RK_BROKER_CLIENT_UNRESOLVED.
|
|
116
|
-
try { client = resolveBrokerClient(client, { platform }).file; } catch (e) { throw new SnapshotRequestError(e.code ?? BROKER_CLIENT_UNRESOLVED, e.message); }
|
|
117
|
-
const roots = resolveManagedRoots({ env, platform });
|
|
118
|
-
// `dataRoot` injected names ONE root for everything (a lab or a test); otherwise the pins are RightKit's (gate root) and the outputs the broker's (its build directory).
|
|
119
|
-
const pinsRoot = dataRoot ?? roots.gateRoot;
|
|
120
|
-
const buildControl = dataRoot === undefined ? roots.buildControl : resolveManagedRoots({ env, platform, dataRoot }).buildControl;
|
|
121
|
-
const pins = loadPins({ dataRoot: pinsRoot, platform, gateFile, checkout, spawn });
|
|
122
|
-
// GB-76: carriers a crashed gate left behind are retired on proof (creator dead, nothing live or unknown at the broker under their sub-handle), counted otherwise. Best-effort: a
|
|
123
|
-
// sweep that cannot run never stops a build, and nothing is deleted without proof.
|
|
124
|
-
let carrierSweep = null;
|
|
125
|
-
if (typeof lease === "function") { try { carrierSweep = sweepSnapshotRequests({ controlRoot: roots.controlRoot, snapshot: snapshot.path, lease: (q) => lease({ ...q, env, platform, spawn, client }) }); } catch { carrierSweep = null; } }
|
|
126
|
-
return {
|
|
127
|
-
carrierSweep,
|
|
128
|
-
controlRoot: roots.controlRoot, commit: { sha: commit.sha, tree: commit.tree }, snapshot: { path: snapshot.path, expectedTree: snapshot.expectedTree },
|
|
129
|
-
declaredInputs: readDeclaredInputs(snapshot.path), handle: ownership.handle, markBrokerSubmit: (callHandle, note) => ownership.markBrokerSubmit(callHandle, note), markBrokerUnsent: typeof ownership.markBrokerUnsent === "function" ? (callHandle, reason) => ownership.markBrokerUnsent(callHandle, reason) : undefined,
|
|
130
|
-
pins: { host: pins.host, keyId: pins.keyId, publicKey: pins.publicKey, brokerDigest: pins.brokerDigest }, pinsSource: pins.source,
|
|
131
|
-
checkout: fs.realpathSync.native(checkout), outputRoots: brokerOutputRoots({ buildControl }), platform, client,
|
|
132
|
-
receiptOf: async (requestId) => receiptSync({ client, requestId, env, spawn, platform }),
|
|
133
|
-
// The broker's lease status of one sub-handle (SNAPSHOT_LEASE_STATUS, with the bounded wait): what a cancelled call is reconciled against.
|
|
134
|
-
...(typeof lease === "function" ? { leaseStatus: ({ handle, waitMs = 0 }) => lease({ snapshot: snapshot.path, handle, env, platform, spawn, client, waitMs }) } : {}),
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* What the production gate hands the door as `o.snapshotBroker`: the statement that this gate carries the RustRight snapshot carrier.
|
|
140
|
-
* The door only asks whether a broker host may take the snapshot route; the broker itself (pins, declared inputs, ownership, receipt
|
|
141
|
-
* reader) is built by `createSnapshotBroker` where the snapshot compile runs.
|
|
142
|
-
*/
|
|
143
|
-
export const PRODUCTION_SNAPSHOT_CARRIER = Object.freeze({ kind: "production", create: createSnapshotBroker });
|
|
144
|
-
|
|
145
|
-
/** What a typed refusal means for the caller, appended to the outcome's message: nothing was spawned, and whether waiting helps (BROKER-CONTRACT section 16). */
|
|
146
|
-
function refusalAdvice(refused) {
|
|
147
|
-
if (refused.refusal === "paused") return ": admission is paused and nothing was spawned";
|
|
148
|
-
if (refused.refusal === "recovery-pending") return ": restart recovery of the workspace is still running and nothing was admitted; the call is retried within its deadline";
|
|
149
|
-
if (refused.refusal === "storage-budget-unavailable") return ": the storage budget could not be settled (a maintenance pass is running) and nothing was admitted; the call is retried within its deadline";
|
|
150
|
-
if (refused.refusal === "adapter-pin-required") return ": nothing was spawned; the commit's gradle/wrapper/gradle-wrapper.properties must carry distributionSha256Sum=<64 lowercase hex> for its distribution (the pin is the commit's, so this is not retried)";
|
|
151
|
-
return "";
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** The part of a snapshot broker the wrapper process needs, as the map file carries it (public values only). */
|
|
155
|
-
export const brokerSection = (sb, { sentinel = null } = {}) => {
|
|
156
|
-
const section = {
|
|
157
|
-
client: sb.client, controlRoot: sb.controlRoot, commit: sb.commit, snapshot: sb.snapshot, handle: sb.handle, checkout: sb.checkout,
|
|
158
|
-
pins: sb.pins, outputRoots: sb.outputRoots, platform: sb.platform, sentinel,
|
|
159
|
-
};
|
|
160
|
-
// The gate's own carried calls record their sub-handle through the ownership object it holds. Not enumerable: it never reaches the carrier
|
|
161
|
-
// map a child reads (JSON), whose carried calls record through the inherited ownership file instead (markCarriedRequest).
|
|
162
|
-
if (typeof sb.markBrokerSubmit === "function") Object.defineProperty(section, "markSend", { value: (callHandle) => sb.markBrokerSubmit(callHandle), enumerable: false });
|
|
163
|
-
if (typeof sb.markBrokerUnsent === "function") Object.defineProperty(section, "markUnsent", { value: (callHandle, reason) => sb.markBrokerUnsent(callHandle, reason), enumerable: false });
|
|
164
|
-
// GB-52: the broker's lease status of one sub-handle, asked after a cancelled call (not part of the map a child reads).
|
|
165
|
-
if (typeof sb.leaseStatus === "function") Object.defineProperty(section, "leaseStatus", { value: (query) => sb.leaseStatus(query), enumerable: false });
|
|
166
|
-
return section;
|
|
167
|
-
};
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Records in the shared build-ownership record, immediately before the carried request `callHandle` is sent, that broker work may exist
|
|
171
|
-
* (build-ownership.mjs markBrokerSubmit: `submitted` and the sub-handle). This is the only place a carried call marks, whichever process
|
|
172
|
-
* it runs in: the gate's own, or a right-release child that inherited RIGHTKIT_BUILD_OWNERSHIP (+ _FILE) from it. `section.markSend` is a
|
|
173
|
-
* seam for a caller that holds the ownership object (and for fixtures). Throws when the mark cannot land; the request is then not sent.
|
|
174
|
-
*/
|
|
175
|
-
function markCarriedRequest({ section, env, callHandle }) {
|
|
176
|
-
if (typeof section.markSend === "function") {
|
|
177
|
-
// GB-69: a direct hook's return value is never trusted unchecked: the same assertion the env-file path makes. A hook that did nothing, returned another handle's record, or
|
|
178
|
-
// returned no record of this call's sub-handle refuses the send (nothing is sent), whatever the hook is.
|
|
179
|
-
const marked = section.markSend(callHandle);
|
|
180
|
-
if (marked?.broker?.submitted !== true || !Array.isArray(marked.broker.handles) || !marked.broker.handles.includes(callHandle) || (marked.handle !== undefined && marked.handle !== section.handle)) throw new SnapshotRequestError("ownership", `the build ownership did not record the carried request ${callHandle} under ${section.handle} (the submit hook returned ${marked?.broker ? "another record" : "no record"}); the request is not sent`);
|
|
181
|
-
return marked;
|
|
182
|
-
}
|
|
183
|
-
const handle = env[OWNERSHIP_ENV] ?? process.env[OWNERSHIP_ENV];
|
|
184
|
-
if (handle !== section.handle) throw new SnapshotRequestError("ownership", `the build ownership in the environment (${handle ?? "none"}) is not this call's (${section.handle}); the carried request is not sent`);
|
|
185
|
-
const file = env[OWNERSHIP_FILE_ENV] ?? process.env[OWNERSHIP_FILE_ENV];
|
|
186
|
-
if (!file) throw new SnapshotRequestError("ownership", `${OWNERSHIP_FILE_ENV} is not set: the carried request cannot be recorded in the build ownership, so it is not sent`);
|
|
187
|
-
const marked = markCarriedSend({ file, handle, callHandle });
|
|
188
|
-
if (marked?.broker?.submitted !== true || !marked.broker.handles?.includes(callHandle)) throw new SnapshotRequestError("ownership", `the build ownership did not record the carried request ${callHandle}`);
|
|
189
|
-
return marked;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/** The spawn errors that prove the client process never started, so no byte reached the broker (GB-21). Anything else after a start is ambiguous and is never marked unsent. */
|
|
193
|
-
/** The code of a carried call whose abort signal fired before the client was started (the asynchronous carry): proof that no byte reached the broker. */
|
|
194
|
-
export const CLIENT_CANCELLED_BEFORE_SPAWN = "RK_CLIENT_CANCELLED_BEFORE_SPAWN";
|
|
195
|
-
const NO_SPAWN_CODES = new Set(["ENOENT", "EACCES", "EPERM", "EINVAL", "ENOEXEC", "ENOTDIR", BROKER_CLIENT_UNRESOLVED, CLIENT_CANCELLED_BEFORE_SPAWN]);
|
|
196
|
-
export const provenNoSpawn = (error) => Boolean(error) && NO_SPAWN_CODES.has(error.code);
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* GB-21: whether the RustRight client can be started at all, checked BEFORE the ownership is marked (a mark records that broker work may exist, so a call that cannot start
|
|
200
|
-
* must not leave one). An absolute client path must exist and (on POSIX) be executable; a bare name is resolved by the spawn itself and is left to it.
|
|
201
|
-
*/
|
|
202
|
-
export function clientStartable(client, platform = process.platform) {
|
|
203
|
-
if (typeof client !== "string" || client === "") return "no RustRight client is named";
|
|
204
|
-
if (!(platform === "win32" ? path.win32 : path).isAbsolute(client)) return null;
|
|
205
|
-
if (platform !== process.platform) return null; // a simulated platform (a test) has no file system of its own to probe
|
|
206
|
-
try { const meta = fs.statSync(client); if (!meta.isFile()) return `${client} is not a file`; if (platform !== "win32") fs.accessSync(client, fs.constants.X_OK); return null; } catch (e) { return `${client} cannot be started (${e.code ?? e.message})`; }
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/** Records, after a client that provably never started, that this sub-handle was never sent (ownership: broker.unsent). Best-effort: a mark that cannot land leaves the record held, never released. */
|
|
210
|
-
function markCarriedUnsentRequest({ section, env, callHandle, reason }) {
|
|
211
|
-
try {
|
|
212
|
-
if (typeof section.markUnsent === "function") { section.markUnsent(callHandle, reason); return true; }
|
|
213
|
-
const handle = env[OWNERSHIP_ENV] ?? process.env[OWNERSHIP_ENV]; const file = env[OWNERSHIP_FILE_ENV] ?? process.env[OWNERSHIP_FILE_ENV];
|
|
214
|
-
if (handle !== section.handle || !file) return false;
|
|
215
|
-
markCarriedUnsent({ file, handle, callHandle, reason });
|
|
216
|
-
return true;
|
|
217
|
-
} catch { return false; }
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const escapes = (rel) => rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
|
|
221
|
-
const inside = (child, parent) => { const rel = path.relative(parent, child); return rel === "" || !escapes(rel); };
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* The primary-checkout counterpart of a snapshot directory, spelled lexically (BROKER-CONTRACT section 16, GB-16): `base` (the logical checkout path) joined with the snapshot-relative `rel`,
|
|
225
|
-
* which `join` normalises, so the result is absolute and holds no `.` or `..`. Nothing about the checkout's present state decides it. `pathApi` is the platform's path module (a Windows
|
|
226
|
-
* spelling is judged with `path.win32`).
|
|
227
|
-
*/
|
|
228
|
-
export const lexicalCounterpart = ({ base, rel, pathApi = path }) => pathApi.join(base, rel);
|
|
229
|
-
|
|
230
|
-
/**
|
|
231
|
-
* The nearest directory at or above `lexical` that exists (`isDirectory(p)`), or null when none does. A path that became a plain file is passed over: the nearest DIRECTORY is what a client
|
|
232
|
-
* can start in.
|
|
233
|
-
*/
|
|
234
|
-
export function nearestExistingDirectory(lexical, { isDirectory = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } }, pathApi = path } = {}) {
|
|
235
|
-
for (let p = lexical; ; p = pathApi.dirname(p)) {
|
|
236
|
-
if (isDirectory(p)) return p;
|
|
237
|
-
if (pathApi.dirname(p) === p) return null;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/** `p` as the file system names it when it exists; when it is gone, the real path of its nearest existing directory plus what is left below it (a lexical path stays one). */
|
|
242
|
-
export function canonicalCounterpart(p) {
|
|
243
|
-
try { return fs.realpathSync.native(p); } catch (e) { if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; }
|
|
244
|
-
const ancestor = nearestExistingDirectory(p);
|
|
245
|
-
if (ancestor === null) throw Object.assign(new Error(`${p} has no existing ancestor`), { code: "ENOENT" });
|
|
246
|
-
return path.join(fs.realpathSync.native(ancestor), path.relative(ancestor, p));
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/**
|
|
250
|
-
* The primary-checkout counterpart of a directory of the snapshot (GB-16). The carrier's `primaryCwd` is that counterpart spelled lexically; the RustRight client accepts it when its own working
|
|
251
|
-
* directory is it, or, when it is gone (an older commit built after the primary checkout removed the directory), the nearest directory of it that still exists, and then names the
|
|
252
|
-
* counterpart as the request's workspace (the attestation hashes that workspace). The broker maps by the snapshot-relative path. So a removed counterpart is no refusal: this returns
|
|
253
|
-
* `{ dir, spawnCwd, removed }`: `dir` the lexical counterpart (what the carrier names), `spawnCwd` the real directory the client is started in (the counterpart itself when it exists, else the
|
|
254
|
-
* real path of its nearest existing ancestor inside the checkout). An existing counterpart, and the ancestor of a removed one, are realpathed, so a link that leaves the checkout is still
|
|
255
|
-
* refused (`..._ESCAPE`); anything else the file system will not say (permission) is `..._UNREADABLE`. Returns `{ dir, spawnCwd, removed }` or `{ refusal: { code, message } }`.
|
|
256
|
-
*/
|
|
257
|
-
export function checkoutCounterpart({ base, rel, checkout, codePrefix }) {
|
|
258
|
-
const escapeCode = `${codePrefix}_ESCAPE`; const unreadableCode = `${codePrefix}_UNREADABLE`;
|
|
259
|
-
// The logical base may be spelled through a link the checkout path is not (a map built from a realpath): resolve the base alone when it exists.
|
|
260
|
-
let root = base; try { root = fs.realpathSync.native(base); } catch { /* an absent base is judged by its spelling */ }
|
|
261
|
-
const lexical = lexicalCounterpart({ base: root, rel });
|
|
262
|
-
if (!inside(lexical, checkout)) return { refusal: { code: escapeCode, message: `${lexical} is outside the primary checkout ${checkout}` } };
|
|
263
|
-
let real;
|
|
264
|
-
try { real = fs.realpathSync.native(lexical); }
|
|
265
|
-
catch (e) {
|
|
266
|
-
if (e.code !== "ENOENT" && e.code !== "ENOTDIR") return { refusal: { code: unreadableCode, message: `${lexical} cannot be resolved (${e.code ?? e.message})` } };
|
|
267
|
-
const ancestor = nearestExistingDirectory(lexical);
|
|
268
|
-
let spawnCwd = null;
|
|
269
|
-
try { spawnCwd = ancestor === null ? null : fs.realpathSync.native(ancestor); } catch (error) { return { refusal: { code: unreadableCode, message: `${ancestor} cannot be resolved (${error.code ?? error.message})` } }; }
|
|
270
|
-
if (spawnCwd === null || !inside(spawnCwd, checkout)) return { refusal: { code: escapeCode, message: `${spawnCwd ?? ancestor ?? lexical} is outside the primary checkout ${checkout}` } };
|
|
271
|
-
return { dir: lexical, spawnCwd, removed: true };
|
|
272
|
-
}
|
|
273
|
-
try { if (!fs.statSync(real).isDirectory()) return { refusal: { code: unreadableCode, message: `${real} is not a directory` } }; } catch (e) { return { refusal: { code: unreadableCode, message: `${real} cannot be read (${e.code ?? e.message})` } }; }
|
|
274
|
-
if (!inside(real, checkout)) return { refusal: { code: escapeCode, message: `${real} is outside the primary checkout ${checkout}` } };
|
|
275
|
-
return { dir: real, spawnCwd: real, removed: false };
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/** Per-call carrier variables, in both spellings (rustright-cli shims.rs LEGACY_ENV_SPELLINGS: the current RUSTRIGHT_* name wins over the legacy one). */
|
|
279
|
-
const CARRIER_CALL_VARIABLES = ["SNAPSHOT_REQUEST", "ATTEST_NONCE", "REQUEST_ID_FILE", "PARENT_REQUEST_ID", "PARENT_CAPABILITY_TOKEN", "SNAPSHOT_ADMISSION"];
|
|
280
|
-
/** The carrier variables of an environment, by name: a call's carrier is set by the gate for that one call and never inherited. */
|
|
281
|
-
export function inheritedCarrierEnv(env) {
|
|
282
|
-
const found = [];
|
|
283
|
-
for (const [key, value] of Object.entries(env ?? {})) {
|
|
284
|
-
const upper = key.toUpperCase();
|
|
285
|
-
const bare = upper.startsWith("RUSTRIGHT_") ? upper.slice("RUSTRIGHT_".length) : upper.startsWith("RIGHTKIT_") ? upper.slice("RIGHTKIT_".length) : null;
|
|
286
|
-
if (bare === null) continue;
|
|
287
|
-
if (CARRIER_CALL_VARIABLES.includes(bare) || (bare === "CHECK_ADMISSION" && String(value).trim() === "1")) found.push(key);
|
|
288
|
-
}
|
|
289
|
-
return found;
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* GB-52: a call that ran out its operation deadline is cancelled BY ID by the client, which then polls the terminal state. The gate does not take that for a release: it asks the broker once, with
|
|
294
|
-
* a bounded wait, what it holds under the call's sub-handle (SNAPSHOT_LEASE_STATUS members, GB-23/GB-85). `reaped` is true only for a well-formed REAPED answer (every submission under the
|
|
295
|
-
* handle durably complete); ACTIVE, UNKNOWN, a wait that timed out, a reader that is absent or throws all leave ownership held, and the outcome says which. Never resubmits.
|
|
296
|
-
*/
|
|
297
|
-
function reconcileAfterCancel({ section, callHandle, childEnv }) {
|
|
298
|
-
// This read BLOCKS the event loop for up to 30 s (a synchronous client call). Only the synchronous carry (carryBrokerAdapter, a stage step that blocks anyway) reaches it: the
|
|
299
|
-
// asynchronous carry (a Swift scan next to the gate's other scans) never calls it, because it must not freeze them; it reports the sub-handle UNKNOWN instead (deferredReconcile).
|
|
300
|
-
const cancelWait = Number(childEnv?.RUSTRIGHT_CANCEL_WAIT_MS);
|
|
301
|
-
const waitMs = Math.min(30_000, Number.isFinite(cancelWait) && cancelWait >= 0 ? Math.trunc(cancelWait) : 30_000);
|
|
302
|
-
if (typeof section.leaseStatus !== "function") return { reaped: false, subHandle: { handle: callHandle, state: "UNKNOWN", why: "this gate has no lease reader" }, note: `the gate cannot ask the broker about sub-handle ${callHandle}, so ownership stays UNKNOWN until every sub-handle is REAPED` };
|
|
303
|
-
let status;
|
|
304
|
-
try { status = section.leaseStatus({ handle: callHandle, waitMs }); } catch (e) { status = { state: "UNKNOWN", why: e.message }; }
|
|
305
|
-
const state = status?.state ?? "UNKNOWN";
|
|
306
|
-
const subHandle = { handle: callHandle, state, why: status?.why ?? null, ...(status?.waitedMs !== undefined ? { waitedMs: status.waitedMs } : {}), ...(status?.waitTimedOut !== undefined ? { waitTimedOut: status.waitTimedOut } : {}), ...(Array.isArray(status?.members) ? { members: status.members } : {}) };
|
|
307
|
-
if (state === "REAPED") return { reaped: true, subHandle, note: `after the cancel the broker reports sub-handle ${callHandle} REAPED (every submission under it is settled)` };
|
|
308
|
-
return { reaped: false, subHandle, note: `after the cancel the broker reports sub-handle ${callHandle} still ${state}${status?.why ? ` (${status.why})` : ""}: ownership stays held until it is REAPED; the job is not resubmitted` };
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/** What the asynchronous carry reports after a cancel or an operation deadline instead of the blocking lease read: ownership stays held, fail closed, and is settled when every sub-handle is REAPED. */
|
|
312
|
-
function deferredReconcile(callHandle) {
|
|
313
|
-
return { reaped: false, subHandle: { handle: callHandle, state: "UNKNOWN", why: "the asynchronous carry reads no lease: the lease reader blocks the event loop for up to 30 s" }, note: `the asynchronous carry does not read the broker's lease (that read blocks the gate for up to 30 s), so sub-handle ${callHandle} stays UNKNOWN and ownership stays held until every sub-handle is REAPED; the job is not resubmitted` };
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* GB-52, GB-78, GB-39 (BROKER-CONTRACT section 16): a carried call the broker answered with a refusal that clears on its own (RK_RECOVERY_PENDING, RK_STORAGE_BUDGET_UNAVAILABLE) or whose
|
|
318
|
-
* connection never opened (RK_BROKER_BUSY: every pipe instance busy, no byte sent) is a wait. The gate pauses (250 ms doubling to 5 s) and sends the call again within the call's own
|
|
319
|
-
* deadline (`deadlineMs`, else DEFAULT_RETRY_WINDOW_MS), each attempt with its own carrier, nonce and sub-handle (a handle is spent once; the refused attempt is a settled, spawned:false
|
|
320
|
-
* submission, a busy one is recorded unsent) and under ONE ledger id, so the final record is the call's. It is never success and never a generic failure: when the deadline passes the
|
|
321
|
-
* outcome keeps the broker's own code (`broker-refused-recovery-pending`, `broker-refused-storage-budget-unavailable`, `broker-busy`) and says how long it waited. Every other outcome, a
|
|
322
|
-
* verified one, RK_ADAPTER_PIN_REQUIRED and RK_OPERATION_DEADLINE included, is returned at once. `now` and `sleep` are seams for tests.
|
|
323
|
-
*/
|
|
324
|
-
function carryWithRetries(once, call) {
|
|
325
|
-
const { deadlineMs = null, now = Date.now, sleep = sleepSync, err = () => {}, record = () => {}, ...rest } = call;
|
|
326
|
-
const window = deadlineMs !== null && Number.isFinite(deadlineMs) ? Math.max(1, Math.trunc(deadlineMs)) : DEFAULT_RETRY_WINDOW_MS;
|
|
327
|
-
const started = now();
|
|
328
|
-
const ledgerId = crypto.randomUUID();
|
|
329
|
-
let attempt = 0; let held = []; let result;
|
|
330
|
-
for (;;) {
|
|
331
|
-
attempt += 1;
|
|
332
|
-
held = [];
|
|
333
|
-
const remaining = Math.max(1, window - (now() - started));
|
|
334
|
-
result = once({ ...rest, record, err: (m) => held.push(m), deadlineMs: deadlineMs === null ? null : remaining, ledgerId });
|
|
335
|
-
const code = result.outcome?.status === "unverified" ? result.outcome.code : null;
|
|
336
|
-
if (code === null || !RETRYABLE_OUTCOME_CODES.has(code)) break;
|
|
337
|
-
const pause = retryPauseMs(attempt);
|
|
338
|
-
if (window - (now() - started) <= pause) {
|
|
339
|
-
const elapsed = now() - started;
|
|
340
|
-
const message = `${result.outcome.message}; retried ${attempt - 1} time(s) over ${elapsed} ms and the call's ${window} ms deadline passed before the broker would take it: it is a wait that did not clear, never a result`;
|
|
341
|
-
result = { ...result, outcome: { ...result.outcome, message, attempts: attempt, retried: attempt - 1 } };
|
|
342
|
-
try { record({ id: ledgerId, mode: "broker", status: "unverified", code: result.outcome.code, message }); } catch { /* the final record above stands */ }
|
|
343
|
-
held.push(`rightkit-gate: ${result.outcome.code}: ${message}`);
|
|
344
|
-
break;
|
|
345
|
-
}
|
|
346
|
-
sleep(pause);
|
|
347
|
-
// The next attempt's pending record replaces this attempt's outcome fields in the ledger (one id).
|
|
348
|
-
try { record({ id: ledgerId, mode: "broker", status: "pending", code: null, message: null }); } catch { /* the attempt records its own pending state */ }
|
|
349
|
-
}
|
|
350
|
-
for (const m of held) err(m);
|
|
351
|
-
return result;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* One carried cargo call: its own fresh nonce and carrier, `primaryCwd` from the gate's snapshot-to-checkout map, `callingGate`
|
|
356
|
-
* inherited and never forged, the carrier removed after the call, the signed receipt verified, and a ledger record either way.
|
|
357
|
-
* `workspace` is the real snapshot path of the cargo workspace the call resolved; `checkoutWorkspace` its counterpart in the primary
|
|
358
|
-
* checkout, from the gate's own map. `stdio` is the client's (`inherit`, or `capture` for a caller that reads cargo's output).
|
|
359
|
-
* Returns `{ status, outcome, stdout, stderr }`; `outcome` is the ledgered record's outcome (`verified` with `outputDir`, or not).
|
|
360
|
-
* Refused before anything runs: a carrier or per-call carrier variable already in the environment, no calling gate, a working
|
|
361
|
-
* directory with no counterpart in the checkout. An output directory of the caller's is dropped (the broker pins it).
|
|
362
|
-
*/
|
|
363
|
-
export function carryBrokerCargo(call) { return carryWithRetries(carryBrokerCargoOnce, call); }
|
|
364
|
-
|
|
365
|
-
function carryBrokerCargoOnce({ words, cwd, env, section, workspace, checkoutWorkspace, record, spawn = spawnSync, err, tmp = os.tmpdir(), stdio = "inherit", deadlineMs = null, ledgerId = null }) {
|
|
366
|
-
words = lockedArgv(words); // a build or run is always locked, and a standard alias is expanded first (snapshot-request.mjs lockedArgv)
|
|
367
|
-
const id = ledgerId ?? crypto.randomUUID();
|
|
368
|
-
const base = { id, mode: "broker", cwd, argv: [...words] };
|
|
369
|
-
const refuse = (code, message) => { record({ ...base, status: "refused", code, message }); err(`rightkit-gate: ${code}: ${message}`); return { status: BROKER_REFUSAL_STATUS, outcome: { status: "refused", code, message }, stdout: "", stderr: `rightkit-gate: ${code}: ${message}\n` }; };
|
|
370
|
-
// GB-01: the one command-shape table (cargo-shapes.mjs, exercised against RustRight's cargo-shapes vector) decides BEFORE anything is marked or sent:
|
|
371
|
-
// a shape the broker refuses inside a snapshot (tree, pkgid, verify-project, a bare metadata, a write-form fmt, help, ...) launches zero processes.
|
|
372
|
-
const shape = carriedShapeDecision(words);
|
|
373
|
-
if (!shape.ok) return refuse(shape.code, shape.message);
|
|
374
|
-
const gate = env[CALLING_GATE_ENV];
|
|
375
|
-
if (typeof gate !== "string" || !gate.trim()) return refuse("RK_CARGO_BROKER_NO_GATE", `${CALLING_GATE_ENV} is not set: the call names no gate, and the wrapper never forges one`);
|
|
376
|
-
const inherited = inheritedCarrierEnv(env);
|
|
377
|
-
if (inherited.length) return refuse("RK_CARGO_BROKER_INHERITED_ENV", `${inherited.join(", ")} ${inherited.length > 1 ? "are" : "is"} already in the environment; a carrier is set by the gate for one call only, so a nested or replayed call is refused`);
|
|
378
|
-
// The broker pins the output directory, so a carried call passes none: the caller's CARGO_TARGET_DIR (and the gate's unbound sentinel)
|
|
379
|
-
// are dropped here. The receipt's `outputDir` is verified to be the broker's generation target under the managed `ws` root, outside the
|
|
380
|
-
// snapshot and the checkout, whatever the environment held, so dropping it can only make the call safer.
|
|
381
|
-
const clientEnv = withoutManagedRustEnv(env);
|
|
382
|
-
// There is no stage grant any more (one model: a snapshot stage's compiles run nested under an adapter job); an inherited one is dropped, never forwarded.
|
|
383
|
-
for (const key of Object.keys(clientEnv)) if (/^(RUSTRIGHT|RIGHTKIT)_SNAPSHOT_GRANT$/i.test(key)) delete clientEnv[key];
|
|
384
|
-
// A release-bound stage's nonce (RIGHTKIT_ATTEST_STAGE_NONCE) is read here and never reaches the client: this call's nonce is derived from it.
|
|
385
|
-
const stageNonce = env[ATTEST_STAGE_NONCE_ENV];
|
|
386
|
-
for (const key of Object.keys(clientEnv)) if (key.toUpperCase() === ATTEST_STAGE_NONCE_ENV) delete clientEnv[key];
|
|
387
|
-
let realCwd; let checkoutCwd; let rel;
|
|
388
|
-
try {
|
|
389
|
-
realCwd = fs.realpathSync.native(cwd);
|
|
390
|
-
rel = path.relative(workspace, realCwd);
|
|
391
|
-
if (escapes(rel)) throw new Error(`${realCwd} is not inside the workspace ${workspace}`);
|
|
392
|
-
} catch (e) { return refuse("RK_CARGO_BROKER_CWD", `the call's working directory is not inside its workspace (${e.message})`); }
|
|
393
|
-
const counterpart = checkoutCounterpart({ base: checkoutWorkspace, rel, checkout: section.checkout, codePrefix: "RK_CARGO_BROKER_COUNTERPART" });
|
|
394
|
-
if (counterpart.refusal) return refuse(counterpart.refusal.code, counterpart.refusal.message);
|
|
395
|
-
checkoutCwd = counterpart.dir; const spawnCwd = counterpart.spawnCwd;
|
|
396
|
-
let inputs;
|
|
397
|
-
try { inputs = readDeclaredInputs(section.snapshot.path); } catch (e) { return refuse("RK_CARGO_BROKER_DECLARED_INPUTS", e.message); }
|
|
398
|
-
const refDir = fs.mkdtempSync(path.join(tmp, "rk-snapreq-"));
|
|
399
|
-
let made = null;
|
|
400
|
-
try {
|
|
401
|
-
try {
|
|
402
|
-
// Under a release-bound stage the nonce is derived from the stage's, this call's directory (relative to the primary checkout, posix) and
|
|
403
|
-
// its argv, so the hosted admission can recompute it from the stage's rows (provenance-verify.mjs carriedCallNonce); otherwise it is fresh.
|
|
404
|
-
const nonce = /^[0-9a-f]{64}$/.test(stageNonce ?? "") ? carriedCallNonce({ stageNonce, cwd: path.relative(section.checkout, checkoutCwd).split(path.sep).join("/") || ".", argv: words }) : undefined;
|
|
405
|
-
made = writeSnapshotRequest({ controlRoot: section.controlRoot, commit: section.commit, snapshot: section.snapshot, declaredInputs: inputs, handle: section.handle, primaryCwd: checkoutCwd, argv: words, nonce, requestIdFile: path.join(refDir, "request.json") });
|
|
406
|
-
} catch (e) { return refuse("RK_CARGO_BROKER_CARRIER", e.message); }
|
|
407
|
-
try { record({ ...base, status: "pending", nonce: made.carrier.nonce, requestRef: path.join(refDir, "request.json"), ownershipHandle: made.carrier.ownership.handle, checkoutCwd, spawnCwd }); } catch (e) { removeCarrier(made.file); return refuse("RK_CARGO_LEDGER_ERROR", `the call cannot be recorded (${e.message}); it does not run`); }
|
|
408
|
-
// GB-52: the call's operation deadline (the caller's own cap is never replaced) and an outer guard past the client's own cancel wait.
|
|
409
|
-
const childEnv = { RUST_BACKTRACE: clientEnv.RUST_BACKTRACE ?? "1", ...clientEnv, ...made.env, ...operationDeadlineEnv({ env: clientEnv, deadlineMs }) };
|
|
410
|
-
const guard = clientGuardMs(childEnv);
|
|
411
|
-
const capture = stdio === "capture";
|
|
412
|
-
// Broker work may exist from the next statement on: the ownership records this request's sub-handle first (a mark that does not land sends nothing).
|
|
413
|
-
{ const startable = clientStartable(section.client, section.platform); if (startable) { removeCarrier(made.file); return refuse("RK_CARGO_BROKER_CLIENT", `${startable}; nothing was marked or sent`); } }
|
|
414
|
-
try { markCarriedRequest({ section, env, callHandle: made.carrier.ownership.handle }); } catch (e) { removeCarrier(made.file); return refuse("RK_CARGO_BROKER_OWNERSHIP", e.message); }
|
|
415
|
-
const r = spawnBrokerClient(spawn, section.client, ["cargo", ...words], capture ? { cwd: spawnCwd, env: childEnv, encoding: "utf8", maxBuffer: 1 << 28, windowsHide: true, ...(guard ? { timeout: guard } : {}) } : { cwd: spawnCwd, env: childEnv, stdio: "inherit", ...(guard ? { timeout: guard } : {}) }, { platform: section.platform });
|
|
416
|
-
removeCarrier(made.file);
|
|
417
|
-
// GB-21: a client that provably never started sent nothing: that sub-handle is recorded unsent under the ownership lock, so it does not wedge a later reclaim. Any other
|
|
418
|
-
// failure after a start (a lost connection, a timeout, an exit before a reference) is ambiguous and stays held, reconciled by the request id.
|
|
419
|
-
if (r.error && provenNoSpawn(r.error)) markCarriedUnsentRequest({ section, env, callHandle: made.carrier.ownership.handle, reason: `the RustRight client did not start (${r.error.code})` });
|
|
420
|
-
let outcome;
|
|
421
|
-
let ref = null;
|
|
422
|
-
try {
|
|
423
|
-
if (r.error) throw new SnapshotRequestError(r.error.code === BROKER_CLIENT_UNRESOLVED ? BROKER_CLIENT_UNRESOLVED : "spawn", `the RustRight client did not start (${r.error.message})`);
|
|
424
|
-
ref = readRequestRef(path.join(refDir, "request.json"));
|
|
425
|
-
const receipt = receiptSync({ client: section.client, requestId: ref.requestId, env: clientEnv, spawn, platform: section.platform });
|
|
426
|
-
const observedEnv = observedEnvOf(clientEnv, section.platform);
|
|
427
|
-
const { evidence, attribution, toolchain, requestDigest } = verifySnapshotReceipt(receipt, { pins: section.pins, jobId: ref.requestId, carrier: made.carrier, argv: words, workspace: ref.workspace, observedEnv, checkout: section.checkout, outputRoots: section.outputRoots, platform: section.platform });
|
|
428
|
-
// attribution and toolchain are recorded as the broker signed them (a consumer that needs per-package attribution treats available:false as FAILED).
|
|
429
|
-
outcome = { status: "verified", requestId: ref.requestId, requestDigest, workspace: ref.workspace, observedEnv, outputDir: evidence.outputDir, treeAtStart: evidence.snapshot.treeAtStart, treeAtExit: evidence.snapshot.treeAtExit, attribution, toolchain };
|
|
430
|
-
} catch (e) {
|
|
431
|
-
outcome = { status: "unverified", code: e.code ?? "error", message: e.message, ...(ref ? { requestId: ref.requestId, workspace: ref.workspace } : {}) };
|
|
432
|
-
}
|
|
433
|
-
outcome = { ...outcome, clientStatus: r.status ?? null, clientSignal: r.signal ?? null }; // A7: the client's own exit, kept with every outcome
|
|
434
|
-
const out = capture ? { stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? "") } : { stdout: "", stderr: "" };
|
|
435
|
-
// GB-54: a request the broker REFUSED (admission paused, a suspended or unknown job, a cutover drain) never started: the client's typed REJECTED result is kept as the outcome's
|
|
436
|
-
// code ("admission is paused; nothing was spawned"), not folded into a missing request reference. It is never a build outcome.
|
|
437
|
-
if (outcome.status !== "verified" && capture) {
|
|
438
|
-
const refused = refusalInCapturedOutput(`${out.stdout}\n${out.stderr}`);
|
|
439
|
-
if (refused?.code === "RK_TOOLCHAIN_IDENTITY_UNAVAILABLE") outcome = { status: "unverified", code: "toolchain-unavailable", message: `the broker refused the compile before it started: it could not build the toolchain identity (RK_TOOLCHAIN_IDENTITY_UNAVAILABLE: ${refused.message}); nothing ran`, ...(outcome.requestId ? { requestId: outcome.requestId, workspace: outcome.workspace } : {}) };
|
|
440
|
-
else if (refused) outcome = { status: "unverified", code: `broker-refused-${refused.refusal}`, message: `the broker refused the request (${refused.code ?? "no code"}: ${refused.message || refused.refusal})${refusalAdvice(refused)}`, ...(outcome.requestId ? { requestId: outcome.requestId, workspace: outcome.workspace } : {}) };
|
|
441
|
-
}
|
|
442
|
-
// GB-52: a call that ran out its operation deadline, or whose client was stopped by the outer guard, is NOT a build outcome: the client cancelled by id and watched for the terminal
|
|
443
|
-
// state, and an unobserved state keeps ownership UNKNOWN (the sub-handle stays recorded; reconciled by the request id, never resubmitted). Busy and unavailable are named apart.
|
|
444
|
-
if (outcome.status !== "verified") {
|
|
445
|
-
const seen = operationOutcomeInOutput(`${out.stdout}\n${out.stderr}`) ?? (r.error?.code === "ETIMEDOUT" ? { code: "operation-deadline", deadlineMs: null, requestId: ref?.requestId ?? null, cancelConfirmed: null, terminalState: null, guard: true } : null);
|
|
446
|
-
if (seen) outcome = { status: "unverified", code: seen.code, message: seen.code === "operation-deadline" ? `the operation deadline${seen.deadlineMs ? ` of ${seen.deadlineMs} ms` : ""} passed${seen.guard ? " and the client was stopped by the gate's outer guard" : ""}; request ${seen.requestId ?? ref?.requestId ?? "unknown"}: cancelConfirmed: ${seen.cancelConfirmed ?? "unknown"}, terminal state: ${seen.terminalState ?? "not observed"}; the job is neither abandoned nor resubmitted and ownership stays UNKNOWN until every sub-handle is REAPED` : seen.code === "broker-busy" ? "every broker connection was busy (RK_BROKER_BUSY: a wait, not an outage); nothing was admitted" : "the broker was unavailable (RK_BROKER_UNAVAILABLE)", ...(ref ? { requestId: ref.requestId, workspace: ref.workspace } : {}) };
|
|
447
|
-
}
|
|
448
|
-
// The client's own account of a call that never got a request reference (it refused the carrier, or the broker refused the request before
|
|
449
|
-
// accepting it): its `rustright: <reason>` lines, which capture mode would otherwise drop (HeardRight Mac package 2026-11-02: exit 125 with
|
|
450
|
-
// no reason in the gate log). A bare `rustright: request <id>` line is not a reason.
|
|
451
|
-
if (outcome.status === "unverified" && capture && ref === null) {
|
|
452
|
-
const said = out.stderr.split(/\r?\n/).map((line) => line.trim()).filter((line) => /^rustright(?:[: ]|-)/.test(line) && !/^rustright: request [0-9a-f-]+$/.test(line));
|
|
453
|
-
if (said.length) outcome = { ...outcome, message: `${outcome.message}; the RustRight client said (exit ${r.status ?? "none"}): ${said.slice(-3).join(" | ").slice(0, 600)}` };
|
|
454
|
-
}
|
|
455
|
-
if (outcome.status === "unverified" && outcome.code === "operation-deadline") {
|
|
456
|
-
const settled = reconcileAfterCancel({ section, callHandle: made.carrier.ownership.handle, childEnv });
|
|
457
|
-
outcome = { ...outcome, message: `${outcome.message}; ${settled.note}`, reaped: settled.reaped, subHandle: settled.subHandle };
|
|
458
|
-
}
|
|
459
|
-
// RK_BROKER_BUSY with no request reference: the connection never opened, so no byte reached the broker. That is the gate's own proof that this sub-handle was never sent (GB-21), recorded under
|
|
460
|
-
// the ownership lock so the retry's own sub-handle, not this one, is what the stage waits on; a busy answer after a reference exists (a reconnect) proves nothing of the kind.
|
|
461
|
-
if (outcome.status === "unverified" && outcome.code === "broker-busy" && ref === null) markCarriedUnsentRequest({ section, env, callHandle: made.carrier.ownership.handle, reason: "every broker connection was busy (RK_BROKER_BUSY): the connection never opened and no byte was sent" });
|
|
462
|
-
// A typed REJECTED result (admission paused, a cutover drain, ...) with no request reference: the broker refused the submit before it admitted anything, so nothing
|
|
463
|
-
// runs under this sub-handle and the broker will never list it as a member. Recorded unsent now, or a dead owner's record could never be reclaimed (HeardRight Mac,
|
|
464
|
-
// 2026-11-02: 42 paused refusals left a member-less sub-handle the broker answers UNKNOWN for).
|
|
465
|
-
else if (outcome.status === "unverified" && /^broker-refused-/.test(String(outcome.code)) && ref === null) markCarriedUnsentRequest({ section, env, callHandle: made.carrier.ownership.handle, reason: `the broker refused the submit before admitting it (${outcome.code}): nothing was spawned` });
|
|
466
|
-
// GB-53: captured output that lost a frame to FRAME_OVER_CAP (or a result the broker replaced with RK_RESPONSE_OVER_CAP) is truncated: refused, never read as complete.
|
|
467
|
-
if (outcome.status === "verified" && capture) {
|
|
468
|
-
const drained = drainFrames(`${out.stdout}\n${out.stderr}`);
|
|
469
|
-
const lost = drained.error ? { code: "frame-over-cap", message: drained.error } : drained.overCap.map(overCapProblem)[0];
|
|
470
|
-
if (lost) outcome = { status: "unverified", code: lost.code, message: lost.message, requestId: outcome.requestId, workspace: outcome.workspace };
|
|
471
|
-
}
|
|
472
|
-
record({ ...base, ...outcome, nonce: made.carrier.nonce, ownershipHandle: made.carrier.ownership.handle, checkoutCwd, spawnCwd, clientExit: r.status ?? null });
|
|
473
|
-
if (outcome.status !== "verified") {
|
|
474
|
-
const message = `rightkit-gate: RK_CARGO_BROKER_UNVERIFIED: \`cargo ${words.join(" ")}\` has no verified signed receipt (${outcome.code}: ${outcome.message}); the scan fails`;
|
|
475
|
-
err(message);
|
|
476
|
-
return { status: r.status ? r.status : BROKER_REFUSAL_STATUS, outcome, ...out, stderr: `${out.stderr}${message}\n` };
|
|
477
|
-
}
|
|
478
|
-
return { status: r.status ?? (r.signal ? 128 : BROKER_REFUSAL_STATUS), outcome, ...out };
|
|
479
|
-
} finally {
|
|
480
|
-
if (made) removeCarrier(made.file);
|
|
481
|
-
fs.rmSync(refDir, { recursive: true, force: true });
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
/**
|
|
486
|
-
* One carried adapter call: a pnpm, node or QA step of a snapshot stage as a broker adapter job (`rustright run <adapter> -- <words>`), with
|
|
487
|
-
* its own fresh (or, under a release-bound stage, derived) nonce and carrier. The step runs from `cwd`, a directory of the snapshot; the broker
|
|
488
|
-
* runs it from the primary checkout's counterpart of that directory (`checkout` + the path of `cwd` below the snapshot root, both from the gate's
|
|
489
|
-
* own `section`, never a Cargo workspace), and that directory is the carrier's `primaryCwd` and the client's own cwd (a per-call carrier, never a
|
|
490
|
-
* grant: a grant applies only to a call whose cwd is inside the grant's snapshot); the request's workspace is the primary toplevel. The carrier is removed after the call, the signed receipt is verified (its snapshotEvidence, its
|
|
491
|
-
* request digest over the adapter core, and its signed and mirrored `nestedChildren` list: every child exited 0 inside the snapshot, each with a managed
|
|
492
|
-
* output directory), and a ledger record is written either way. Returns `{ status, outcome, stdout, stderr }`; `outcome` is `verified` with the
|
|
493
|
-
* job's `outputDir` and the verified `nestedChildren`, or not.
|
|
494
|
-
* Refused before anything runs: a carrier or per-call carrier variable already in the environment (so a call from inside a broker job, which
|
|
495
|
-
* has a parent request, is refused), no calling gate, a working directory outside the snapshot or with no counterpart in the checkout.
|
|
496
|
-
*/
|
|
497
|
-
export function carryBrokerAdapter(call) { return carryWithRetries(carryBrokerAdapterOnce, call); }
|
|
498
|
-
|
|
499
|
-
/**
|
|
500
|
-
* The same carried adapter call without blocking the caller's event loop (rightkit#1367 step 2: a carried Swift scan used to freeze the gate for as long as it ran or
|
|
501
|
-
* queued). One body (carryBrokerAdapterSteps) serves both: it yields each client call (`{ args, options }`) and the driver runs it, `spawnSync` for the synchronous call and
|
|
502
|
-
* an awaited asynchronous spawn here. `signal` (an AbortSignal) is handed to the client's spawn, so the scan's deadline or a cancel stops the client's process tree; a
|
|
503
|
-
* retry wait is abortable too. The lease reconciliation after an operation deadline stays synchronous (a bounded read, never reached on the normal path).
|
|
504
|
-
*/
|
|
505
|
-
export async function carryBrokerAdapterAsync(call) {
|
|
506
|
-
const { spawn, signal = null, deadlineMs = null, now = Date.now, sleep = abortableSleep, err = () => {}, record = () => {}, ...rest } = call;
|
|
507
|
-
if (typeof spawn !== "function") throw new TypeError("carryBrokerAdapterAsync needs an asynchronous spawn");
|
|
508
|
-
const window = deadlineMs !== null && Number.isFinite(deadlineMs) ? Math.max(1, Math.trunc(deadlineMs)) : DEFAULT_RETRY_WINDOW_MS;
|
|
509
|
-
const started = now();
|
|
510
|
-
const ledgerId = crypto.randomUUID();
|
|
511
|
-
const drive = async (effect) => {
|
|
512
|
-
// An abort that arrived before the client was started proves nothing was sent: the error carries the code provenNoSpawn recognises, so the sub-handle is recorded unsent.
|
|
513
|
-
if (signal?.aborted && effect.args[0] === "run") return { status: null, stdout: "", stderr: "", cancelled: true, error: Object.assign(new Error("cancelled before the client started"), { code: CLIENT_CANCELLED_BEFORE_SPAWN }) };
|
|
514
|
-
return spawnBrokerClient(spawn, rest.section.client, effect.args, { ...effect.options, ...(signal ? { signal } : {}) }, { platform: rest.section.platform });
|
|
515
|
-
};
|
|
516
|
-
let attempt = 0; let held = []; let result;
|
|
517
|
-
for (;;) {
|
|
518
|
-
attempt += 1;
|
|
519
|
-
held = [];
|
|
520
|
-
const remaining = Math.max(1, window - (now() - started));
|
|
521
|
-
result = await runStepsAsync(carryBrokerAdapterSteps({ ...rest, record, err: (m) => held.push(m), deadlineMs: deadlineMs === null ? null : remaining, ledgerId, signal, asyncCarry: true }), drive);
|
|
522
|
-
const code = result.outcome?.status === "unverified" ? result.outcome.code : null;
|
|
523
|
-
if (code === null || !RETRYABLE_OUTCOME_CODES.has(code) || signal?.aborted) break;
|
|
524
|
-
const pause = retryPauseMs(attempt);
|
|
525
|
-
if (window - (now() - started) <= pause) {
|
|
526
|
-
const elapsed = now() - started;
|
|
527
|
-
const message = `${result.outcome.message}; retried ${attempt - 1} time(s) over ${elapsed} ms and the call's ${window} ms deadline passed before the broker would take it: it is a wait that did not clear, never a result`;
|
|
528
|
-
result = { ...result, outcome: { ...result.outcome, message, attempts: attempt, retried: attempt - 1 } };
|
|
529
|
-
try { record({ id: ledgerId, mode: "broker", status: "unverified", code: result.outcome.code, message }); } catch { /* the final record above stands */ }
|
|
530
|
-
held.push(`rightkit-gate: ${result.outcome.code}: ${message}`);
|
|
531
|
-
break;
|
|
532
|
-
}
|
|
533
|
-
await sleep(pause, signal);
|
|
534
|
-
// A cancel during the wait ends the carry here: nothing is marked or sent for another attempt (the refused attempt was already recorded as settled or unsent).
|
|
535
|
-
if (signal?.aborted) break;
|
|
536
|
-
try { record({ id: ledgerId, mode: "broker", status: "pending", code: null, message: null }); } catch { /* the attempt records its own pending state */ }
|
|
537
|
-
}
|
|
538
|
-
for (const m of held) err(m);
|
|
539
|
-
return result;
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
/** A retry wait that ends at once when the abort signal fires (the default `sleep` of the asynchronous carry). */
|
|
543
|
-
function abortableSleep(ms, signal = null) {
|
|
544
|
-
return new Promise((resolve) => {
|
|
545
|
-
if (signal?.aborted) { resolve(); return; }
|
|
546
|
-
const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); };
|
|
547
|
-
const timer = setTimeout(done, ms);
|
|
548
|
-
signal?.addEventListener("abort", done, { once: true });
|
|
549
|
-
});
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/** Drives a steps generator synchronously: each yielded client call runs through `drive` (spawnSync or its test double). */
|
|
553
|
-
function runStepsSync(steps, drive) {
|
|
554
|
-
let step = steps.next();
|
|
555
|
-
while (!step.done) step = steps.next(drive(step.value));
|
|
556
|
-
return step.value;
|
|
557
|
-
}
|
|
558
|
-
async function runStepsAsync(steps, drive) {
|
|
559
|
-
let step = steps.next();
|
|
560
|
-
while (!step.done) {
|
|
561
|
-
let reply;
|
|
562
|
-
try { reply = await drive(step.value); } catch (error) { step = steps.throw(error); continue; }
|
|
563
|
-
step = steps.next(reply);
|
|
564
|
-
}
|
|
565
|
-
return step.value;
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
function carryBrokerAdapterOnce(call) {
|
|
569
|
-
const { section, spawn = spawnSync } = call;
|
|
570
|
-
return runStepsSync(carryBrokerAdapterSteps(call), (effect) => spawnBrokerClient(spawn, section.client, effect.args, effect.options, { platform: section.platform }));
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
/** One carried adapter attempt as a generator: it yields `{ args, options }` for each client call (the carried run, then the receipt's status) and receives the spawn result. */
|
|
574
|
-
function* carryBrokerAdapterSteps({ adapter, words, cwd, env, section, record, err, tmp = os.tmpdir(), stdio = "inherit", deadlineMs = null, ledgerId = null, signal = null, asyncCarry = false }) {
|
|
575
|
-
const id = ledgerId ?? crypto.randomUUID();
|
|
576
|
-
words = [...words].map(String);
|
|
577
|
-
const base = { id, mode: "broker", shim: "adapter", adapter, cwd, argv: [...words] };
|
|
578
|
-
const refuse = (code, message) => { record({ ...base, status: "refused", code, message }); err(`rightkit-gate: ${code}: ${message}`); return { status: BROKER_REFUSAL_STATUS, outcome: { status: "refused", code, message }, stdout: "", stderr: `rightkit-gate: ${code}: ${message}\n` }; };
|
|
579
|
-
const describe = `${adapter} ${words.join(" ")}`.trim();
|
|
580
|
-
// GB-67: the broker owns SwiftPM's scratch and build path; a caller-named one is refused before the carrier, the mark and the send.
|
|
581
|
-
if (adapter === "rightkit-swift") { const owned = swiftScratchRefusal(words); if (owned) return refuse(owned.code, owned.message); }
|
|
582
|
-
if (typeof adapter !== "string" || !/^[a-z][a-z0-9-]*$/.test(adapter)) return refuse("RK_ADAPTER_BROKER_ADAPTER", `${JSON.stringify(adapter)} is not a registered adapter name`);
|
|
583
|
-
const gate = env[CALLING_GATE_ENV];
|
|
584
|
-
if (typeof gate !== "string" || !gate.trim()) return refuse("RK_ADAPTER_BROKER_NO_GATE", `${CALLING_GATE_ENV} is not set: the call names no gate, and the carrier never forges one`);
|
|
585
|
-
const inherited = inheritedCarrierEnv(env);
|
|
586
|
-
if (inherited.length) return refuse("RK_ADAPTER_BROKER_INHERITED_ENV", `${inherited.join(", ")} ${inherited.length > 1 ? "are" : "is"} already in the environment; a carrier is set by the gate for one call only, so a nested or replayed call (or one from inside a broker job) is refused`);
|
|
587
|
-
// The client's environment: the stage nonce is read here and never forwarded (this call's nonce is derived from it); no output directory
|
|
588
|
-
// and no stage grant is forwarded either (the broker pins the output, and no grant exists).
|
|
589
|
-
const clientEnv = withoutManagedRustEnv(env);
|
|
590
|
-
for (const key of Object.keys(clientEnv)) if (/^(RUSTRIGHT|RIGHTKIT)_SNAPSHOT_GRANT$/i.test(key)) delete clientEnv[key];
|
|
591
|
-
const stageNonce = env[ATTEST_STAGE_NONCE_ENV];
|
|
592
|
-
for (const key of Object.keys(clientEnv)) if (key.toUpperCase() === ATTEST_STAGE_NONCE_ENV) delete clientEnv[key];
|
|
593
|
-
// The request environment the client will forward (RUSTRIGHT_ADAPTER_ENV and the variables it names): bound into the request core below and
|
|
594
|
-
// recorded in the ledger so the gate's own re-verification recomputes the same digest. A reserved or unset name is refused here, as the client would.
|
|
595
|
-
let adapterEnv;
|
|
596
|
-
try { adapterEnv = forwardedAdapterEnv(env); } catch (e) { return refuse(e.code ?? "RK_ADAPTER_ENV_INVALID", e.message); }
|
|
597
|
-
base.adapterEnv = adapterEnv;
|
|
598
|
-
let realCwd; let checkoutCwd; let rel;
|
|
599
|
-
try {
|
|
600
|
-
const snapshotRoot = fs.realpathSync.native(section.snapshot.path);
|
|
601
|
-
realCwd = fs.realpathSync.native(cwd);
|
|
602
|
-
rel = path.relative(snapshotRoot, realCwd);
|
|
603
|
-
if (escapes(rel)) throw new Error(`${realCwd} is not inside the snapshot ${snapshotRoot}`);
|
|
604
|
-
} catch (e) { return refuse("RK_ADAPTER_BROKER_CWD", `the step's working directory is not inside the snapshot (${e.message})`); }
|
|
605
|
-
const counterpart = checkoutCounterpart({ base: section.checkout, rel, checkout: section.checkout, codePrefix: "RK_ADAPTER_BROKER_COUNTERPART" });
|
|
606
|
-
if (counterpart.refusal) return refuse(counterpart.refusal.code, counterpart.refusal.message);
|
|
607
|
-
checkoutCwd = counterpart.dir; const spawnCwd = counterpart.spawnCwd;
|
|
608
|
-
let inputs;
|
|
609
|
-
try { inputs = readDeclaredInputs(section.snapshot.path); } catch (e) { return refuse("RK_ADAPTER_BROKER_DECLARED_INPUTS", e.message); }
|
|
610
|
-
const refDir = fs.mkdtempSync(path.join(tmp, "rk-snapreq-"));
|
|
611
|
-
let made = null;
|
|
612
|
-
try {
|
|
613
|
-
try {
|
|
614
|
-
const nonce = /^[0-9a-f]{64}$/.test(stageNonce ?? "") ? carriedCallNonce({ stageNonce, cwd: path.relative(section.checkout, checkoutCwd).split(path.sep).join("/") || ".", argv: words }) : undefined;
|
|
615
|
-
made = writeSnapshotRequest({ controlRoot: section.controlRoot, commit: section.commit, snapshot: section.snapshot, declaredInputs: inputs, handle: section.handle, primaryCwd: checkoutCwd, argv: words, nonce, requestIdFile: path.join(refDir, "request.json") });
|
|
616
|
-
} catch (e) { return refuse("RK_ADAPTER_BROKER_CARRIER", e.message); }
|
|
617
|
-
try { record({ ...base, status: "pending", nonce: made.carrier.nonce, requestRef: path.join(refDir, "request.json"), ownershipHandle: made.carrier.ownership.handle, checkoutCwd, spawnCwd }); } catch (e) { removeCarrier(made.file); return refuse("RK_CARGO_LEDGER_ERROR", `the call cannot be recorded (${e.message}); it does not run`); }
|
|
618
|
-
// GB-52: the call's operation deadline (the caller's own cap is never replaced) and an outer guard past the client's own cancel wait.
|
|
619
|
-
const childEnv = { RUST_BACKTRACE: clientEnv.RUST_BACKTRACE ?? "1", ...clientEnv, ...made.env, ...operationDeadlineEnv({ env: clientEnv, deadlineMs }) };
|
|
620
|
-
const guard = clientGuardMs(childEnv);
|
|
621
|
-
const capture = stdio === "capture";
|
|
622
|
-
// Broker work may exist from the next statement on: the ownership records this request's sub-handle first (a mark that does not land sends nothing).
|
|
623
|
-
{ const startable = clientStartable(section.client, section.platform); if (startable) { removeCarrier(made.file); return refuse("RK_ADAPTER_BROKER_CLIENT", `${startable}; nothing was marked or sent`); } }
|
|
624
|
-
// A scan cancelled before the request is marked sends nothing and marks nothing (the mark records that broker work may exist).
|
|
625
|
-
if (signal?.aborted) { removeCarrier(made.file); return refuse("RK_ADAPTER_BROKER_CANCELLED", "the scan was cancelled before the request was marked or sent; nothing was sent"); }
|
|
626
|
-
try { markCarriedRequest({ section, env, callHandle: made.carrier.ownership.handle }); } catch (e) { removeCarrier(made.file); return refuse("RK_ADAPTER_BROKER_OWNERSHIP", e.message); }
|
|
627
|
-
const r = yield { args: ["run", adapter, "--", ...words], options: capture ? { cwd: spawnCwd, env: childEnv, encoding: "utf8", maxBuffer: 1 << 28, windowsHide: true, ...(guard ? { timeout: guard } : {}) } : { cwd: spawnCwd, env: childEnv, stdio: "inherit", ...(guard ? { timeout: guard } : {}) } };
|
|
628
|
-
removeCarrier(made.file);
|
|
629
|
-
// GB-21: a client that provably never started sent nothing: that sub-handle is recorded unsent under the ownership lock, so it does not wedge a later reclaim. Any other
|
|
630
|
-
// failure after a start (a lost connection, a timeout, an exit before a reference) is ambiguous and stays held, reconciled by the request id.
|
|
631
|
-
if (r.error && provenNoSpawn(r.error)) markCarriedUnsentRequest({ section, env, callHandle: made.carrier.ownership.handle, reason: `the RustRight client did not start (${r.error.code})` });
|
|
632
|
-
let outcome;
|
|
633
|
-
let ref = null;
|
|
634
|
-
let nativeManaged = null;
|
|
635
|
-
const cancelledRun = Boolean(r.error) && (r.cancelled === true || signal?.aborted === true);
|
|
636
|
-
try {
|
|
637
|
-
if (r.error && cancelledRun) {
|
|
638
|
-
// The scan's own signal stopped the client: a cancel, never "the client did not start" (the request may exist at the broker; its reference is kept when the client wrote it).
|
|
639
|
-
try { ref = readRequestRef(path.join(refDir, "request.json")); } catch { ref = null; }
|
|
640
|
-
throw new SnapshotRequestError("cancelled", provenNoSpawn(r.error) ? "the scan was cancelled before the RustRight client started; nothing was sent" : `the scan was cancelled: its signal stopped the RustRight client${ref ? ` (request ${ref.requestId})` : ""}; the request is not resubmitted`);
|
|
641
|
-
}
|
|
642
|
-
if (r.error) throw new SnapshotRequestError(r.error.code === BROKER_CLIENT_UNRESOLVED ? BROKER_CLIENT_UNRESOLVED : "spawn", `the RustRight client did not start (${r.error.message})`);
|
|
643
|
-
ref = readRequestRef(path.join(refDir, "request.json"));
|
|
644
|
-
// The request's workspace of a snapshot-bound adapter job is the directory the client ran in: the primary checkout's counterpart of the step's
|
|
645
|
-
// snapshot directory (the broker, START: "the job runs where it was asked to (request.workspace, already the primary's counterpart of a
|
|
646
|
-
// directory in the snapshot), which must be inside that root"). It is the carrier's primaryCwd, never the toplevel for a step run from a subfolder
|
|
647
|
-
// (an app whose root is `app/`), and never a directory outside the primary checkout or one that is not this call's counterpart.
|
|
648
|
-
if (canonicalCounterpart(ref.workspace) !== canonicalCounterpart(checkoutCwd) || !inside(canonicalCounterpart(ref.workspace), section.checkout)) throw new SnapshotRequestError("workspace", `the request's workspace ${ref.workspace} is not the primary checkout counterpart ${checkoutCwd} of the step's directory ${realCwd} (primary toplevel ${section.checkout})`);
|
|
649
|
-
let statusReply = yield { args: ["status", ref.requestId], options: statusOptions(clientEnv) };
|
|
650
|
-
// A job still live although its client exited (A7): follow it once with `rustright attach` (WATCH, bounded), then read STATUS again; never a poll.
|
|
651
|
-
let liveWaited = false;
|
|
652
|
-
try { receiptFromReply(statusReply, ref.requestId); } catch (probe) {
|
|
653
|
-
if (isLiveRead(probe)) { yield { args: ["attach", ref.requestId], options: liveWaitOptions(clientEnv, LIVE_WAIT_MS) }; statusReply = yield { args: ["status", ref.requestId], options: statusOptions(clientEnv) }; liveWaited = true; }
|
|
654
|
-
}
|
|
655
|
-
let receipt;
|
|
656
|
-
try { receipt = receiptFromReply(statusReply, ref.requestId); } catch (again) { throw liveWaited && isLiveRead(again) ? stillLive(again, LIVE_WAIT_MS) : again; }
|
|
657
|
-
const { payload, evidence, attribution, toolchain, nestedChildren } = verifySnapshotReceipt(receipt, { pins: section.pins, jobId: ref.requestId, carrier: made.carrier, argv: words, workspace: ref.workspace, adapter, adapterEnv, checkout: section.checkout, outputRoots: section.outputRoots, platform: section.platform });
|
|
658
|
-
nativeManaged = signedNativeOutputs(receipt, payload);
|
|
659
|
-
outcome = { status: "verified", requestId: ref.requestId, workspace: ref.workspace, outputDir: evidence.outputDir, nestedChildren, treeAtStart: evidence.snapshot.treeAtStart, treeAtExit: evidence.snapshot.treeAtExit, attribution, toolchain };
|
|
660
|
-
} catch (e) {
|
|
661
|
-
outcome = { status: "unverified", code: e.code ?? "error", message: e.message, ...(ref ? { requestId: ref.requestId, workspace: ref.workspace } : {}) };
|
|
662
|
-
}
|
|
663
|
-
outcome = { ...outcome, clientStatus: r.status ?? null, clientSignal: r.signal ?? null }; // A7: the client's own exit, kept with every outcome
|
|
664
|
-
const out = capture ? { stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? "") } : { stdout: "", stderr: "" };
|
|
665
|
-
// GB-54: a request the broker REFUSED (admission paused, a suspended or unknown job, a cutover drain) never started: the client's typed REJECTED result is kept as the outcome's
|
|
666
|
-
// code ("admission is paused; nothing was spawned"), not folded into a missing request reference. It is never a build outcome.
|
|
667
|
-
if (outcome.status !== "verified" && capture) {
|
|
668
|
-
const refused = refusalInCapturedOutput(`${out.stdout}\n${out.stderr}`);
|
|
669
|
-
if (refused?.code === "RK_TOOLCHAIN_IDENTITY_UNAVAILABLE") outcome = { status: "unverified", code: "toolchain-unavailable", message: `the broker refused the compile before it started: it could not build the toolchain identity (RK_TOOLCHAIN_IDENTITY_UNAVAILABLE: ${refused.message}); nothing ran`, ...(outcome.requestId ? { requestId: outcome.requestId, workspace: outcome.workspace } : {}) };
|
|
670
|
-
else if (refused) outcome = { status: "unverified", code: `broker-refused-${refused.refusal}`, message: `the broker refused the request (${refused.code ?? "no code"}: ${refused.message || refused.refusal})${refusalAdvice(refused)}`, ...(outcome.requestId ? { requestId: outcome.requestId, workspace: outcome.workspace } : {}) };
|
|
671
|
-
}
|
|
672
|
-
// GB-52: a call that ran out its operation deadline, or whose client was stopped by the outer guard, is NOT a build outcome: the client cancelled by id and watched for the terminal
|
|
673
|
-
// state, and an unobserved state keeps ownership UNKNOWN (the sub-handle stays recorded; reconciled by the request id, never resubmitted). Busy and unavailable are named apart.
|
|
674
|
-
if (outcome.status !== "verified") {
|
|
675
|
-
const seen = operationOutcomeInOutput(`${out.stdout}\n${out.stderr}`) ?? (r.error?.code === "ETIMEDOUT" ? { code: "operation-deadline", deadlineMs: null, requestId: ref?.requestId ?? null, cancelConfirmed: null, terminalState: null, guard: true } : null);
|
|
676
|
-
if (seen) outcome = { status: "unverified", code: seen.code, message: seen.code === "operation-deadline" ? `the operation deadline${seen.deadlineMs ? ` of ${seen.deadlineMs} ms` : ""} passed${seen.guard ? " and the client was stopped by the gate's outer guard" : ""}; request ${seen.requestId ?? ref?.requestId ?? "unknown"}: cancelConfirmed: ${seen.cancelConfirmed ?? "unknown"}, terminal state: ${seen.terminalState ?? "not observed"}; the job is neither abandoned nor resubmitted and ownership stays UNKNOWN until every sub-handle is REAPED` : seen.code === "broker-busy" ? "every broker connection was busy (RK_BROKER_BUSY: a wait, not an outage); nothing was admitted" : "the broker was unavailable (RK_BROKER_UNAVAILABLE)", ...(ref ? { requestId: ref.requestId, workspace: ref.workspace } : {}) };
|
|
677
|
-
}
|
|
678
|
-
if (outcome.status === "unverified" && (outcome.code === "operation-deadline" || (outcome.code === "cancelled" && !provenNoSpawn(r.error)))) {
|
|
679
|
-
const settled = asyncCarry ? deferredReconcile(made.carrier.ownership.handle) : reconcileAfterCancel({ section, callHandle: made.carrier.ownership.handle, childEnv });
|
|
680
|
-
outcome = { ...outcome, message: `${outcome.message}; ${settled.note}`, reaped: settled.reaped, subHandle: settled.subHandle };
|
|
681
|
-
}
|
|
682
|
-
// RK_BROKER_BUSY with no request reference: the connection never opened, so no byte reached the broker. That is the gate's own proof that this sub-handle was never sent (GB-21), recorded under
|
|
683
|
-
// the ownership lock so the retry's own sub-handle, not this one, is what the stage waits on; a busy answer after a reference exists (a reconnect) proves nothing of the kind.
|
|
684
|
-
if (outcome.status === "unverified" && outcome.code === "broker-busy" && ref === null) markCarriedUnsentRequest({ section, env, callHandle: made.carrier.ownership.handle, reason: "every broker connection was busy (RK_BROKER_BUSY): the connection never opened and no byte was sent" });
|
|
685
|
-
// A typed REJECTED result (admission paused, a cutover drain, ...) with no request reference: the broker refused the submit before it admitted anything, so nothing
|
|
686
|
-
// runs under this sub-handle and the broker will never list it as a member. Recorded unsent now, or a dead owner's record could never be reclaimed (HeardRight Mac,
|
|
687
|
-
// 2026-11-02: 42 paused refusals left a member-less sub-handle the broker answers UNKNOWN for).
|
|
688
|
-
else if (outcome.status === "unverified" && /^broker-refused-/.test(String(outcome.code)) && ref === null) markCarriedUnsentRequest({ section, env, callHandle: made.carrier.ownership.handle, reason: `the broker refused the submit before admitting it (${outcome.code}): nothing was spawned` });
|
|
689
|
-
// GB-53: captured output that lost a frame to FRAME_OVER_CAP (or a result the broker replaced with RK_RESPONSE_OVER_CAP) is truncated: refused, never read as complete.
|
|
690
|
-
if (outcome.status === "verified" && capture) {
|
|
691
|
-
const drained = drainFrames(`${out.stdout}\n${out.stderr}`);
|
|
692
|
-
const lost = drained.error ? { code: "frame-over-cap", message: drained.error } : drained.overCap.map(overCapProblem)[0];
|
|
693
|
-
if (lost) outcome = { status: "unverified", code: lost.code, message: lost.message, requestId: outcome.requestId, workspace: outcome.workspace };
|
|
694
|
-
}
|
|
695
|
-
record({ ...base, ...outcome, nonce: made.carrier.nonce, ownershipHandle: made.carrier.ownership.handle, checkoutCwd, spawnCwd, clientExit: r.status ?? null });
|
|
696
|
-
if (outcome.status !== "verified") {
|
|
697
|
-
const message = `rightkit-gate: RK_ADAPTER_BROKER_UNVERIFIED: \`${describe}\` has no verified signed receipt (${outcome.code}: ${outcome.message}); the stage fails`;
|
|
698
|
-
err(message);
|
|
699
|
-
return { status: r.status ? r.status : BROKER_REFUSAL_STATUS, outcome, ...out, stderr: `${out.stderr}${message}\n` };
|
|
700
|
-
}
|
|
701
|
-
// RA-07/RA-09: the native call's output mapping, as the broker SIGNED it (`executable.managedOutputs`); kept out of the ledger record, which is unchanged.
|
|
702
|
-
return { status: r.status ?? (r.signal ? 128 : BROKER_REFUSAL_STATUS), outcome, ...out, ...(nativeManaged ? { executable: { managedOutputs: nativeManaged } } : {}) };
|
|
703
|
-
} finally {
|
|
704
|
-
if (made) removeCarrier(made.file);
|
|
705
|
-
fs.rmSync(refDir, { recursive: true, force: true });
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
/**
|
|
710
|
-
* The native build tool's output mapping of a verified adapter receipt (RustRight service.rs: a native call's `executable.managedOutputs` is `{ tool, state, outputs: [{ role, path }] }`, signed in
|
|
711
|
-
* `payload.executable` with `argv` removed, and mirrored at the receipt's `nativeOutputs`), or null when the call has none (xcodegen without `--use-cache`, every non-native adapter, an older broker).
|
|
712
|
-
* Only the SIGNED copy is read; a receipt mirror that is present must equal it, and a mirror with nothing signed is refused: the receipt's own say-so is never the mapping.
|
|
713
|
-
*/
|
|
714
|
-
export function signedNativeOutputs(receipt, payload) {
|
|
715
|
-
const signed = payload?.executable?.managedOutputs;
|
|
716
|
-
const mirror = receipt?.nativeOutputs;
|
|
717
|
-
if (signed === undefined || signed === null) {
|
|
718
|
-
if (mirror !== undefined && mirror !== null) throw new SnapshotRequestError("evidence", "the receipt carries nativeOutputs that the signed payload does not (executable.managedOutputs): the mapping is not covered by the signature");
|
|
719
|
-
return null;
|
|
720
|
-
}
|
|
721
|
-
if (mirror !== undefined && mirror !== null && JSON.stringify(canonicalValue(mirror)) !== JSON.stringify(canonicalValue(signed))) throw new SnapshotRequestError("evidence", "receipt nativeOutputs differs from the signed executable.managedOutputs");
|
|
722
|
-
const shaped = signed !== null && typeof signed === "object" && typeof signed.tool === "string" && typeof signed.state === "string" && Array.isArray(signed.outputs)
|
|
723
|
-
&& signed.outputs.every((o) => o !== null && typeof o === "object" && typeof o.role === "string" && typeof o.path === "string");
|
|
724
|
-
if (!shaped) throw new SnapshotRequestError("evidence", "the signed executable.managedOutputs is not { tool, state, outputs: [{ role, path }] }");
|
|
725
|
-
return signed;
|
|
726
|
-
}
|
|
727
|
-
const canonicalValue = (v) => (Array.isArray(v) ? v.map(canonicalValue) : v !== null && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonicalValue(v[k])])) : v);
|
|
728
|
-
|
|
729
|
-
/** One cargo call of a test, carried through the broker (`carryBrokerCargo`). Returns cargo's exit status. */
|
|
730
|
-
export const runBrokerCargo = (call) => carryBrokerCargo(call).status;
|
|
731
|
-
|
|
732
|
-
/**
|
|
733
|
-
* The gate's own check of every ledgered broker call of one scan. A call counts only when the broker's signed receipt, fetched
|
|
734
|
-
* again now, verifies against THIS gate's commit, snapshot, ownership handle and pins, and its carrier was used once: a nonce or a
|
|
735
|
-
* request id that appears twice in the run (`seen`) is a replay. Returns the problems; none means every call verified.
|
|
736
|
-
*/
|
|
737
|
-
export async function verifyBrokerLedger(entries, sb, { seen = { nonces: new Set(), ids: new Set(), handles: new Set() }, openInputDigests = null } = {}) {
|
|
738
|
-
seen.handles ??= new Set();
|
|
739
|
-
const problems = [];
|
|
740
|
-
// `openInputDigests` is supplied ONLY by a producer carrier (the gate's own web-build, windows-identity and stage-sidecar steps, which write declared inputs by design):
|
|
741
|
-
// the inputs whose digest at stage open (the gate's own, allowAbsent) differs from the digest at stage end, computed once, are then "produced" and accept any well-formed
|
|
742
|
-
// receipt entry. Without it (every other carrier) nothing is produced: every receipt, cargo AND adapter, must equal the stage-end digest input by input, so an input a child
|
|
743
|
-
// swapped around an admission and restored is refused. closeSnapshotStage's attribution check is what makes "produced" safe. A failure to digest ends the verification with that problem.
|
|
744
|
-
let inputPolicy = null;
|
|
745
|
-
const ledgered = entries.some((e) => e.mode === "broker" && e.status === "verified");
|
|
746
|
-
if (ledgered) {
|
|
747
|
-
try {
|
|
748
|
-
const end = declaredInputDigestsOf(sb.snapshot.path, readDeclaredInputs(sb.snapshot.path), { platform: sb.platform, allowAbsent: true });
|
|
749
|
-
const produced = new Set();
|
|
750
|
-
if (Array.isArray(openInputDigests)) {
|
|
751
|
-
if (openInputDigests.length !== end.length) throw new SnapshotRequestError("ledger", "the stage-open digest of the declared inputs does not match the declaration");
|
|
752
|
-
end.forEach((d, i) => { if (openInputDigests[i]?.path !== d.path) throw new SnapshotRequestError("ledger", "the stage-open digest of the declared inputs is not in declaration order"); if (canonicalJson(openInputDigests[i]) !== canonicalJson(d)) produced.add(d.path); });
|
|
753
|
-
}
|
|
754
|
-
inputPolicy = { produced, current: end };
|
|
755
|
-
} catch (error) { return [`the gate cannot digest the snapshot's declared inputs at the end of the stage (${error.code ?? "error"}: ${error.message})`]; }
|
|
756
|
-
}
|
|
757
|
-
for (const e of entries) {
|
|
758
|
-
if (e.mode !== "broker" || e.status !== "verified") continue;
|
|
759
|
-
const adapter = typeof e.adapter === "string" && e.adapter ? e.adapter : null;
|
|
760
|
-
const call = `${adapter ?? "cargo"} ${(e.argv ?? []).join(" ")}`.trim();
|
|
761
|
-
try {
|
|
762
|
-
if (typeof e.nonce !== "string" || typeof e.requestId !== "string" || !Array.isArray(e.argv) || !e.argv.every((a) => typeof a === "string") || typeof e.workspace !== "string" || typeof e.checkoutCwd !== "string") throw new SnapshotRequestError("ledger", "the record is incomplete");
|
|
763
|
-
if (seen.nonces.has(e.nonce) || seen.ids.has(e.requestId)) throw new SnapshotRequestError("replay", "a carrier or request was used twice; each call carries its own fresh nonce and is used once");
|
|
764
|
-
if (e.adapterEnv !== undefined && !(e.adapterEnv && typeof e.adapterEnv === "object" && !Array.isArray(e.adapterEnv) && Object.values(e.adapterEnv).every((v) => typeof v === "string"))) throw new SnapshotRequestError("ledger", "the record's adapter environment is not a map of strings");
|
|
765
|
-
if (adapter === null && e.adapterEnv !== undefined && Object.keys(e.adapterEnv).length) throw new SnapshotRequestError("ledger", "a cargo call carries no request environment");
|
|
766
|
-
// One lease handle per call: the sub-handle the gate sent (recorded with the call) is exactly one of this ownership's, used once in the run;
|
|
767
|
-
// the receipt must sign that very handle (verifySnapshotReceipt binds equality, never a prefix).
|
|
768
|
-
if (!isCallHandleOf(e.ownershipHandle, sb.handle)) throw new SnapshotRequestError("ledger", `the record names no sub-handle of the build ownership ${sb.handle}`);
|
|
769
|
-
if (seen.handles.has(e.ownershipHandle)) throw new SnapshotRequestError("replay", `lease handle ${e.ownershipHandle} was used by two calls; each carried request has its own`);
|
|
770
|
-
seen.nonces.add(e.nonce); seen.ids.add(e.requestId); seen.handles.add(e.ownershipHandle);
|
|
771
|
-
// GB-16: a counterpart the primary checkout no longer has is the lexical path the carrier named (the client names it as the workspace); it is judged by its nearest existing ancestor.
|
|
772
|
-
const workspace = canonicalCounterpart(e.workspace);
|
|
773
|
-
if (!inside(workspace, sb.checkout)) throw new SnapshotRequestError("ledger", `the request ran in ${workspace}, outside the primary checkout`);
|
|
774
|
-
if (adapter === null && canonicalCounterpart(e.checkoutCwd) !== workspace) throw new SnapshotRequestError("ledger", "the request's working directory is not the one the call recorded");
|
|
775
|
-
if (adapter !== null) {
|
|
776
|
-
// The workspace is the directory the client ran in, the carrier's primaryCwd; the step's snapshot directory and that checkout directory are the
|
|
777
|
-
// same path below their two roots.
|
|
778
|
-
if (workspace !== canonicalCounterpart(e.checkoutCwd)) throw new SnapshotRequestError("ledger", `the adapter request's workspace ${workspace} is not the primary checkout counterpart ${e.checkoutCwd} of the step's directory`);
|
|
779
|
-
const below = path.relative(fs.realpathSync.native(sb.snapshot.path), fs.realpathSync.native(e.cwd));
|
|
780
|
-
if (escapes(below)) throw new SnapshotRequestError("ledger", `the step ran from ${e.cwd}, outside the snapshot`);
|
|
781
|
-
if (path.relative(sb.checkout, canonicalCounterpart(e.checkoutCwd)) !== below) throw new SnapshotRequestError("ledger", `the carrier named ${e.checkoutCwd}, not the checkout counterpart of ${e.cwd}`);
|
|
782
|
-
}
|
|
783
|
-
// The gate's own truth: its commit, snapshot, handle and declared inputs; only the call's own argv, nonce and cwd come from the ledger.
|
|
784
|
-
const carrier = {
|
|
785
|
-
schema: SNAPSHOT_REQUEST_SCHEMA, commit: sb.commit, snapshot: sb.snapshot, declaredInputs: { inputs: readDeclaredInputs(sb.snapshot.path) },
|
|
786
|
-
ownership: { handle: e.ownershipHandle }, primaryCwd: e.checkoutCwd, argvSha256: argvSha256(e.argv), nonce: e.nonce,
|
|
787
|
-
};
|
|
788
|
-
const receipt = await sb.receiptOf(e.requestId);
|
|
789
|
-
const verified = verifySnapshotReceipt(receipt, { pins: sb.pins, jobId: e.requestId, carrier, argv: e.argv, workspace: e.workspace, observedEnv: e.observedEnv ?? {}, adapter, adapterEnv: e.adapterEnv ?? {}, checkout: sb.checkout, outputRoots: sb.outputRoots, platform: sb.platform, inputPolicy });
|
|
790
|
-
if (adapter !== null) {
|
|
791
|
-
// The children the ledger records (the bundle root and the stage's output directories are read from them) are the signed ones, and no more.
|
|
792
|
-
if (canonicalJson(e.nestedChildren ?? null) !== canonicalJson(verified.nestedChildren)) throw new SnapshotRequestError("nested", "the nested children the call recorded are not the ones the broker's receipt signs");
|
|
793
|
-
for (const child of verified.nestedChildren) {
|
|
794
|
-
if (seen.ids.has(child.requestId)) throw new SnapshotRequestError("replay", `nested child ${child.requestId} was reported twice in this stage`);
|
|
795
|
-
seen.ids.add(child.requestId);
|
|
796
|
-
// rightkit#1418: a nested compile child that signs its own declared-input digests is compared strictly, like a top-level compile: an input swapped
|
|
797
|
-
// for the child and restored before the stage ends is refused. (A child with none is not yet signed by the broker; that half is the broker's.)
|
|
798
|
-
if (child.declaredInputDigests !== undefined) {
|
|
799
|
-
if (!inputPolicy) throw new SnapshotRequestError("evidence", `nested child ${child.requestId} signs declared-input digests but the gate holds no end-of-stage digest of the declared inputs to compare them with`);
|
|
800
|
-
const bad = declaredInputDigestProblems(child.declaredInputDigests, { gateInputs: readDeclaredInputs(sb.snapshot.path), policy: inputPolicy });
|
|
801
|
-
if (bad.length) throw new SnapshotRequestError("evidence", `nested child ${child.requestId} (${child.argv.join(" ")}): ${bad[0]}`);
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
} catch (error) { problems.push(`${call} (from ${e.cwd}): the gate's own verification of the broker's receipt failed (${error.code ?? "error"}: ${error.message})`); }
|
|
806
|
-
}
|
|
807
|
-
return problems;
|
|
808
|
-
}
|