@rightkit/release 0.6.27 → 0.6.28
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/build-helper-trace.mjs +7 -3
- package/build-helpers-command.mjs +32 -4
- package/deterministic-scans.mjs +3 -1
- package/package.json +1 -1
- package/pipeline-receipts.mjs +302 -302
- package/rightkit-versions.json +1 -1
- package/bin/darwin/rightkit-swap +0 -0
- package/bin/darwin/rightkit-swap.sign.json +0 -6
package/build-helper-trace.mjs
CHANGED
|
@@ -169,11 +169,15 @@ export function parseStraceWrites(text, { cwd = "/" } = {}) {
|
|
|
169
169
|
const out = new Set();
|
|
170
170
|
for (const line of String(text).split(/\r?\n/)) {
|
|
171
171
|
if (/=\s*-1\s/.test(line) || /<unfinished \.\.\.>/.test(line)) continue;
|
|
172
|
+
// With `strace -y`, a directory fd prints its real path (`AT_FDCWD</abs/cwd>`, `5</abs/dir>`): a relative path resolves against that,
|
|
173
|
+
// never against a guessed folder (rustc writes `full.rmeta` relative to its own working directory).
|
|
174
|
+
const dirOf = new Map([...line.matchAll(/(?:AT_FDCWD|\d+)<([^>]+)>,\s*"((?:[^"\\]|\\.)*)"/g)].map((m) => [m[2], m[1]]));
|
|
175
|
+
const resolveIt = (p) => (path.posix.isAbsolute(p) ? p : path.posix.resolve(dirOf.get(p) ?? cwd, p));
|
|
172
176
|
let paths = [];
|
|
173
177
|
const open = OPEN.exec(line);
|
|
174
178
|
if (open) { if (/O_WRONLY|O_RDWR|O_CREAT|O_TRUNC|O_APPEND/.test(open[3])) paths = [open[2]]; }
|
|
175
179
|
else if (MUTATING.test(line)) paths = [...line.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1]);
|
|
176
|
-
for (const p of paths) if (p) out.add(
|
|
180
|
+
for (const p of paths) if (p) out.add(resolveIt(p));
|
|
177
181
|
}
|
|
178
182
|
return [...out];
|
|
179
183
|
}
|
|
@@ -210,7 +214,7 @@ export function parseEtwWrites(xml, { rootPid, devices = {} }) {
|
|
|
210
214
|
if (tree.has(parent)) tree.add(child);
|
|
211
215
|
}
|
|
212
216
|
}
|
|
213
|
-
const toDos = (p) => { if (!p) return null; for (const [dev, letter] of Object.entries(devices)) if (p.toLowerCase().startsWith(dev.toLowerCase())) return letter + p.slice(dev.length); return p; };
|
|
217
|
+
const toDos = (p) => { if (!p) return null; for (const [dev, letter] of Object.entries(devices)) if (p.toLowerCase().startsWith(`${dev.toLowerCase()}\\`)) return letter + p.slice(dev.length); return p; };
|
|
214
218
|
const names = new Map(); const out = new Set();
|
|
215
219
|
for (const ev of events) {
|
|
216
220
|
if (provider(ev) !== "Microsoft-Windows-Kernel-File" || !tree.has(pidOf(ev))) continue;
|
|
@@ -330,7 +334,7 @@ export function etwWritesByRoot(file, roots, devices = {}) {
|
|
|
330
334
|
if (provider(ev) === "Microsoft-Windows-Kernel-Process" && id(ev) === 1) parent.set(Number(field(ev, "ProcessID")), Number(field(ev, "ParentProcessID")));
|
|
331
335
|
});
|
|
332
336
|
const rootOf = rootFinder(parent, roots); const out = new Map([...roots].map((r) => [r, new Set()]));
|
|
333
|
-
const toDos = (p) => { if (!p) return null; for (const [dev, letter] of Object.entries(devices)) if (p.toLowerCase().startsWith(dev.toLowerCase())) return letter + p.slice(dev.length); return p; };
|
|
337
|
+
const toDos = (p) => { if (!p) return null; for (const [dev, letter] of Object.entries(devices)) if (p.toLowerCase().startsWith(`${dev.toLowerCase()}\\`)) return letter + p.slice(dev.length); return p; };
|
|
334
338
|
const names = new Map();
|
|
335
339
|
forEachRecord(file, "</Event>", (ev) => {
|
|
336
340
|
if (provider(ev) !== "Microsoft-Windows-Kernel-File") return;
|
|
@@ -63,7 +63,8 @@ export function cargoWorkspaces(root, { depth = 4, fsApi = fs } = {}) {
|
|
|
63
63
|
};
|
|
64
64
|
walk(root, depth);
|
|
65
65
|
// Only repositories the gate builds: the workspace's repository root (nearest .git) carries a .rightkit directory.
|
|
66
|
-
|
|
66
|
+
// A gate snapshot of a commit (<managed root>/snapshots/<key>) has .rightkit but no .git: the first ancestor with either decides.
|
|
67
|
+
const gated = (dir) => { for (let d = dir; ; d = path.dirname(d)) { if (fsApi.existsSync(path.join(d, ".rightkit"))) return true; if (fsApi.existsSync(path.join(d, ".git"))) return false; if (path.dirname(d) === d) return false; } };
|
|
67
68
|
return found.filter(gated).sort();
|
|
68
69
|
}
|
|
69
70
|
|
|
@@ -143,8 +144,10 @@ function mainWith(argv, { env, platform, run, log, err }) {
|
|
|
143
144
|
// ETW kernel sessions need an elevated shell; kernel paths are mapped back to drive letters once (QueryDosDevice).
|
|
144
145
|
const admin = run("net", ["session"], { encoding: "utf8" });
|
|
145
146
|
if (admin.status !== 0) { err("right-release build-helpers trace: run from an elevated (Administrator) shell; ETW kernel tracing needs it"); return 2; }
|
|
146
|
-
const map = run("powershell", ["-NoProfile", "-Command", "$s='[DllImport(
|
|
147
|
+
const map = run("powershell", ["-NoProfile", "-Command", "$s='[DllImport(\"kernel32.dll\")] public static extern uint QueryDosDevice(string d, System.Text.StringBuilder b, uint m);'; $k=Add-Type -MemberDefinition $s -Name K -Namespace W -PassThru; foreach($d in [IO.DriveInfo]::GetDrives()){ $l=$d.Name.Substring(0,2); $b=New-Object Text.StringBuilder 512; [void]$k::QueryDosDevice($l,$b,512); \"$l=$b\" }"], { encoding: "utf8" });
|
|
147
148
|
for (const line of String(map.stdout ?? "").split(/\r?\n/)) { const m = /^([A-Z]:)=(\\Device\\\S+)$/.exec(line.trim()); if (m) devices[m[2]] = m[1]; }
|
|
149
|
+
// Without the map every kernel path would be judged outside the allowed folders: stop instead of recording false verdicts.
|
|
150
|
+
if (!Object.keys(devices).length) { err(`right-release build-helpers trace: could not map kernel device paths to drive letters (QueryDosDevice): ${String(map.stderr ?? "").trim().split(/\r?\n/)[0] ?? ""}`); return 2; }
|
|
148
151
|
}
|
|
149
152
|
const recordRepo = rest.includes("--record-repo");
|
|
150
153
|
const cargoHome = env.CARGO_HOME ?? path.join(os.homedir(), ".cargo");
|
|
@@ -174,7 +177,7 @@ function mainWith(argv, { env, platform, run, log, err }) {
|
|
|
174
177
|
const buildEnv = { ...env, CARGO_TARGET_DIR: target, CARGO_BUILD_JOBS: perBuildJobs };
|
|
175
178
|
const straceOut = path.join(scratch, "strace");
|
|
176
179
|
const job = platform === "linux"
|
|
177
|
-
? { cmd: "strace", args: ["-ff", "-qq", "-o", straceOut, "-e", "trace=open,openat,openat2,creat,rename,renameat,renameat2,unlink,unlinkat,mkdir,mkdirat,rmdir,link,linkat,symlink,symlinkat,truncate,chmod,fchmodat,chown,fchownat,lchown,utimensat", "cargo", ...buildArgs], env: buildEnv }
|
|
180
|
+
? { cmd: "strace", args: ["-ff", "-qq", "-y", "-o", straceOut, "-e", "trace=open,openat,openat2,creat,rename,renameat,renameat2,unlink,unlinkat,mkdir,mkdirat,rmdir,link,linkat,symlink,symlinkat,truncate,chmod,fchmodat,chown,fchownat,lchown,utimensat", "cargo", ...buildArgs], env: buildEnv }
|
|
178
181
|
: { cmd: "cargo", args: buildArgs, env: buildEnv };
|
|
179
182
|
job.label = `${unit.crate} ${unit.version}`;
|
|
180
183
|
return { unit, scratch, target, straceOut, job };
|
|
@@ -188,7 +191,32 @@ function mainWith(argv, { env, platform, run, log, err }) {
|
|
|
188
191
|
const tracer = run("sh", ["-c", `sudo -n eslogger fork exec create rename unlink link truncate open close clone copyfile exchangedata > '${traceFile}' 2>'${traceFile}.err' & echo $!`], { encoding: "utf8" });
|
|
189
192
|
const tracerPid = String(tracer.stdout ?? "").trim();
|
|
190
193
|
run("sleep", ["2"]);
|
|
191
|
-
|
|
194
|
+
// Drain before stopping: eslogger writes a block-buffered file and Endpoint Security delivers late, so the last builds' events were
|
|
195
|
+
// still in flight when a fixed one-second wait ended (every "build was not observed" fail on the Mac was a build that finished last
|
|
196
|
+
// in its session). Marker files are created in the session folder, one a second, until the first appears in the recording: every
|
|
197
|
+
// event before it is then on disk. Two minutes without it leaves the verdicts to judgeTrace, which fails a build it did not see.
|
|
198
|
+
const drain = () => {
|
|
199
|
+
const tag = `rk-bht-drain-${process.pid}-`;
|
|
200
|
+
let from = 0; try { from = fs.statSync(traceFile).size; } catch { /* nothing yet */ }
|
|
201
|
+
for (let i = 0; i < 120; i += 1) {
|
|
202
|
+
fs.writeFileSync(path.join(sessionDir, `${tag}${i}`), "");
|
|
203
|
+
run("sleep", ["1"]);
|
|
204
|
+
let size = 0; try { size = fs.statSync(traceFile).size; } catch { continue; }
|
|
205
|
+
if (size <= from) continue;
|
|
206
|
+
const fd = fs.openSync(traceFile, "r");
|
|
207
|
+
try {
|
|
208
|
+
const chunk = Buffer.alloc(8 << 20);
|
|
209
|
+
for (let at = from; at < size; at += chunk.length - tag.length) {
|
|
210
|
+
const n = fs.readSync(fd, chunk, 0, chunk.length, at);
|
|
211
|
+
if (chunk.subarray(0, n).includes(tag)) return true;
|
|
212
|
+
}
|
|
213
|
+
} finally { fs.closeSync(fd); }
|
|
214
|
+
from = Math.max(from, size - tag.length);
|
|
215
|
+
}
|
|
216
|
+
err("right-release build-helpers trace: eslogger did not record the drain marker within 2 minutes; builds it did not see are judged unobserved");
|
|
217
|
+
return false;
|
|
218
|
+
};
|
|
219
|
+
stopTracer = () => { drain(); if (tracerPid) { run("sudo", ["-n", "pkill", "-INT", "-P", tracerPid]); run("kill", [tracerPid]); run("sleep", ["1"]); } };
|
|
192
220
|
} else if (platform === "win32") {
|
|
193
221
|
// One ETW session with both kernel providers, each with an explicit level (0x5): a separate process-only session without a level
|
|
194
222
|
// recorded nothing on the Dell (proc.etl 0 MB), so no write could be tied to its build. Tested on the Dell: process starts (with
|
package/deterministic-scans.mjs
CHANGED
|
@@ -1071,7 +1071,9 @@ export function planScans({
|
|
|
1071
1071
|
const wsOf = (n) => (rustMap ? rustMap.get(n).cargoDir : cargoWs);
|
|
1072
1072
|
const crateOf = (n) => (rustMap?.get(n)?.crate ?? n);
|
|
1073
1073
|
const featuresOf = (n) => crateFeatures?.[n] ?? crateFeatures?.[crateOf(n)] ?? {};
|
|
1074
|
-
|
|
1074
|
+
// With no Rust unit in play the default workspace counts only when it has a Cargo.toml: a root rust-toolchain.toml (or other Rust config)
|
|
1075
|
+
// in a crate-per-workspace repository must not turn the repository root into a phantom workspace whose cargo scans have no manifest.
|
|
1076
|
+
const workspaces = rustMap && rustMap.size ? [...new Set([...rustMap.values()].map((u) => u.cargoDir))].sort() : (exists(path.join(contentRoot, cargoWs === "." ? "Cargo.toml" : `${cargoWs}/Cargo.toml`)) ? [cargoWs] : []);
|
|
1075
1077
|
const lockOf = (ws) => (rustLocks?.[ws] instanceof Map ? rustLocks[ws] : ws === cargoWs && rustLock instanceof Map ? rustLock : null);
|
|
1076
1078
|
const rustDir = (n) => (rustMap ? rustMap.get(n).dir : `crates/${n}`);
|
|
1077
1079
|
const npmDir = (n) => (npmMap ? npmMap.get(n).dir : `packages/${n}`);
|
package/package.json
CHANGED
package/pipeline-receipts.mjs
CHANGED
|
@@ -1,302 +1,302 @@
|
|
|
1
|
-
// Pipeline stage receipts and their verifier (architecture-v3 sections 4-5, "Receipts").
|
|
2
|
-
//
|
|
3
|
-
// A receipt records a fact about one stage of one request. It never authorizes execution alone: the
|
|
4
|
-
// broker (RustRight) signs receipts and issues short-lived capabilities; this module only checks that
|
|
5
|
-
// a chain of receipts is well formed, linked, fresh and complete. Signature checking is an injected
|
|
6
|
-
// interface (`verifySignature`); this module does no cryptography beyond SHA-256 hashing and invents none.
|
|
7
|
-
//
|
|
8
|
-
// Chain: ADMISSION -> SCAN_A -> ROUTE -> SCAN_B -> BUILD -> SIGN -> QUALIFIED -> PUBLISH_INTENT -> PUBLISHED.
|
|
9
|
-
// Each stage requires exactly its predecessor; `parents` carries that predecessor's receipt hash.
|
|
10
|
-
import crypto from "node:crypto";
|
|
11
|
-
import { canonicalJson, digestScanSet, scanClassOf } from "./deterministic-scans.mjs";
|
|
12
|
-
|
|
13
|
-
export const RECEIPT_SCHEMA = "rightkit.pipeline-receipt/1";
|
|
14
|
-
export const STAGES = Object.freeze(["ADMISSION", "SCAN_A", "ROUTE", "SCAN_B", "BUILD", "SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
|
|
15
|
-
export const OPERATIONS = Object.freeze(["dev", "build", "qualify", "sign", "publish"]);
|
|
16
|
-
/** The last stage each operation may reach. */
|
|
17
|
-
export const OPERATION_LAST_STAGE = Object.freeze({ dev: "BUILD", build: "BUILD", sign: "SIGN", qualify: "QUALIFIED", publish: "PUBLISHED" });
|
|
18
|
-
/** Each stage requires only these predecessors. */
|
|
19
|
-
export const PREREQUISITES = Object.freeze({
|
|
20
|
-
ADMISSION: [], SCAN_A: ["ADMISSION"], ROUTE: ["SCAN_A"], SCAN_B: ["ROUTE"], BUILD: ["SCAN_B"],
|
|
21
|
-
SIGN: ["BUILD"], QUALIFIED: ["SIGN"], PUBLISH_INTENT: ["QUALIFIED"], PUBLISHED: ["PUBLISH_INTENT"],
|
|
22
|
-
});
|
|
23
|
-
const RELEASE_ID_STAGES = new Set(["SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
|
|
24
|
-
/** Stages only a publishable request may reach: signing and everything after it. A dev or non-publishable chain stops at BUILD. */
|
|
25
|
-
const PUBLISHABLE_ONLY_STAGES = new Set(RELEASE_ID_STAGES);
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* What ADMISSION's evidence allows for `stage`, as [{ code, message }]. ADMISSION is the sole authority:
|
|
29
|
-
* a missing or malformed ADMISSION authorizes nothing, and `publishable` must be exactly true to reach SIGN or later.
|
|
30
|
-
*/
|
|
31
|
-
function admissionProblems(admission, stage) {
|
|
32
|
-
const out = [];
|
|
33
|
-
if (!admission) return [{ code: "STAGE_NOT_AUTHORIZED", message: `no valid ADMISSION evidence authorizes ${stage}` }];
|
|
34
|
-
if (!Array.isArray(admission.authorizedStages) || !admission.authorizedStages.includes(stage)) out.push({ code: "STAGE_NOT_AUTHORIZED", message: `ADMISSION does not authorize ${stage}` });
|
|
35
|
-
if (admission.publishable !== true && PUBLISHABLE_ONLY_STAGES.has(stage)) out.push({ code: "NOT_PUBLISHABLE", message: `ADMISSION does not mark this request publishable:true; it cannot reach ${stage}` });
|
|
36
|
-
return out;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const ENVELOPE_STRINGS = ["receiptId", "jobId", "requestId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "runtimeDigest", "executor", "issuedAt", "expiresAt", "keyId", "signature"];
|
|
40
|
-
const HEX64 = /^[0-9a-f]{64}$/;
|
|
41
|
-
const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex");
|
|
42
|
-
|
|
43
|
-
/** Domain-separated bytes a signature covers: receipt type bound in, signature field excluded. */
|
|
44
|
-
export function signingBytes(receipt) {
|
|
45
|
-
const { signature, ...rest } = receipt;
|
|
46
|
-
return Buffer.from(`${RECEIPT_SCHEMA}\0${receipt.type}\0${canonicalJson(rest)}`, "utf8");
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** The hash a child receipt records in `parents`: covers the whole receipt including its signature. */
|
|
50
|
-
export function receiptHash(receipt) {
|
|
51
|
-
return sha256(Buffer.concat([Buffer.from(`${RECEIPT_SCHEMA}.hash\0`, "utf8"), Buffer.from(canonicalJson(receipt), "utf8")]));
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** In-memory request ledger for tests and single-process brokers: records which job owns a requestId. */
|
|
55
|
-
export function createMemoryLedger() {
|
|
56
|
-
const owners = new Map(); const consumed = new Set();
|
|
57
|
-
return {
|
|
58
|
-
requestOwner: (requestId) => owners.get(requestId),
|
|
59
|
-
isConsumed: (receiptId) => consumed.has(receiptId),
|
|
60
|
-
record(chain) { for (const r of chain) { if (!owners.has(r.requestId)) owners.set(r.requestId, r.jobId); consumed.add(r.receiptId); } },
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
65
|
-
const nonEmptyString = (v) => typeof v === "string" && v.trim() !== "";
|
|
66
|
-
const isHex = (v) => typeof v === "string" && HEX64.test(v);
|
|
67
|
-
const nonEmptyArray = (v) => Array.isArray(v) && v.length > 0;
|
|
68
|
-
|
|
69
|
-
/** Stage-specific evidence checks. Each returns a list of problem messages. */
|
|
70
|
-
const STAGE_EVIDENCE = {
|
|
71
|
-
ADMISSION(e) {
|
|
72
|
-
const p = [];
|
|
73
|
-
for (const f of ["inputManifestDigest", "dependencyManifestDigest", "toolchainManifestDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
|
|
74
|
-
if (!nonEmptyArray(e.authorizedStages) || e.authorizedStages.some((s) => !STAGES.includes(s))) p.push("authorizedStages must list known stages");
|
|
75
|
-
if (typeof e.publishable !== "boolean") p.push("publishable must be a boolean");
|
|
76
|
-
return p;
|
|
77
|
-
},
|
|
78
|
-
SCAN_A: (e, ctx) => scanEvidence(e, "A", ctx),
|
|
79
|
-
ROUTE(e, ctx) {
|
|
80
|
-
const p = [];
|
|
81
|
-
const d = e.decision;
|
|
82
|
-
if (!isObj(d)) return ["decision is required"];
|
|
83
|
-
if (!["local", "ci"].includes(d.executor)) p.push("decision.executor must be local or ci");
|
|
84
|
-
if (!["public", "private"].includes(d.visibility)) p.push("decision.visibility must be public or private (unknown visibility is rejected)");
|
|
85
|
-
if (d.visibility === "private" && d.executor !== "local") p.push("a private repository never routes to CI");
|
|
86
|
-
if (typeof d.localGrant !== "boolean") p.push("decision.localGrant must be a boolean");
|
|
87
|
-
if (d.executor === "local" && !nonEmptyString(String(e.leaseFence ?? ""))) p.push("a local route needs a leaseFence");
|
|
88
|
-
if (d.executor === "ci" && !isObj(e.dispatchBinding)) p.push("a CI route needs a dispatchBinding");
|
|
89
|
-
if (!nonEmptyString(d.policyVersion)) p.push("decision.policyVersion is required");
|
|
90
|
-
return p;
|
|
91
|
-
},
|
|
92
|
-
SCAN_B: (e, ctx) => scanEvidence(e, "B", ctx),
|
|
93
|
-
BUILD(e) {
|
|
94
|
-
const p = [];
|
|
95
|
-
if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
|
|
96
|
-
if (!nonEmptyArray(e.artifacts) || e.artifacts.some((a) => !nonEmptyString(a?.path) || !isHex(a?.sha256))) p.push("artifacts must list path and sha256 for every output");
|
|
97
|
-
for (const f of ["generationEvidenceDigest", "provenanceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
|
|
98
|
-
if (!nonEmptyArray(e.targetMatrix)) p.push("targetMatrix must list the built targets");
|
|
99
|
-
return p;
|
|
100
|
-
},
|
|
101
|
-
SIGN(e, ctx) {
|
|
102
|
-
const p = [];
|
|
103
|
-
if (!["SIGN", "SEAL"].includes(e.mode)) p.push("mode must be SIGN or SEAL");
|
|
104
|
-
for (const f of ["inputManifestDigest", "outputManifestDigest", "signingEvidenceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
|
|
105
|
-
if (!nonEmptyString(e.signingProfile)) p.push("signingProfile is required");
|
|
106
|
-
const build = ctx.byStage.BUILD;
|
|
107
|
-
if (build && e.inputManifestDigest !== build.evidence?.artifactManifestDigest) p.push("inputManifestDigest does not equal the BUILD artifactManifestDigest");
|
|
108
|
-
return p;
|
|
109
|
-
},
|
|
110
|
-
QUALIFIED(e, ctx) {
|
|
111
|
-
const p = [];
|
|
112
|
-
if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
|
|
113
|
-
if (!nonEmptyArray(e.testMatrix) || e.testMatrix.some((t) => !nonEmptyString(t?.name) || t?.status !== "pass")) p.push("testMatrix must be non-empty and every row must pass");
|
|
114
|
-
const sign = ctx.byStage.SIGN;
|
|
115
|
-
if (sign && e.artifactManifestDigest !== sign.evidence?.outputManifestDigest) p.push("artifactManifestDigest does not equal the SIGN outputManifestDigest (qualification covers the final signed bytes)");
|
|
116
|
-
return p;
|
|
117
|
-
},
|
|
118
|
-
PUBLISH_INTENT(e, ctx) {
|
|
119
|
-
const p = [];
|
|
120
|
-
if (!isHex(e.releaseManifestDigest)) p.push("releaseManifestDigest must be a sha256 hex digest");
|
|
121
|
-
if (!nonEmptyArray(e.destinations) || e.destinations.some((d) => !nonEmptyString(d?.id) || !nonEmptyString(d?.identity) || !nonEmptyString(d?.version) || !isHex(d?.expectedDigest) || !nonEmptyString(d?.idempotencyKey))) {
|
|
122
|
-
p.push("destinations must name id, identity, version, expectedDigest and idempotencyKey");
|
|
123
|
-
}
|
|
124
|
-
const q = ctx.byStage.QUALIFIED;
|
|
125
|
-
if (q && e.releaseManifestDigest !== q.evidence?.artifactManifestDigest) p.push("releaseManifestDigest does not equal the QUALIFIED artifactManifestDigest");
|
|
126
|
-
return p;
|
|
127
|
-
},
|
|
128
|
-
PUBLISHED(e, ctx) {
|
|
129
|
-
const p = [];
|
|
130
|
-
const intent = ctx.byStage.PUBLISH_INTENT;
|
|
131
|
-
if (!nonEmptyArray(e.entries)) return ["entries must list every destination outcome"];
|
|
132
|
-
for (const d of intent?.evidence?.destinations ?? []) {
|
|
133
|
-
const entry = e.entries.find((x) => x?.destinationId === d.id);
|
|
134
|
-
if (!entry) p.push(`no entry for destination ${d.id}`);
|
|
135
|
-
else if (entry.outcome !== "verified") p.push(`destination ${d.id} is ${entry.outcome}, not verified`);
|
|
136
|
-
else if (entry.remoteDigest !== d.expectedDigest) p.push(`destination ${d.id} readback digest differs from the intent`);
|
|
137
|
-
}
|
|
138
|
-
return p;
|
|
139
|
-
},
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
function scanEvidence(e, cls, ctx) {
|
|
143
|
-
const p = [];
|
|
144
|
-
const other = cls === "A" ? "B" : "A";
|
|
145
|
-
if (e.scanClass !== cls) p.push(`scanClass must be ${cls}`);
|
|
146
|
-
if (!nonEmptyArray(e.scans)) return [...p, "scans must list every required scan result"];
|
|
147
|
-
if (cls === "A" && !isHex(e.advisorySnapshotDigest)) p.push("advisorySnapshotDigest must be a sha256 hex digest");
|
|
148
|
-
if (cls === "A" && !nonEmptyString(e.advisorySnapshotTime)) p.push("advisorySnapshotTime is required");
|
|
149
|
-
for (const s of e.scans) {
|
|
150
|
-
const derived = scanClassOf(s?.id);
|
|
151
|
-
if (s?.class === other || derived === other) p.push(`${cls === "A" ? "SCAN_A claims" : "SCAN_B carries"} class ${other} scan ${s?.id}`);
|
|
152
|
-
else if (s?.class !== cls) p.push(`scan ${s?.id} has class ${s?.class}, expected ${cls}`);
|
|
153
|
-
if (s?.status !== "pass") p.push(`scan ${s?.id} is ${s?.status}, not pass`);
|
|
154
|
-
}
|
|
155
|
-
const ids = new Set(e.scans.map((s) => s?.id));
|
|
156
|
-
const required = ctx.requiredScans?.[cls];
|
|
157
|
-
const declared = Array.isArray(e.requiredScanIds) ? e.requiredScanIds : null;
|
|
158
|
-
if (!declared) p.push("requiredScanIds is required");
|
|
159
|
-
// The required set comes only from the injected policy matrix. A receipt's own declaration is never trusted:
|
|
160
|
-
// without the policy, verification fails closed.
|
|
161
|
-
if (!Array.isArray(required) || required.some((id) => typeof id !== "string")) {
|
|
162
|
-
p.push(`trusted required scan set for class ${cls} is not supplied by policy; verification fails closed`);
|
|
163
|
-
return p;
|
|
164
|
-
}
|
|
165
|
-
for (const id of required) if (!ids.has(id)) p.push(`required class ${cls} scan ${id} is missing`);
|
|
166
|
-
if (declared && canonicalJson([...required].sort()) !== canonicalJson([...declared].sort())) p.push(`requiredScanIds differ from the trusted class ${cls} set`);
|
|
167
|
-
if (e.scanSetDigest !== digestScanSet(e.scans)) p.push("scanSetDigest does not match the listed scans");
|
|
168
|
-
if (cls === "B" && !nonEmptyArray(required)) p.push("SCAN_B must require at least one class B scan");
|
|
169
|
-
return p;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Verify a chain of receipts (ADMISSION first, ending at the stage being authorized).
|
|
174
|
-
*
|
|
175
|
-
* options:
|
|
176
|
-
* verifySignature({ receipt, keyId, signingBytes, signature }) -> boolean REQUIRED (the broker supplies keys)
|
|
177
|
-
* now ISO string or Date, default current time
|
|
178
|
-
* expected { requestId, operation, inputDigest, stage, repositoryId, commit, jobId, releaseId, targetSet } (each optional but checked when given)
|
|
179
|
-
* requiredScans { A: [ids], B: [ids] } trusted required sets from the policy matrix: REQUIRED; absence rejects (NO_SCAN_POLICY)
|
|
180
|
-
* ledger { requestOwner(requestId), isConsumed(receiptId) } REQUIRED: without it verification fails (NO_LEDGER)
|
|
181
|
-
* keyAllowed (keyId, receipt) -> boolean, for revocations
|
|
182
|
-
* Returns { ok, problems: [{ code, stage, message }], head }. Never throws on a bad receipt.
|
|
183
|
-
*/
|
|
184
|
-
export function verifyReceiptChain(chain, options = {}) {
|
|
185
|
-
const problems = [];
|
|
186
|
-
const bad = (code, stage, message) => problems.push({ code, stage: stage ?? null, message });
|
|
187
|
-
if (typeof options.verifySignature !== "function") return { ok: false, problems: [{ code: "NO_SIGNATURE_VERIFIER", stage: null, message: "a signature verifier must be supplied by the broker" }], head: null };
|
|
188
|
-
if (!Array.isArray(chain) || chain.length === 0) return { ok: false, problems: [{ code: "EMPTY_CHAIN", stage: null, message: "no receipts" }], head: null };
|
|
189
|
-
const now = new Date(options.now ?? Date.now()).getTime();
|
|
190
|
-
const expected = options.expected ?? {};
|
|
191
|
-
const byStage = {};
|
|
192
|
-
let previous = null;
|
|
193
|
-
// Replay protection is mandatory: without a ledger the chain cannot be proven fresh, so it fails closed.
|
|
194
|
-
if (typeof options.ledger?.requestOwner !== "function" || typeof options.ledger?.isConsumed !== "function") {
|
|
195
|
-
bad("NO_LEDGER", null, "a request ledger with requestOwner and isConsumed must be supplied; replay cannot be ruled out without it");
|
|
196
|
-
}
|
|
197
|
-
// One release id for the whole chain: the ADMISSION one when it has it, else the first release-stage one.
|
|
198
|
-
const releaseRef = chain.find((r) => isObj(r) && nonEmptyString(r.releaseId))?.releaseId;
|
|
199
|
-
// ADMISSION fixes which stages may run and whether the request may publish at all.
|
|
200
|
-
const admission = isObj(chain[0]) && chain[0].type === "ADMISSION" && isObj(chain[0].evidence) ? chain[0].evidence : null;
|
|
201
|
-
|
|
202
|
-
chain.forEach((receipt, index) => {
|
|
203
|
-
const stage = isObj(receipt) ? receipt.type : null;
|
|
204
|
-
if (!isObj(receipt)) { bad("MALFORMED", null, `receipt ${index} is not an object`); return; }
|
|
205
|
-
if (receipt.schema !== RECEIPT_SCHEMA) bad("SCHEMA", stage, `schema must be ${RECEIPT_SCHEMA}`);
|
|
206
|
-
if (!STAGES.includes(stage)) { bad("UNKNOWN_STAGE", stage, `unknown receipt type ${JSON.stringify(stage)}`); return; }
|
|
207
|
-
const wantStage = STAGES[index];
|
|
208
|
-
if (stage !== wantStage) bad("WRONG_STAGE", stage, `position ${index} requires ${wantStage}, got ${stage}`);
|
|
209
|
-
for (const f of ENVELOPE_STRINGS) if (!nonEmptyString(receipt[f])) bad("ENVELOPE", stage, `${f} is required`);
|
|
210
|
-
if (!Number.isInteger(receipt.attempt) || receipt.attempt < 1) bad("ENVELOPE", stage, "attempt must be an integer >= 1");
|
|
211
|
-
if (!Array.isArray(receipt.targetSet)) bad("ENVELOPE", stage, "targetSet must be an array");
|
|
212
|
-
if (!OPERATIONS.includes(receipt.operation)) bad("WRONG_OPERATION", stage, `unknown operation ${JSON.stringify(receipt.operation)}`);
|
|
213
|
-
if (RELEASE_ID_STAGES.has(stage) && !nonEmptyString(receipt.releaseId)) bad("ENVELOPE", stage, "releaseId is required");
|
|
214
|
-
if (!isObj(receipt.evidence)) bad("EVIDENCE", stage, "evidence is required");
|
|
215
|
-
|
|
216
|
-
// The operation bounds how far a request may go.
|
|
217
|
-
const last = OPERATION_LAST_STAGE[receipt.operation];
|
|
218
|
-
if (last && STAGES.indexOf(stage) > STAGES.indexOf(last)) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} does not authorize ${stage}`);
|
|
219
|
-
|
|
220
|
-
// ADMISSION bounds the chain: only its authorized stages, and nothing from SIGN on unless publishable:true.
|
|
221
|
-
for (const x of admissionProblems(admission, stage)) bad(x.code, stage, x.message);
|
|
222
|
-
|
|
223
|
-
// Binding to the caller's expectations.
|
|
224
|
-
if (expected.requestId !== undefined && receipt.requestId !== expected.requestId) bad("WRONG_REQUEST_ID", stage, "requestId differs from the expected request");
|
|
225
|
-
if (expected.operation !== undefined && receipt.operation !== expected.operation) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} differs from expected ${expected.operation}`);
|
|
226
|
-
if (expected.inputDigest !== undefined && receipt.inputDigest !== expected.inputDigest) bad("WRONG_INPUT_DIGEST", stage, "inputDigest differs from the expected input");
|
|
227
|
-
for (const f of ["repositoryId", "commit", "jobId", "releaseId"]) if (expected[f] !== undefined && receipt[f] !== expected[f]) bad("BINDING", stage, `${f} differs from the expected value`);
|
|
228
|
-
if (expected.targetSet !== undefined && canonicalJson(receipt.targetSet ?? null) !== canonicalJson(expected.targetSet)) bad("BINDING", stage, "targetSet differs from the expected value");
|
|
229
|
-
if (releaseRef !== undefined && receipt.releaseId !== undefined && receipt.releaseId !== releaseRef) bad("BINDING", stage, "releaseId differs from the chain's release");
|
|
230
|
-
|
|
231
|
-
// Consistency across the chain.
|
|
232
|
-
const first = chain[0];
|
|
233
|
-
if (index > 0 && isObj(first)) {
|
|
234
|
-
for (const f of ["requestId", "jobId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "operation", "targetSet"]) {
|
|
235
|
-
if (f === "targetSet" ? canonicalJson(receipt[f] ?? null) !== canonicalJson(first[f] ?? null) : receipt[f] !== first[f]) bad(f === "requestId" ? "WRONG_REQUEST_ID" : f === "inputDigest" ? "WRONG_INPUT_DIGEST" : f === "operation" ? "WRONG_OPERATION" : "BINDING", stage, `${f} differs from the ADMISSION receipt`);
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// Freshness.
|
|
240
|
-
const issued = Date.parse(receipt.issuedAt); const expires = Date.parse(receipt.expiresAt);
|
|
241
|
-
if (Number.isNaN(issued) || Number.isNaN(expires)) bad("ENVELOPE", stage, "issuedAt and expiresAt must be ISO timestamps");
|
|
242
|
-
else {
|
|
243
|
-
if (expires <= issued) bad("ENVELOPE", stage, "expiresAt must be after issuedAt");
|
|
244
|
-
if (expires <= now) bad("EXPIRED", stage, `expired at ${receipt.expiresAt}`);
|
|
245
|
-
if (issued > now + 60_000) bad("ENVELOPE", stage, "issuedAt is in the future");
|
|
246
|
-
if (previous && issued < Date.parse(previous.issuedAt)) bad("ORDER", stage, "issued before its parent receipt");
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
// Hash chain.
|
|
250
|
-
const wantParents = previous ? [receiptHash(previous)] : [];
|
|
251
|
-
if (!Array.isArray(receipt.parents) || canonicalJson(receipt.parents) !== canonicalJson(wantParents)) bad("BROKEN_CHAIN", stage, previous ? `parents must be exactly [hash of ${previous.type}]` : "ADMISSION has no parents");
|
|
252
|
-
|
|
253
|
-
// Replay (the ledger is required; see NO_LEDGER above).
|
|
254
|
-
if (typeof options.ledger?.requestOwner === "function" && typeof options.ledger?.isConsumed === "function") {
|
|
255
|
-
const owner = options.ledger.requestOwner(receipt.requestId);
|
|
256
|
-
if (owner !== undefined && owner !== receipt.jobId) bad("REPLAYED_REQUEST_ID", stage, "requestId already belongs to another job");
|
|
257
|
-
if (options.ledger.isConsumed(receipt.receiptId)) bad("REPLAYED_RECEIPT", stage, "receipt already consumed");
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Signature (injected).
|
|
261
|
-
if (options.keyAllowed && !options.keyAllowed(receipt.keyId, receipt)) bad("KEY_REVOKED", stage, `key ${receipt.keyId} is not allowed for this receipt`);
|
|
262
|
-
let signatureOk = false;
|
|
263
|
-
try { signatureOk = options.verifySignature({ receipt, keyId: receipt.keyId, signingBytes: signingBytes(receipt), signature: receipt.signature }) === true; } catch { signatureOk = false; }
|
|
264
|
-
if (!signatureOk) bad("BAD_SIGNATURE", stage, "signature did not verify");
|
|
265
|
-
|
|
266
|
-
byStage[stage] = receipt;
|
|
267
|
-
// Stage evidence last: it can look at the earlier stages collected so far.
|
|
268
|
-
if (isObj(receipt.evidence) && STAGE_EVIDENCE[stage]) {
|
|
269
|
-
for (const message of STAGE_EVIDENCE[stage](receipt.evidence, { byStage, requiredScans: options.requiredScans })) {
|
|
270
|
-
const code = /trusted required scan set/.test(message) ? "NO_SCAN_POLICY" : /missing|claims|carries/.test(message) && (stage === "SCAN_A" || stage === "SCAN_B") ? (/claims|carries/.test(message) ? "SCAN_CLASS_MIX" : "SCAN_INCOMPLETE") : "EVIDENCE";
|
|
271
|
-
bad(code, stage, message);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
previous = receipt;
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
const head = chain[chain.length - 1];
|
|
278
|
-
if (expected.stage !== undefined) {
|
|
279
|
-
if (!STAGES.includes(expected.stage)) bad("WRONG_STAGE", null, `unknown expected stage ${expected.stage}`);
|
|
280
|
-
else if (head?.type !== expected.stage) bad("WRONG_STAGE", head?.type, `chain ends at ${head?.type}, expected ${expected.stage}`);
|
|
281
|
-
}
|
|
282
|
-
return { ok: problems.length === 0, problems, head: isObj(head) ? { type: head.type, hash: receiptHash(head) } : null };
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
/**
|
|
286
|
-
* Verify that a new stage may start: the chain so far must verify and end at the stage `stage` requires.
|
|
287
|
-
* Returns the same result shape; `authorizes` is the stage the chain authorizes next (or null).
|
|
288
|
-
*/
|
|
289
|
-
export function authorizeNextStage(chain, stage, options = {}) {
|
|
290
|
-
const need = PREREQUISITES[stage];
|
|
291
|
-
if (!need) return { ok: false, problems: [{ code: "UNKNOWN_STAGE", stage, message: `unknown stage ${stage}` }], head: null, authorizes: null };
|
|
292
|
-
if (need.length === 0) return { ok: !chain?.length, problems: chain?.length ? [{ code: "WRONG_STAGE", stage, message: "ADMISSION starts a chain" }] : [], head: null, authorizes: chain?.length ? null : stage };
|
|
293
|
-
const result = verifyReceiptChain(chain, { ...options, expected: { ...(options.expected ?? {}), stage: need[0] } });
|
|
294
|
-
// The requested stage itself must sit inside the operation's boundary and ADMISSION's authorized stages.
|
|
295
|
-
const first = Array.isArray(chain) ? chain[0] : null;
|
|
296
|
-
const last = OPERATION_LAST_STAGE[first?.operation];
|
|
297
|
-
if (!last || STAGES.indexOf(stage) > STAGES.indexOf(last)) result.problems.push({ code: "WRONG_OPERATION", stage, message: `operation ${first?.operation} does not authorize ${stage}` });
|
|
298
|
-
const admission = first?.type === "ADMISSION" && isObj(first.evidence) ? first.evidence : null;
|
|
299
|
-
for (const x of admissionProblems(admission, stage)) result.problems.push({ code: x.code, stage, message: x.message });
|
|
300
|
-
result.ok = result.problems.length === 0;
|
|
301
|
-
return { ...result, authorizes: result.ok ? stage : null };
|
|
302
|
-
}
|
|
1
|
+
// Pipeline stage receipts and their verifier (architecture-v3 sections 4-5, "Receipts").
|
|
2
|
+
//
|
|
3
|
+
// A receipt records a fact about one stage of one request. It never authorizes execution alone: the
|
|
4
|
+
// broker (RustRight) signs receipts and issues short-lived capabilities; this module only checks that
|
|
5
|
+
// a chain of receipts is well formed, linked, fresh and complete. Signature checking is an injected
|
|
6
|
+
// interface (`verifySignature`); this module does no cryptography beyond SHA-256 hashing and invents none.
|
|
7
|
+
//
|
|
8
|
+
// Chain: ADMISSION -> SCAN_A -> ROUTE -> SCAN_B -> BUILD -> SIGN -> QUALIFIED -> PUBLISH_INTENT -> PUBLISHED.
|
|
9
|
+
// Each stage requires exactly its predecessor; `parents` carries that predecessor's receipt hash.
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import { canonicalJson, digestScanSet, scanClassOf } from "./deterministic-scans.mjs";
|
|
12
|
+
|
|
13
|
+
export const RECEIPT_SCHEMA = "rightkit.pipeline-receipt/1";
|
|
14
|
+
export const STAGES = Object.freeze(["ADMISSION", "SCAN_A", "ROUTE", "SCAN_B", "BUILD", "SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
|
|
15
|
+
export const OPERATIONS = Object.freeze(["dev", "build", "qualify", "sign", "publish"]);
|
|
16
|
+
/** The last stage each operation may reach. */
|
|
17
|
+
export const OPERATION_LAST_STAGE = Object.freeze({ dev: "BUILD", build: "BUILD", sign: "SIGN", qualify: "QUALIFIED", publish: "PUBLISHED" });
|
|
18
|
+
/** Each stage requires only these predecessors. */
|
|
19
|
+
export const PREREQUISITES = Object.freeze({
|
|
20
|
+
ADMISSION: [], SCAN_A: ["ADMISSION"], ROUTE: ["SCAN_A"], SCAN_B: ["ROUTE"], BUILD: ["SCAN_B"],
|
|
21
|
+
SIGN: ["BUILD"], QUALIFIED: ["SIGN"], PUBLISH_INTENT: ["QUALIFIED"], PUBLISHED: ["PUBLISH_INTENT"],
|
|
22
|
+
});
|
|
23
|
+
const RELEASE_ID_STAGES = new Set(["SIGN", "QUALIFIED", "PUBLISH_INTENT", "PUBLISHED"]);
|
|
24
|
+
/** Stages only a publishable request may reach: signing and everything after it. A dev or non-publishable chain stops at BUILD. */
|
|
25
|
+
const PUBLISHABLE_ONLY_STAGES = new Set(RELEASE_ID_STAGES);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What ADMISSION's evidence allows for `stage`, as [{ code, message }]. ADMISSION is the sole authority:
|
|
29
|
+
* a missing or malformed ADMISSION authorizes nothing, and `publishable` must be exactly true to reach SIGN or later.
|
|
30
|
+
*/
|
|
31
|
+
function admissionProblems(admission, stage) {
|
|
32
|
+
const out = [];
|
|
33
|
+
if (!admission) return [{ code: "STAGE_NOT_AUTHORIZED", message: `no valid ADMISSION evidence authorizes ${stage}` }];
|
|
34
|
+
if (!Array.isArray(admission.authorizedStages) || !admission.authorizedStages.includes(stage)) out.push({ code: "STAGE_NOT_AUTHORIZED", message: `ADMISSION does not authorize ${stage}` });
|
|
35
|
+
if (admission.publishable !== true && PUBLISHABLE_ONLY_STAGES.has(stage)) out.push({ code: "NOT_PUBLISHABLE", message: `ADMISSION does not mark this request publishable:true; it cannot reach ${stage}` });
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const ENVELOPE_STRINGS = ["receiptId", "jobId", "requestId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "runtimeDigest", "executor", "issuedAt", "expiresAt", "keyId", "signature"];
|
|
40
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
41
|
+
const sha256 = (value) => crypto.createHash("sha256").update(value).digest("hex");
|
|
42
|
+
|
|
43
|
+
/** Domain-separated bytes a signature covers: receipt type bound in, signature field excluded. */
|
|
44
|
+
export function signingBytes(receipt) {
|
|
45
|
+
const { signature, ...rest } = receipt;
|
|
46
|
+
return Buffer.from(`${RECEIPT_SCHEMA}\0${receipt.type}\0${canonicalJson(rest)}`, "utf8");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The hash a child receipt records in `parents`: covers the whole receipt including its signature. */
|
|
50
|
+
export function receiptHash(receipt) {
|
|
51
|
+
return sha256(Buffer.concat([Buffer.from(`${RECEIPT_SCHEMA}.hash\0`, "utf8"), Buffer.from(canonicalJson(receipt), "utf8")]));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** In-memory request ledger for tests and single-process brokers: records which job owns a requestId. */
|
|
55
|
+
export function createMemoryLedger() {
|
|
56
|
+
const owners = new Map(); const consumed = new Set();
|
|
57
|
+
return {
|
|
58
|
+
requestOwner: (requestId) => owners.get(requestId),
|
|
59
|
+
isConsumed: (receiptId) => consumed.has(receiptId),
|
|
60
|
+
record(chain) { for (const r of chain) { if (!owners.has(r.requestId)) owners.set(r.requestId, r.jobId); consumed.add(r.receiptId); } },
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
65
|
+
const nonEmptyString = (v) => typeof v === "string" && v.trim() !== "";
|
|
66
|
+
const isHex = (v) => typeof v === "string" && HEX64.test(v);
|
|
67
|
+
const nonEmptyArray = (v) => Array.isArray(v) && v.length > 0;
|
|
68
|
+
|
|
69
|
+
/** Stage-specific evidence checks. Each returns a list of problem messages. */
|
|
70
|
+
const STAGE_EVIDENCE = {
|
|
71
|
+
ADMISSION(e) {
|
|
72
|
+
const p = [];
|
|
73
|
+
for (const f of ["inputManifestDigest", "dependencyManifestDigest", "toolchainManifestDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
|
|
74
|
+
if (!nonEmptyArray(e.authorizedStages) || e.authorizedStages.some((s) => !STAGES.includes(s))) p.push("authorizedStages must list known stages");
|
|
75
|
+
if (typeof e.publishable !== "boolean") p.push("publishable must be a boolean");
|
|
76
|
+
return p;
|
|
77
|
+
},
|
|
78
|
+
SCAN_A: (e, ctx) => scanEvidence(e, "A", ctx),
|
|
79
|
+
ROUTE(e, ctx) {
|
|
80
|
+
const p = [];
|
|
81
|
+
const d = e.decision;
|
|
82
|
+
if (!isObj(d)) return ["decision is required"];
|
|
83
|
+
if (!["local", "ci"].includes(d.executor)) p.push("decision.executor must be local or ci");
|
|
84
|
+
if (!["public", "private"].includes(d.visibility)) p.push("decision.visibility must be public or private (unknown visibility is rejected)");
|
|
85
|
+
if (d.visibility === "private" && d.executor !== "local") p.push("a private repository never routes to CI");
|
|
86
|
+
if (typeof d.localGrant !== "boolean") p.push("decision.localGrant must be a boolean");
|
|
87
|
+
if (d.executor === "local" && !nonEmptyString(String(e.leaseFence ?? ""))) p.push("a local route needs a leaseFence");
|
|
88
|
+
if (d.executor === "ci" && !isObj(e.dispatchBinding)) p.push("a CI route needs a dispatchBinding");
|
|
89
|
+
if (!nonEmptyString(d.policyVersion)) p.push("decision.policyVersion is required");
|
|
90
|
+
return p;
|
|
91
|
+
},
|
|
92
|
+
SCAN_B: (e, ctx) => scanEvidence(e, "B", ctx),
|
|
93
|
+
BUILD(e) {
|
|
94
|
+
const p = [];
|
|
95
|
+
if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
|
|
96
|
+
if (!nonEmptyArray(e.artifacts) || e.artifacts.some((a) => !nonEmptyString(a?.path) || !isHex(a?.sha256))) p.push("artifacts must list path and sha256 for every output");
|
|
97
|
+
for (const f of ["generationEvidenceDigest", "provenanceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
|
|
98
|
+
if (!nonEmptyArray(e.targetMatrix)) p.push("targetMatrix must list the built targets");
|
|
99
|
+
return p;
|
|
100
|
+
},
|
|
101
|
+
SIGN(e, ctx) {
|
|
102
|
+
const p = [];
|
|
103
|
+
if (!["SIGN", "SEAL"].includes(e.mode)) p.push("mode must be SIGN or SEAL");
|
|
104
|
+
for (const f of ["inputManifestDigest", "outputManifestDigest", "signingEvidenceDigest"]) if (!isHex(e[f])) p.push(`${f} must be a sha256 hex digest`);
|
|
105
|
+
if (!nonEmptyString(e.signingProfile)) p.push("signingProfile is required");
|
|
106
|
+
const build = ctx.byStage.BUILD;
|
|
107
|
+
if (build && e.inputManifestDigest !== build.evidence?.artifactManifestDigest) p.push("inputManifestDigest does not equal the BUILD artifactManifestDigest");
|
|
108
|
+
return p;
|
|
109
|
+
},
|
|
110
|
+
QUALIFIED(e, ctx) {
|
|
111
|
+
const p = [];
|
|
112
|
+
if (!isHex(e.artifactManifestDigest)) p.push("artifactManifestDigest must be a sha256 hex digest");
|
|
113
|
+
if (!nonEmptyArray(e.testMatrix) || e.testMatrix.some((t) => !nonEmptyString(t?.name) || t?.status !== "pass")) p.push("testMatrix must be non-empty and every row must pass");
|
|
114
|
+
const sign = ctx.byStage.SIGN;
|
|
115
|
+
if (sign && e.artifactManifestDigest !== sign.evidence?.outputManifestDigest) p.push("artifactManifestDigest does not equal the SIGN outputManifestDigest (qualification covers the final signed bytes)");
|
|
116
|
+
return p;
|
|
117
|
+
},
|
|
118
|
+
PUBLISH_INTENT(e, ctx) {
|
|
119
|
+
const p = [];
|
|
120
|
+
if (!isHex(e.releaseManifestDigest)) p.push("releaseManifestDigest must be a sha256 hex digest");
|
|
121
|
+
if (!nonEmptyArray(e.destinations) || e.destinations.some((d) => !nonEmptyString(d?.id) || !nonEmptyString(d?.identity) || !nonEmptyString(d?.version) || !isHex(d?.expectedDigest) || !nonEmptyString(d?.idempotencyKey))) {
|
|
122
|
+
p.push("destinations must name id, identity, version, expectedDigest and idempotencyKey");
|
|
123
|
+
}
|
|
124
|
+
const q = ctx.byStage.QUALIFIED;
|
|
125
|
+
if (q && e.releaseManifestDigest !== q.evidence?.artifactManifestDigest) p.push("releaseManifestDigest does not equal the QUALIFIED artifactManifestDigest");
|
|
126
|
+
return p;
|
|
127
|
+
},
|
|
128
|
+
PUBLISHED(e, ctx) {
|
|
129
|
+
const p = [];
|
|
130
|
+
const intent = ctx.byStage.PUBLISH_INTENT;
|
|
131
|
+
if (!nonEmptyArray(e.entries)) return ["entries must list every destination outcome"];
|
|
132
|
+
for (const d of intent?.evidence?.destinations ?? []) {
|
|
133
|
+
const entry = e.entries.find((x) => x?.destinationId === d.id);
|
|
134
|
+
if (!entry) p.push(`no entry for destination ${d.id}`);
|
|
135
|
+
else if (entry.outcome !== "verified") p.push(`destination ${d.id} is ${entry.outcome}, not verified`);
|
|
136
|
+
else if (entry.remoteDigest !== d.expectedDigest) p.push(`destination ${d.id} readback digest differs from the intent`);
|
|
137
|
+
}
|
|
138
|
+
return p;
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
function scanEvidence(e, cls, ctx) {
|
|
143
|
+
const p = [];
|
|
144
|
+
const other = cls === "A" ? "B" : "A";
|
|
145
|
+
if (e.scanClass !== cls) p.push(`scanClass must be ${cls}`);
|
|
146
|
+
if (!nonEmptyArray(e.scans)) return [...p, "scans must list every required scan result"];
|
|
147
|
+
if (cls === "A" && !isHex(e.advisorySnapshotDigest)) p.push("advisorySnapshotDigest must be a sha256 hex digest");
|
|
148
|
+
if (cls === "A" && !nonEmptyString(e.advisorySnapshotTime)) p.push("advisorySnapshotTime is required");
|
|
149
|
+
for (const s of e.scans) {
|
|
150
|
+
const derived = scanClassOf(s?.id);
|
|
151
|
+
if (s?.class === other || derived === other) p.push(`${cls === "A" ? "SCAN_A claims" : "SCAN_B carries"} class ${other} scan ${s?.id}`);
|
|
152
|
+
else if (s?.class !== cls) p.push(`scan ${s?.id} has class ${s?.class}, expected ${cls}`);
|
|
153
|
+
if (s?.status !== "pass") p.push(`scan ${s?.id} is ${s?.status}, not pass`);
|
|
154
|
+
}
|
|
155
|
+
const ids = new Set(e.scans.map((s) => s?.id));
|
|
156
|
+
const required = ctx.requiredScans?.[cls];
|
|
157
|
+
const declared = Array.isArray(e.requiredScanIds) ? e.requiredScanIds : null;
|
|
158
|
+
if (!declared) p.push("requiredScanIds is required");
|
|
159
|
+
// The required set comes only from the injected policy matrix. A receipt's own declaration is never trusted:
|
|
160
|
+
// without the policy, verification fails closed.
|
|
161
|
+
if (!Array.isArray(required) || required.some((id) => typeof id !== "string")) {
|
|
162
|
+
p.push(`trusted required scan set for class ${cls} is not supplied by policy; verification fails closed`);
|
|
163
|
+
return p;
|
|
164
|
+
}
|
|
165
|
+
for (const id of required) if (!ids.has(id)) p.push(`required class ${cls} scan ${id} is missing`);
|
|
166
|
+
if (declared && canonicalJson([...required].sort()) !== canonicalJson([...declared].sort())) p.push(`requiredScanIds differ from the trusted class ${cls} set`);
|
|
167
|
+
if (e.scanSetDigest !== digestScanSet(e.scans)) p.push("scanSetDigest does not match the listed scans");
|
|
168
|
+
if (cls === "B" && !nonEmptyArray(required)) p.push("SCAN_B must require at least one class B scan");
|
|
169
|
+
return p;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Verify a chain of receipts (ADMISSION first, ending at the stage being authorized).
|
|
174
|
+
*
|
|
175
|
+
* options:
|
|
176
|
+
* verifySignature({ receipt, keyId, signingBytes, signature }) -> boolean REQUIRED (the broker supplies keys)
|
|
177
|
+
* now ISO string or Date, default current time
|
|
178
|
+
* expected { requestId, operation, inputDigest, stage, repositoryId, commit, jobId, releaseId, targetSet } (each optional but checked when given)
|
|
179
|
+
* requiredScans { A: [ids], B: [ids] } trusted required sets from the policy matrix: REQUIRED; absence rejects (NO_SCAN_POLICY)
|
|
180
|
+
* ledger { requestOwner(requestId), isConsumed(receiptId) } REQUIRED: without it verification fails (NO_LEDGER)
|
|
181
|
+
* keyAllowed (keyId, receipt) -> boolean, for revocations
|
|
182
|
+
* Returns { ok, problems: [{ code, stage, message }], head }. Never throws on a bad receipt.
|
|
183
|
+
*/
|
|
184
|
+
export function verifyReceiptChain(chain, options = {}) {
|
|
185
|
+
const problems = [];
|
|
186
|
+
const bad = (code, stage, message) => problems.push({ code, stage: stage ?? null, message });
|
|
187
|
+
if (typeof options.verifySignature !== "function") return { ok: false, problems: [{ code: "NO_SIGNATURE_VERIFIER", stage: null, message: "a signature verifier must be supplied by the broker" }], head: null };
|
|
188
|
+
if (!Array.isArray(chain) || chain.length === 0) return { ok: false, problems: [{ code: "EMPTY_CHAIN", stage: null, message: "no receipts" }], head: null };
|
|
189
|
+
const now = new Date(options.now ?? Date.now()).getTime();
|
|
190
|
+
const expected = options.expected ?? {};
|
|
191
|
+
const byStage = {};
|
|
192
|
+
let previous = null;
|
|
193
|
+
// Replay protection is mandatory: without a ledger the chain cannot be proven fresh, so it fails closed.
|
|
194
|
+
if (typeof options.ledger?.requestOwner !== "function" || typeof options.ledger?.isConsumed !== "function") {
|
|
195
|
+
bad("NO_LEDGER", null, "a request ledger with requestOwner and isConsumed must be supplied; replay cannot be ruled out without it");
|
|
196
|
+
}
|
|
197
|
+
// One release id for the whole chain: the ADMISSION one when it has it, else the first release-stage one.
|
|
198
|
+
const releaseRef = chain.find((r) => isObj(r) && nonEmptyString(r.releaseId))?.releaseId;
|
|
199
|
+
// ADMISSION fixes which stages may run and whether the request may publish at all.
|
|
200
|
+
const admission = isObj(chain[0]) && chain[0].type === "ADMISSION" && isObj(chain[0].evidence) ? chain[0].evidence : null;
|
|
201
|
+
|
|
202
|
+
chain.forEach((receipt, index) => {
|
|
203
|
+
const stage = isObj(receipt) ? receipt.type : null;
|
|
204
|
+
if (!isObj(receipt)) { bad("MALFORMED", null, `receipt ${index} is not an object`); return; }
|
|
205
|
+
if (receipt.schema !== RECEIPT_SCHEMA) bad("SCHEMA", stage, `schema must be ${RECEIPT_SCHEMA}`);
|
|
206
|
+
if (!STAGES.includes(stage)) { bad("UNKNOWN_STAGE", stage, `unknown receipt type ${JSON.stringify(stage)}`); return; }
|
|
207
|
+
const wantStage = STAGES[index];
|
|
208
|
+
if (stage !== wantStage) bad("WRONG_STAGE", stage, `position ${index} requires ${wantStage}, got ${stage}`);
|
|
209
|
+
for (const f of ENVELOPE_STRINGS) if (!nonEmptyString(receipt[f])) bad("ENVELOPE", stage, `${f} is required`);
|
|
210
|
+
if (!Number.isInteger(receipt.attempt) || receipt.attempt < 1) bad("ENVELOPE", stage, "attempt must be an integer >= 1");
|
|
211
|
+
if (!Array.isArray(receipt.targetSet)) bad("ENVELOPE", stage, "targetSet must be an array");
|
|
212
|
+
if (!OPERATIONS.includes(receipt.operation)) bad("WRONG_OPERATION", stage, `unknown operation ${JSON.stringify(receipt.operation)}`);
|
|
213
|
+
if (RELEASE_ID_STAGES.has(stage) && !nonEmptyString(receipt.releaseId)) bad("ENVELOPE", stage, "releaseId is required");
|
|
214
|
+
if (!isObj(receipt.evidence)) bad("EVIDENCE", stage, "evidence is required");
|
|
215
|
+
|
|
216
|
+
// The operation bounds how far a request may go.
|
|
217
|
+
const last = OPERATION_LAST_STAGE[receipt.operation];
|
|
218
|
+
if (last && STAGES.indexOf(stage) > STAGES.indexOf(last)) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} does not authorize ${stage}`);
|
|
219
|
+
|
|
220
|
+
// ADMISSION bounds the chain: only its authorized stages, and nothing from SIGN on unless publishable:true.
|
|
221
|
+
for (const x of admissionProblems(admission, stage)) bad(x.code, stage, x.message);
|
|
222
|
+
|
|
223
|
+
// Binding to the caller's expectations.
|
|
224
|
+
if (expected.requestId !== undefined && receipt.requestId !== expected.requestId) bad("WRONG_REQUEST_ID", stage, "requestId differs from the expected request");
|
|
225
|
+
if (expected.operation !== undefined && receipt.operation !== expected.operation) bad("WRONG_OPERATION", stage, `operation ${receipt.operation} differs from expected ${expected.operation}`);
|
|
226
|
+
if (expected.inputDigest !== undefined && receipt.inputDigest !== expected.inputDigest) bad("WRONG_INPUT_DIGEST", stage, "inputDigest differs from the expected input");
|
|
227
|
+
for (const f of ["repositoryId", "commit", "jobId", "releaseId"]) if (expected[f] !== undefined && receipt[f] !== expected[f]) bad("BINDING", stage, `${f} differs from the expected value`);
|
|
228
|
+
if (expected.targetSet !== undefined && canonicalJson(receipt.targetSet ?? null) !== canonicalJson(expected.targetSet)) bad("BINDING", stage, "targetSet differs from the expected value");
|
|
229
|
+
if (releaseRef !== undefined && receipt.releaseId !== undefined && receipt.releaseId !== releaseRef) bad("BINDING", stage, "releaseId differs from the chain's release");
|
|
230
|
+
|
|
231
|
+
// Consistency across the chain.
|
|
232
|
+
const first = chain[0];
|
|
233
|
+
if (index > 0 && isObj(first)) {
|
|
234
|
+
for (const f of ["requestId", "jobId", "repositoryId", "commit", "inputDigest", "configDigest", "policyDigest", "stagePlanDigest", "operation", "targetSet"]) {
|
|
235
|
+
if (f === "targetSet" ? canonicalJson(receipt[f] ?? null) !== canonicalJson(first[f] ?? null) : receipt[f] !== first[f]) bad(f === "requestId" ? "WRONG_REQUEST_ID" : f === "inputDigest" ? "WRONG_INPUT_DIGEST" : f === "operation" ? "WRONG_OPERATION" : "BINDING", stage, `${f} differs from the ADMISSION receipt`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Freshness.
|
|
240
|
+
const issued = Date.parse(receipt.issuedAt); const expires = Date.parse(receipt.expiresAt);
|
|
241
|
+
if (Number.isNaN(issued) || Number.isNaN(expires)) bad("ENVELOPE", stage, "issuedAt and expiresAt must be ISO timestamps");
|
|
242
|
+
else {
|
|
243
|
+
if (expires <= issued) bad("ENVELOPE", stage, "expiresAt must be after issuedAt");
|
|
244
|
+
if (expires <= now) bad("EXPIRED", stage, `expired at ${receipt.expiresAt}`);
|
|
245
|
+
if (issued > now + 60_000) bad("ENVELOPE", stage, "issuedAt is in the future");
|
|
246
|
+
if (previous && issued < Date.parse(previous.issuedAt)) bad("ORDER", stage, "issued before its parent receipt");
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Hash chain.
|
|
250
|
+
const wantParents = previous ? [receiptHash(previous)] : [];
|
|
251
|
+
if (!Array.isArray(receipt.parents) || canonicalJson(receipt.parents) !== canonicalJson(wantParents)) bad("BROKEN_CHAIN", stage, previous ? `parents must be exactly [hash of ${previous.type}]` : "ADMISSION has no parents");
|
|
252
|
+
|
|
253
|
+
// Replay (the ledger is required; see NO_LEDGER above).
|
|
254
|
+
if (typeof options.ledger?.requestOwner === "function" && typeof options.ledger?.isConsumed === "function") {
|
|
255
|
+
const owner = options.ledger.requestOwner(receipt.requestId);
|
|
256
|
+
if (owner !== undefined && owner !== receipt.jobId) bad("REPLAYED_REQUEST_ID", stage, "requestId already belongs to another job");
|
|
257
|
+
if (options.ledger.isConsumed(receipt.receiptId)) bad("REPLAYED_RECEIPT", stage, "receipt already consumed");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Signature (injected).
|
|
261
|
+
if (options.keyAllowed && !options.keyAllowed(receipt.keyId, receipt)) bad("KEY_REVOKED", stage, `key ${receipt.keyId} is not allowed for this receipt`);
|
|
262
|
+
let signatureOk = false;
|
|
263
|
+
try { signatureOk = options.verifySignature({ receipt, keyId: receipt.keyId, signingBytes: signingBytes(receipt), signature: receipt.signature }) === true; } catch { signatureOk = false; }
|
|
264
|
+
if (!signatureOk) bad("BAD_SIGNATURE", stage, "signature did not verify");
|
|
265
|
+
|
|
266
|
+
byStage[stage] = receipt;
|
|
267
|
+
// Stage evidence last: it can look at the earlier stages collected so far.
|
|
268
|
+
if (isObj(receipt.evidence) && STAGE_EVIDENCE[stage]) {
|
|
269
|
+
for (const message of STAGE_EVIDENCE[stage](receipt.evidence, { byStage, requiredScans: options.requiredScans })) {
|
|
270
|
+
const code = /trusted required scan set/.test(message) ? "NO_SCAN_POLICY" : /missing|claims|carries/.test(message) && (stage === "SCAN_A" || stage === "SCAN_B") ? (/claims|carries/.test(message) ? "SCAN_CLASS_MIX" : "SCAN_INCOMPLETE") : "EVIDENCE";
|
|
271
|
+
bad(code, stage, message);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
previous = receipt;
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
const head = chain[chain.length - 1];
|
|
278
|
+
if (expected.stage !== undefined) {
|
|
279
|
+
if (!STAGES.includes(expected.stage)) bad("WRONG_STAGE", null, `unknown expected stage ${expected.stage}`);
|
|
280
|
+
else if (head?.type !== expected.stage) bad("WRONG_STAGE", head?.type, `chain ends at ${head?.type}, expected ${expected.stage}`);
|
|
281
|
+
}
|
|
282
|
+
return { ok: problems.length === 0, problems, head: isObj(head) ? { type: head.type, hash: receiptHash(head) } : null };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Verify that a new stage may start: the chain so far must verify and end at the stage `stage` requires.
|
|
287
|
+
* Returns the same result shape; `authorizes` is the stage the chain authorizes next (or null).
|
|
288
|
+
*/
|
|
289
|
+
export function authorizeNextStage(chain, stage, options = {}) {
|
|
290
|
+
const need = PREREQUISITES[stage];
|
|
291
|
+
if (!need) return { ok: false, problems: [{ code: "UNKNOWN_STAGE", stage, message: `unknown stage ${stage}` }], head: null, authorizes: null };
|
|
292
|
+
if (need.length === 0) return { ok: !chain?.length, problems: chain?.length ? [{ code: "WRONG_STAGE", stage, message: "ADMISSION starts a chain" }] : [], head: null, authorizes: chain?.length ? null : stage };
|
|
293
|
+
const result = verifyReceiptChain(chain, { ...options, expected: { ...(options.expected ?? {}), stage: need[0] } });
|
|
294
|
+
// The requested stage itself must sit inside the operation's boundary and ADMISSION's authorized stages.
|
|
295
|
+
const first = Array.isArray(chain) ? chain[0] : null;
|
|
296
|
+
const last = OPERATION_LAST_STAGE[first?.operation];
|
|
297
|
+
if (!last || STAGES.indexOf(stage) > STAGES.indexOf(last)) result.problems.push({ code: "WRONG_OPERATION", stage, message: `operation ${first?.operation} does not authorize ${stage}` });
|
|
298
|
+
const admission = first?.type === "ADMISSION" && isObj(first.evidence) ? first.evidence : null;
|
|
299
|
+
for (const x of admissionProblems(admission, stage)) result.problems.push({ code: x.code, stage, message: x.message });
|
|
300
|
+
result.ok = result.problems.length === 0;
|
|
301
|
+
return { ...result, authorizes: result.ok ? stage : null };
|
|
302
|
+
}
|
package/rightkit-versions.json
CHANGED
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"@rightkit/qa": "0.6.2",
|
|
50
50
|
"@rightkit/qa-chrome": "0.1.12",
|
|
51
51
|
"@rightkit/react-shell": "0.7.2",
|
|
52
|
-
"@rightkit/release": "0.6.
|
|
52
|
+
"@rightkit/release": "0.6.28",
|
|
53
53
|
"@rightkit/settings-ui": "0.7.0",
|
|
54
54
|
"@rightkit/social-ui": "0.1.0",
|
|
55
55
|
"@rightkit/system-ui": "0.1.0",
|
package/bin/darwin/rightkit-swap
DELETED
|
Binary file
|