neurarch 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +507 -0
- package/README.md +662 -152
- package/attest.bundle.mjs +343 -0
- package/bin/attest.mjs +188 -0
- package/bin/neurarch.mjs +109 -22
- package/bin/pinCheck.mjs +138 -0
- package/bin/policy.mjs +320 -0
- package/bin/scan.mjs +255 -0
- package/bin/templateCheck.mjs +99 -0
- package/bin/weightsDiff.mjs +35 -0
- package/engine.bundle.mjs +9481 -1364
- package/examples/.neurarch.yml +44 -0
- package/examples/github-attest.yml +69 -0
- package/examples/github-precheck.yml +40 -0
- package/package.json +5 -2
- package/policy.bundle.mjs +8392 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// src/utils/attestation/index.ts
|
|
2
|
+
var STATEMENT_TYPE = "https://in-toto.io/Statement/v1";
|
|
3
|
+
var PREDICATE_TYPE = "https://in-toto.io/attestation/test-result/v0.1";
|
|
4
|
+
var EXTENSION_FIELD = "neurarchPrecheck";
|
|
5
|
+
var ATTESTATION_SCHEMA_ID = "https://neurarch.com/schema/precheck-attestation-v1.json";
|
|
6
|
+
var MODEL_SIGNING_PREDICATE_TYPE = "https://model_signing/signature/v1.0";
|
|
7
|
+
var MT_IGNORE_PATHS = [".git", ".gitattributes", ".github", ".gitignore"];
|
|
8
|
+
function cmpCodePoints(a, b) {
|
|
9
|
+
const A = Array.from(a);
|
|
10
|
+
const B = Array.from(b);
|
|
11
|
+
for (let i = 0; i < Math.min(A.length, B.length); i++) {
|
|
12
|
+
const x = A[i].codePointAt(0);
|
|
13
|
+
const y = B[i].codePointAt(0);
|
|
14
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
15
|
+
}
|
|
16
|
+
return A.length - B.length;
|
|
17
|
+
}
|
|
18
|
+
function compareManifestPaths(a, b) {
|
|
19
|
+
const A = a.split("/");
|
|
20
|
+
const B = b.split("/");
|
|
21
|
+
for (let i = 0; i < Math.min(A.length, B.length); i++) {
|
|
22
|
+
const c = cmpCodePoints(A[i], B[i]);
|
|
23
|
+
if (c !== 0) return c;
|
|
24
|
+
}
|
|
25
|
+
return A.length - B.length;
|
|
26
|
+
}
|
|
27
|
+
var HEX = /^[0-9a-f]{64}$/;
|
|
28
|
+
function hexToBytes(hex) {
|
|
29
|
+
const out = new Uint8Array(hex.length / 2);
|
|
30
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
function isIgnoredByDefault(path) {
|
|
34
|
+
const top = path.split("/")[0];
|
|
35
|
+
return MT_IGNORE_PATHS.includes(top);
|
|
36
|
+
}
|
|
37
|
+
function manifestFiles(files, extraIgnored = []) {
|
|
38
|
+
const seen = /* @__PURE__ */ new Set();
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const f of files) {
|
|
41
|
+
const p = f.path.replace(/^\.\//, "");
|
|
42
|
+
if (!p || p.startsWith("/") || p.split("/").includes("..")) throw new Error(`not a path relative to the model root: ${f.path}`);
|
|
43
|
+
if (isIgnoredByDefault(p) || extraIgnored.includes(p)) continue;
|
|
44
|
+
const d = f.sha256.toLowerCase();
|
|
45
|
+
if (!HEX.test(d)) throw new Error(`not a sha256 hex digest for ${p}: ${f.sha256}`);
|
|
46
|
+
if (seen.has(p)) throw new Error(`duplicate path in the manifest: ${p}`);
|
|
47
|
+
seen.add(p);
|
|
48
|
+
out.push({ path: p, sha256: d });
|
|
49
|
+
}
|
|
50
|
+
return out.sort((a, b) => compareManifestPaths(a.path, b.path));
|
|
51
|
+
}
|
|
52
|
+
function modelRootDigest(files, sha256) {
|
|
53
|
+
const sorted = manifestFiles(files);
|
|
54
|
+
const buf = new Uint8Array(sorted.length * 32);
|
|
55
|
+
sorted.forEach((f, i) => buf.set(hexToBytes(f.sha256), i * 32));
|
|
56
|
+
return sha256(buf);
|
|
57
|
+
}
|
|
58
|
+
function canonicalJson(value) {
|
|
59
|
+
const norm = (v) => {
|
|
60
|
+
if (v === null || typeof v !== "object") {
|
|
61
|
+
if (typeof v === "number" && !Number.isFinite(v)) return null;
|
|
62
|
+
return v;
|
|
63
|
+
}
|
|
64
|
+
if (Array.isArray(v)) return v.map((x) => x === void 0 ? null : norm(x));
|
|
65
|
+
const o = {};
|
|
66
|
+
for (const k of Object.keys(v).sort()) {
|
|
67
|
+
const x = v[k];
|
|
68
|
+
if (x !== void 0) o[k] = norm(x);
|
|
69
|
+
}
|
|
70
|
+
return o;
|
|
71
|
+
};
|
|
72
|
+
return JSON.stringify(norm(value), null, 2) + "\n";
|
|
73
|
+
}
|
|
74
|
+
var round = (x, digits = 3) => typeof x === "number" && Number.isFinite(x) ? Number(x.toFixed(digits)) : void 0;
|
|
75
|
+
var verdictOf = (fs) => (fs ?? []).some((f) => f.severity === "block") ? "block" : (fs ?? []).some((f) => f.severity === "warn") ? "warn" : "pass";
|
|
76
|
+
var cardGb = (name) => {
|
|
77
|
+
const m = /(\d+(?:\.\d+)?)\s*GB/i.exec(String(name ?? ""));
|
|
78
|
+
return m ? Number(m[1]) : Number.POSITIVE_INFINITY;
|
|
79
|
+
};
|
|
80
|
+
function summarizeVerdicts(run) {
|
|
81
|
+
const out = {};
|
|
82
|
+
if (run.params != null) out.params = { derived: run.params };
|
|
83
|
+
const c = run.cost;
|
|
84
|
+
if (c && typeof c === "object") {
|
|
85
|
+
out.training = {
|
|
86
|
+
peakGb: round(c.peakGb),
|
|
87
|
+
upperGb: round(c.peakGbUpper),
|
|
88
|
+
// The conservative pick (upper bound x headroom), then the point estimate's.
|
|
89
|
+
smallestCard: c.smallestSafeGpu ?? null,
|
|
90
|
+
smallestCardAtEstimate: c.smallestFitGpu ?? c.fitsGpu ?? null,
|
|
91
|
+
seqLen: c.seqLen ?? void 0,
|
|
92
|
+
attention: c.attention ?? void 0,
|
|
93
|
+
estCostUsd: round(c.estCostUsd, 2)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const ip = run.inference;
|
|
97
|
+
if (ip && typeof ip === "object") {
|
|
98
|
+
const fits = Array.isArray(ip.fits) ? ip.fits : [];
|
|
99
|
+
const smallest = fits.filter((g) => g.fits).sort((a, b) => cardGb(a.gpu) - cardGb(b.gpu))[0];
|
|
100
|
+
out.inference = {
|
|
101
|
+
peakGb: round(ip.peakGb),
|
|
102
|
+
smallestCard: smallest ? smallest.gpu : null,
|
|
103
|
+
batch: ip.batch ?? void 0,
|
|
104
|
+
promptTokens: ip.promptTokens ?? void 0,
|
|
105
|
+
genTokens: ip.genTokens ?? void 0,
|
|
106
|
+
precision: ip.precision ?? void 0
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
if (run.serve) {
|
|
110
|
+
const r = run.serve.resolved ?? {};
|
|
111
|
+
out.serve = {
|
|
112
|
+
verdict: verdictOf(run.serve.findings),
|
|
113
|
+
engine: run.engine ?? run.serve.engine,
|
|
114
|
+
engineVersion: r.engineVersion ?? null,
|
|
115
|
+
engineVersionAssumed: r.engineVersionAssumed ?? void 0,
|
|
116
|
+
gpu: r.gpu ?? null,
|
|
117
|
+
gpus: r.gpus ?? void 0,
|
|
118
|
+
tp: r.tp ?? void 0,
|
|
119
|
+
pp: r.pp ?? void 0,
|
|
120
|
+
dp: r.dp ?? void 0
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
if (run.layout) {
|
|
124
|
+
const r = run.layout.resolved ?? {};
|
|
125
|
+
const L = run.layoutSpec ?? {};
|
|
126
|
+
out.layout = {
|
|
127
|
+
verdict: verdictOf(run.layout.findings),
|
|
128
|
+
tp: L.tp ?? void 0,
|
|
129
|
+
pp: L.pp ?? void 0,
|
|
130
|
+
dp: L.dp ?? void 0,
|
|
131
|
+
cp: L.cp ?? void 0,
|
|
132
|
+
ep: L.ep ?? void 0,
|
|
133
|
+
gpu: r.gpu ?? null,
|
|
134
|
+
worldSize: r.worldSize ?? void 0
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (run.dataFit) out.dataFit = { verdict: verdictOf(run.dataFit.findings) };
|
|
138
|
+
if (run.change && typeof run.change === "object") out.change = { gate: run.change.gate?.ok ? "approved" : "refused" };
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
function testLists(run, findings) {
|
|
142
|
+
const failed = /* @__PURE__ */ new Set();
|
|
143
|
+
const warned = /* @__PURE__ */ new Set();
|
|
144
|
+
for (const f of findings) {
|
|
145
|
+
const level = f.effective ?? f.severity;
|
|
146
|
+
if (level === "off" || level === "info") continue;
|
|
147
|
+
const gates = f.gates ?? level === "block";
|
|
148
|
+
if (level === "block" && gates) failed.add(f.rule);
|
|
149
|
+
else warned.add(f.rule);
|
|
150
|
+
}
|
|
151
|
+
const passed = /* @__PURE__ */ new Set();
|
|
152
|
+
const slug = (c) => c.trim().toLowerCase().replace(/[^a-z0-9_.:-]+/g, "-");
|
|
153
|
+
const ran = (ns, checked) => {
|
|
154
|
+
if (checked && checked.length) for (const c of checked) passed.add(`${ns}/${slug(c)}`);
|
|
155
|
+
else passed.add(ns);
|
|
156
|
+
};
|
|
157
|
+
if (run.layout) ran("layout", run.layout.checked);
|
|
158
|
+
if (run.serve) ran("serve", run.serve.checked);
|
|
159
|
+
if (run.dataFit) ran("data-fit", run.dataFit.checked);
|
|
160
|
+
if (run.lint) ran("lint", void 0);
|
|
161
|
+
if (run.cost) ran("memory", ["training-peak"]);
|
|
162
|
+
if (run.inference) ran("memory", ["inference-peak"]);
|
|
163
|
+
if (run.change) ran("change", ["gate"]);
|
|
164
|
+
const stem = (r) => r.split("-")[0];
|
|
165
|
+
for (const r of [...failed, ...warned]) {
|
|
166
|
+
for (const p of [...passed]) if (p === r || stem(p) === stem(r) || p === r.split("/")[0]) passed.delete(p);
|
|
167
|
+
}
|
|
168
|
+
for (const r of failed) warned.delete(r);
|
|
169
|
+
const sort = (s) => [...s].sort();
|
|
170
|
+
return { passed: sort(passed), warned: sort(warned), failed: sort(failed) };
|
|
171
|
+
}
|
|
172
|
+
function resultOf(exitCode, lists) {
|
|
173
|
+
if (exitCode !== 0 || lists.failed.length) return "FAILED";
|
|
174
|
+
return lists.warned.length ? "WARNED" : "PASSED";
|
|
175
|
+
}
|
|
176
|
+
function buildStatement(input) {
|
|
177
|
+
const s = input.subject;
|
|
178
|
+
const files = manifestFiles(s.files, s.extraIgnored ?? []);
|
|
179
|
+
if (!files.length) throw new Error("no files to attest: the subject has no digests");
|
|
180
|
+
const root = modelRootDigest(files, input.sha256);
|
|
181
|
+
const lists = testLists(input.run, input.findings);
|
|
182
|
+
const result = resultOf(input.exitCode, lists);
|
|
183
|
+
const ignorePaths = [...MT_IGNORE_PATHS, ...s.extraIgnored ?? []].sort();
|
|
184
|
+
const subject = [
|
|
185
|
+
// model-transparency's subject, byte for byte: the model name and the root digest.
|
|
186
|
+
{ name: s.modelName, digest: { sha256: root } },
|
|
187
|
+
// Then every file, so `gh attestation verify config.json` finds the record by the file's own digest.
|
|
188
|
+
...files.map((f) => ({ name: f.path, digest: { sha256: f.sha256 } }))
|
|
189
|
+
];
|
|
190
|
+
const configuration = [
|
|
191
|
+
{ name: input.tool.name, uri: `pkg:npm/${input.tool.name}@${input.tool.version}` },
|
|
192
|
+
...[...input.tool.files].sort((a, b) => compareManifestPaths(a.path, b.path)).map((f) => ({ name: `${input.tool.name}/${f.path}`, digest: { sha256: f.sha256 } })),
|
|
193
|
+
...[...input.inputs ?? []].sort((a, b) => a.role + a.path < b.role + b.path ? -1 : 1).map((i) => ({ name: i.path, digest: { sha256: i.sha256 }, annotations: { role: i.role } }))
|
|
194
|
+
];
|
|
195
|
+
const findings = [...input.findings].map((f) => ({
|
|
196
|
+
rule: f.rule,
|
|
197
|
+
checker: f.checker,
|
|
198
|
+
severity: f.severity,
|
|
199
|
+
title: f.title,
|
|
200
|
+
effective: f.effective,
|
|
201
|
+
gates: f.gates,
|
|
202
|
+
waived: f.waived || void 0,
|
|
203
|
+
baseline: f.baseline
|
|
204
|
+
})).sort((a, b) => a.rule === b.rule ? a.title < b.title ? -1 : a.title > b.title ? 1 : 0 : a.rule < b.rule ? -1 : 1);
|
|
205
|
+
const ext = {
|
|
206
|
+
schema: ATTESTATION_SCHEMA_ID,
|
|
207
|
+
command: input.run.command,
|
|
208
|
+
model: input.run.model,
|
|
209
|
+
argv: input.argv,
|
|
210
|
+
tool: { name: input.tool.name, version: input.tool.version },
|
|
211
|
+
exitCode: input.exitCode,
|
|
212
|
+
verdicts: summarizeVerdicts(input.run),
|
|
213
|
+
findings,
|
|
214
|
+
subjectSource: {
|
|
215
|
+
kind: s.kind,
|
|
216
|
+
modelName: s.modelName,
|
|
217
|
+
repo: s.repo,
|
|
218
|
+
revision: s.revision,
|
|
219
|
+
// What model-transparency would write as `serialization`, so its
|
|
220
|
+
// manifest can be rebuilt from this record and the root compared.
|
|
221
|
+
serialization: { method: "files", hash_type: "sha256", allow_symlinks: !!s.followedSymlinks, ignore_paths: ignorePaths },
|
|
222
|
+
modelSigningPredicateType: MODEL_SIGNING_PREDICATE_TYPE,
|
|
223
|
+
rootDigest: { sha256: root },
|
|
224
|
+
files: files.length
|
|
225
|
+
},
|
|
226
|
+
time: input.time
|
|
227
|
+
};
|
|
228
|
+
return {
|
|
229
|
+
_type: STATEMENT_TYPE,
|
|
230
|
+
subject,
|
|
231
|
+
predicateType: PREDICATE_TYPE,
|
|
232
|
+
predicate: {
|
|
233
|
+
result,
|
|
234
|
+
configuration,
|
|
235
|
+
url: input.url,
|
|
236
|
+
passedTests: lists.passed,
|
|
237
|
+
warnedTests: lists.warned,
|
|
238
|
+
failedTests: lists.failed,
|
|
239
|
+
[EXTENSION_FIELD]: ext
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
var CYCLONEDX_SPEC_VERSION = "1.6";
|
|
244
|
+
var NEURARCH_PROPERTIES = {
|
|
245
|
+
"neurarch:precheck:result": "PASSED, WARNED or FAILED: the in-toto test-result value of the same run.",
|
|
246
|
+
"neurarch:precheck:command": "Which pre-check ran: check, layout, serve-check or policy-apply.",
|
|
247
|
+
"neurarch:precheck:tool_version": "The neurarch CLI version that produced the values.",
|
|
248
|
+
"neurarch:subject:root_sha256": "model-transparency root digest over the model files (the subject of a model_signing signature).",
|
|
249
|
+
"neurarch:subject:revision": "Hub commit the file digests were read at, when the model came from the Hugging Face Hub.",
|
|
250
|
+
"neurarch:params:derived": "Parameter count derived from config.json alone.",
|
|
251
|
+
"neurarch:training:peak_gb": "Predicted training peak memory in GB for one unsharded copy (derived from the config, not measured).",
|
|
252
|
+
"neurarch:training:peak_upper_gb": "The training peak times the held-out calibration multiplier.",
|
|
253
|
+
"neurarch:training:smallest_card": "Smallest listed card that holds the upper-bound training peak with 1.15x headroom.",
|
|
254
|
+
"neurarch:inference:peak_gb": "Predicted inference peak (weights plus KV cache) in GB.",
|
|
255
|
+
"neurarch:inference:smallest_card": "Smallest listed card that holds the inference peak with headroom.",
|
|
256
|
+
"neurarch:serve:verdict": "pass, warn or block: whether the serving launch is predicted to start and hold what it promises.",
|
|
257
|
+
"neurarch:serve:engine": "vllm, sglang or llamacpp.",
|
|
258
|
+
"neurarch:serve:engine_version": "The engine release whose defaults and tables were applied.",
|
|
259
|
+
"neurarch:layout:verdict": "pass, warn or block: whether the TP / PP / DP split is legal and balanced.",
|
|
260
|
+
"neurarch:layout:tp_pp_dp": "The parallel split checked, as TPxPPxDP."
|
|
261
|
+
};
|
|
262
|
+
function buildCycloneDx(input) {
|
|
263
|
+
const st = input.statement;
|
|
264
|
+
const ext = st.predicate[EXTENSION_FIELD];
|
|
265
|
+
const v = ext.verdicts;
|
|
266
|
+
const props = [
|
|
267
|
+
["neurarch:precheck:result", st.predicate.result],
|
|
268
|
+
["neurarch:precheck:command", ext.command],
|
|
269
|
+
["neurarch:precheck:tool_version", ext.tool.version],
|
|
270
|
+
["neurarch:subject:root_sha256", ext.subjectSource.rootDigest.sha256],
|
|
271
|
+
["neurarch:subject:revision", ext.subjectSource.revision],
|
|
272
|
+
["neurarch:params:derived", v.params?.derived],
|
|
273
|
+
["neurarch:training:peak_gb", v.training?.peakGb],
|
|
274
|
+
["neurarch:training:peak_upper_gb", v.training?.upperGb],
|
|
275
|
+
["neurarch:training:smallest_card", v.training?.smallestCard],
|
|
276
|
+
["neurarch:inference:peak_gb", v.inference?.peakGb],
|
|
277
|
+
["neurarch:inference:smallest_card", v.inference?.smallestCard],
|
|
278
|
+
["neurarch:serve:verdict", v.serve?.verdict],
|
|
279
|
+
["neurarch:serve:engine", v.serve?.engine],
|
|
280
|
+
["neurarch:serve:engine_version", v.serve?.engineVersion],
|
|
281
|
+
["neurarch:layout:verdict", v.layout?.verdict],
|
|
282
|
+
["neurarch:layout:tp_pp_dp", v.layout ? [v.layout.tp ?? 1, v.layout.pp ?? 1, v.layout.dp ?? 1].join("x") : void 0]
|
|
283
|
+
];
|
|
284
|
+
const properties = props.filter(([, value]) => value !== void 0 && value !== null && value !== "").map(([name2, value]) => ({ name: name2, value: String(value) })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
285
|
+
const name = ext.subjectSource.repo ?? ext.subjectSource.modelName;
|
|
286
|
+
const ref = `model:${name}`;
|
|
287
|
+
const component = {
|
|
288
|
+
type: "machine-learning-model",
|
|
289
|
+
"bom-ref": ref,
|
|
290
|
+
name,
|
|
291
|
+
...ext.subjectSource.revision ? { version: ext.subjectSource.revision } : {},
|
|
292
|
+
...input.purl ? { purl: input.purl } : {},
|
|
293
|
+
properties
|
|
294
|
+
};
|
|
295
|
+
const files = st.subject.slice(1).map((s) => ({
|
|
296
|
+
type: "file",
|
|
297
|
+
"bom-ref": `${ref}#${s.name}`,
|
|
298
|
+
name: s.name,
|
|
299
|
+
hashes: [{ alg: "SHA-256", content: s.digest.sha256 }]
|
|
300
|
+
}));
|
|
301
|
+
if (files.length) component.components = files;
|
|
302
|
+
return {
|
|
303
|
+
bomFormat: "CycloneDX",
|
|
304
|
+
specVersion: CYCLONEDX_SPEC_VERSION,
|
|
305
|
+
version: 1,
|
|
306
|
+
metadata: {
|
|
307
|
+
...input.time ? { timestamp: input.time } : {},
|
|
308
|
+
tools: { components: [{ type: "application", name: ext.tool.name, version: ext.tool.version }] }
|
|
309
|
+
},
|
|
310
|
+
components: [component]
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function huggingfacePurl(repo, revision) {
|
|
314
|
+
const [ns, ...rest] = repo.split("/");
|
|
315
|
+
const enc = (x) => encodeURIComponent(x);
|
|
316
|
+
const path = rest.length ? `${enc(ns)}/${rest.map(enc).join("/")}` : enc(ns);
|
|
317
|
+
return `pkg:huggingface/${path}${revision ? `@${enc(revision)}` : ""}`;
|
|
318
|
+
}
|
|
319
|
+
function checksumsFor(st) {
|
|
320
|
+
return st.subject.map((s) => `${s.digest.sha256} ${s.name}`).join("\n") + "\n";
|
|
321
|
+
}
|
|
322
|
+
export {
|
|
323
|
+
ATTESTATION_SCHEMA_ID,
|
|
324
|
+
CYCLONEDX_SPEC_VERSION,
|
|
325
|
+
EXTENSION_FIELD,
|
|
326
|
+
MODEL_SIGNING_PREDICATE_TYPE,
|
|
327
|
+
MT_IGNORE_PATHS,
|
|
328
|
+
NEURARCH_PROPERTIES,
|
|
329
|
+
PREDICATE_TYPE,
|
|
330
|
+
STATEMENT_TYPE,
|
|
331
|
+
buildCycloneDx,
|
|
332
|
+
buildStatement,
|
|
333
|
+
canonicalJson,
|
|
334
|
+
checksumsFor,
|
|
335
|
+
compareManifestPaths,
|
|
336
|
+
huggingfacePurl,
|
|
337
|
+
isIgnoredByDefault,
|
|
338
|
+
manifestFiles,
|
|
339
|
+
modelRootDigest,
|
|
340
|
+
resultOf,
|
|
341
|
+
summarizeVerdicts,
|
|
342
|
+
testLists
|
|
343
|
+
};
|
package/bin/attest.mjs
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `--attest <out.json>` and `--cyclonedx <out.json>` on every pre-check: the
|
|
3
|
+
* run as a record someone else can verify. This file is the CLI's glue
|
|
4
|
+
* (files, hashing, the Hub); what goes in the record is decided in
|
|
5
|
+
* src/utils/attestation/ through attest.bundle.mjs.
|
|
6
|
+
*
|
|
7
|
+
* neurarch layout <id> ... --attest precheck.intoto.json [--cyclonedx precheck.cdx.json]
|
|
8
|
+
* [--model-dir ./checkpoint] [--attest-url <ci run url>] [--attest-time 2026-10-18T00:00:00Z]
|
|
9
|
+
*
|
|
10
|
+
* The subjects are the model's files, named and hashed the way OpenSSF
|
|
11
|
+
* model-transparency names and hashes them: `--model-dir` hashes a local
|
|
12
|
+
* copy; otherwise a Hub id is read at the commit `main` points to (LFS files
|
|
13
|
+
* by their recorded sha256, the rest downloaded and hashed); otherwise a graph
|
|
14
|
+
* file is its own subject. Nothing here reads the clock: a time appears only
|
|
15
|
+
* when `--attest-time` gives one, so two runs over the same inputs write the
|
|
16
|
+
* same bytes.
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
import { createReadStream, readFileSync, writeFileSync, readdirSync, lstatSync, statSync, existsSync } from 'node:fs';
|
|
20
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
|
|
23
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
const PKG = join(HERE, '..');
|
|
25
|
+
const VALUED = ['--attest', '--cyclonedx', '--attest-time', '--attest-url', '--model-dir'];
|
|
26
|
+
/** The files whose code and tables decide a verdict; their digests go in the record. */
|
|
27
|
+
const TOOL_FILES = ['bin/neurarch.mjs', 'bin/policy.mjs', 'bin/attest.mjs', 'engine.bundle.mjs', 'policy.bundle.mjs', 'attest.bundle.mjs'];
|
|
28
|
+
const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
|
|
29
|
+
|
|
30
|
+
let bundle;
|
|
31
|
+
const lib = async () => (bundle ??= await import('../attest.bundle.mjs'));
|
|
32
|
+
const posix = (p) => p.split(sep).join('/');
|
|
33
|
+
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
34
|
+
const toolVersion = () => { try { return JSON.parse(readFileSync(join(PKG, 'package.json'), 'utf8')).version; } catch { return '0.0.0'; } };
|
|
35
|
+
const say = (s) => process.stderr.write((process.stderr.isTTY && !process.env.NO_COLOR ? `\x1b[2m${s}\x1b[0m` : s) + '\n');
|
|
36
|
+
const fail = (s) => { process.stderr.write(`neurarch: ${s}\n`); process.exit(2); };
|
|
37
|
+
|
|
38
|
+
/** Pull the record flags out of argv (in place). Exits 2 on a flag that cannot be used. */
|
|
39
|
+
export function setup(args) {
|
|
40
|
+
const o = {};
|
|
41
|
+
for (let i = 0; i < args.length; i++) {
|
|
42
|
+
const a = args[i];
|
|
43
|
+
if (a === '--') break; // serve-check: everything after is the launch command
|
|
44
|
+
const eq = /^(--[a-z-]+)=(.*)$/.exec(a);
|
|
45
|
+
if (eq && VALUED.includes(eq[1])) { o[eq[1].slice(2)] = eq[2]; args.splice(i--, 1); continue; }
|
|
46
|
+
if (VALUED.includes(a)) {
|
|
47
|
+
if (args[i + 1] == null || args[i + 1] === '--') fail(`${a} needs a value`);
|
|
48
|
+
o[a.slice(2)] = args[i + 1]; args.splice(i--, 2);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
o.active = !!(o.attest || o.cyclonedx);
|
|
52
|
+
if (!o.active && (o['model-dir'] || o['attest-time'] || o['attest-url'])) fail('--model-dir, --attest-time and --attest-url only apply with --attest or --cyclonedx');
|
|
53
|
+
if (o['attest-time'] && !RFC3339.test(o['attest-time'])) fail(`--attest-time ${o['attest-time']}: give an RFC 3339 time, e.g. 2026-10-18T00:00:00Z`);
|
|
54
|
+
if (o['model-dir'] && !(existsSync(o['model-dir']) && statSync(o['model-dir']).isDirectory())) fail(`--model-dir ${o['model-dir']}: not a directory`);
|
|
55
|
+
if (o.active && args[0] && ['oom', 'rightsize'].includes(args[0])) fail(`--attest and --cyclonedx are for check, layout, serve-check and policy apply; ${args[0]} has no model verdict to record`);
|
|
56
|
+
return o;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function hashFile(p) {
|
|
60
|
+
const h = createHash('sha256');
|
|
61
|
+
await new Promise((res, rej) => createReadStream(p).on('data', (d) => h.update(d)).on('end', res).on('error', rej));
|
|
62
|
+
return h.digest('hex');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Every file under `root`, as model-transparency walks it: posix paths relative to the root. */
|
|
66
|
+
async function directorySubject(root, outputs, isIgnored) {
|
|
67
|
+
const abs = resolve(root);
|
|
68
|
+
const files = [];
|
|
69
|
+
let followed = false;
|
|
70
|
+
const walk = async (dir) => {
|
|
71
|
+
for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
72
|
+
const full = join(dir, e.name);
|
|
73
|
+
const rel = posix(relative(abs, full));
|
|
74
|
+
if (isIgnored(rel)) continue;
|
|
75
|
+
let st = lstatSync(full);
|
|
76
|
+
if (st.isSymbolicLink()) { followed = true; st = statSync(full); }
|
|
77
|
+
if (st.isDirectory()) await walk(full);
|
|
78
|
+
else if (st.isFile()) files.push({ path: rel, sha256: await hashFile(full) });
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
await walk(abs);
|
|
82
|
+
const extraIgnored = outputs.map((p) => posix(relative(abs, resolve(p)))).filter((r) => !r.startsWith('..') && files.some((f) => f.path === r));
|
|
83
|
+
return { kind: 'directory', modelName: basename(abs), followedSymlinks: followed || undefined, extraIgnored: extraIgnored.length ? extraIgnored.sort() : undefined, files: files.filter((f) => !extraIgnored.includes(f.path)) };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A Hub repo at the commit `main` points to. LFS files by their recorded sha256; the rest downloaded. */
|
|
87
|
+
async function hubSubject(repo, isIgnored) {
|
|
88
|
+
const token = process.env.HF_TOKEN?.trim();
|
|
89
|
+
const headers = token ? { Authorization: `Bearer ${token}` } : {};
|
|
90
|
+
const get = async (url) => {
|
|
91
|
+
const r = await fetch(url, { headers, signal: AbortSignal.timeout(30_000) });
|
|
92
|
+
if (!r.ok) throw new Error(`${url} answered ${r.status}${r.status === 401 || r.status === 403 ? ' (set HF_TOKEN for a gated repo)' : ''}`);
|
|
93
|
+
return r;
|
|
94
|
+
};
|
|
95
|
+
const enc = (p) => p.split('/').map(encodeURIComponent).join('/');
|
|
96
|
+
const rev = (await (await get(`https://huggingface.co/api/models/${enc(repo)}/revision/main`)).json()).sha;
|
|
97
|
+
if (!/^[0-9a-f]{40}$/.test(rev ?? '')) throw new Error(`no commit for ${repo}`);
|
|
98
|
+
const entries = [];
|
|
99
|
+
for (let url = `https://huggingface.co/api/models/${enc(repo)}/tree/${rev}?recursive=true`; url;) {
|
|
100
|
+
const r = await get(url);
|
|
101
|
+
entries.push(...(await r.json()));
|
|
102
|
+
url = /<([^>]+)>;\s*rel="next"/.exec(r.headers.get('link') ?? '')?.[1] ?? null;
|
|
103
|
+
}
|
|
104
|
+
const want = entries.filter((e) => e.type === 'file' && !isIgnored(e.path));
|
|
105
|
+
const files = [];
|
|
106
|
+
const queue = [...want];
|
|
107
|
+
const worker = async () => {
|
|
108
|
+
for (let e = queue.shift(); e; e = queue.shift()) {
|
|
109
|
+
if (e.lfs?.oid && /^[0-9a-f]{64}$/.test(e.lfs.oid)) { files.push({ path: e.path, sha256: e.lfs.oid }); continue; }
|
|
110
|
+
const body = new Uint8Array(await (await get(`https://huggingface.co/${enc(repo)}/resolve/${rev}/${enc(e.path)}`)).arrayBuffer());
|
|
111
|
+
files.push({ path: e.path, sha256: sha256(body) });
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
await Promise.all([worker(), worker(), worker(), worker()]);
|
|
115
|
+
return { kind: 'hub', modelName: repo.split('/').pop(), repo, revision: rev, files };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function resolveSubject(att, model, A) {
|
|
119
|
+
const outputs = [att.attest, att.cyclonedx].filter(Boolean);
|
|
120
|
+
if (att['model-dir']) return directorySubject(att['model-dir'], outputs, A.isIgnoredByDefault);
|
|
121
|
+
if (model && existsSync(model) && statSync(model).isFile()) {
|
|
122
|
+
return { kind: 'file', modelName: basename(model), files: [{ path: basename(model), sha256: await hashFile(model) }] };
|
|
123
|
+
}
|
|
124
|
+
if (model && /^[\w.-]+\/[\w.-]+$/.test(model)) return hubSubject(model, A.isIgnoredByDefault);
|
|
125
|
+
throw new Error(`cannot name the subject of ${model ?? 'this run'}: give --model-dir <dir> with the model's files`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Judged findings when a policy ran (waivers and overrides applied), the checkers' own otherwise. */
|
|
129
|
+
async function findingsOf(pol, run, code) {
|
|
130
|
+
if (pol?.judged) {
|
|
131
|
+
return pol.judged.map((j) => ({ checker: j.checker, rule: j.rule, severity: j.severity, title: j.title, effective: j.effective, gates: j.gates, waived: !!j.waiver, baseline: j.baseline }));
|
|
132
|
+
}
|
|
133
|
+
// No policy ran: the checker's own exit code is the verdict. A finding the
|
|
134
|
+
// policy layer would raise (a peak over the --gpu card) did not stop this
|
|
135
|
+
// run, so it is recorded with its severity and `gates: false`, not as a
|
|
136
|
+
// failure the exit code never reported.
|
|
137
|
+
const { collect } = await import('./policy.mjs');
|
|
138
|
+
return (await collect(run, pol ?? {})).findings.map((f) => ({ checker: f.checker, rule: f.rule, severity: f.severity, title: f.title, gates: code !== 0 && f.severity === 'block' }));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Write the record(s). Returns the exit code to use: the checker's, or 2 when a record was asked for and could not be written. */
|
|
142
|
+
async function write(att, pol, run, code, findings) {
|
|
143
|
+
const A = await lib();
|
|
144
|
+
const subject = await resolveSubject(att, run.model, A);
|
|
145
|
+
const tool = { name: 'neurarch', version: toolVersion(), files: TOOL_FILES.filter((f) => existsSync(join(PKG, f))).map((f) => ({ path: f, sha256: sha256(readFileSync(join(PKG, f))) })) };
|
|
146
|
+
const root = pol?.root ?? process.cwd();
|
|
147
|
+
const inputs = [];
|
|
148
|
+
if (pol?.policyPath && existsSync(pol.policyPath)) inputs.push({ role: 'policy', path: posix(relative(root, pol.policyPath)), sha256: sha256(readFileSync(pol.policyPath)) });
|
|
149
|
+
if (pol?.sourceAbs && existsSync(pol.sourceAbs)) inputs.push({ role: 'source', path: posix(relative(root, pol.sourceAbs)), sha256: sha256(readFileSync(pol.sourceAbs)) });
|
|
150
|
+
const statement = A.buildStatement({
|
|
151
|
+
run, exitCode: code, findings, subject, tool, argv: att.argv ?? [], inputs,
|
|
152
|
+
time: att['attest-time'], url: att['attest-url'], sha256,
|
|
153
|
+
});
|
|
154
|
+
const root8 = statement.predicate[A.EXTENSION_FIELD].subjectSource.rootDigest.sha256.slice(0, 12);
|
|
155
|
+
if (att.attest) {
|
|
156
|
+
writeFileSync(att.attest, A.canonicalJson(statement));
|
|
157
|
+
say(` attest ${att.attest} (in-toto ${statement.predicate.result}, ${statement.subject.length} subjects, model root sha256:${root8})`);
|
|
158
|
+
}
|
|
159
|
+
if (att.cyclonedx) {
|
|
160
|
+
const bom = A.buildCycloneDx({ statement, purl: subject.kind === 'hub' ? A.huggingfacePurl(subject.repo, subject.revision) : undefined, time: att['attest-time'] });
|
|
161
|
+
writeFileSync(att.cyclonedx, A.canonicalJson(bom));
|
|
162
|
+
say(` cyclonedx ${att.cyclonedx} (CycloneDX ${A.CYCLONEDX_SPEC_VERSION}, machine-learning-model ${subject.repo ?? subject.modelName})`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Called by the CLI where it would exit, after the policy layer. */
|
|
167
|
+
export async function finish(att, pol, run, code) {
|
|
168
|
+
if (!att?.active) return code;
|
|
169
|
+
try {
|
|
170
|
+
await write(att, pol, run, code, await findingsOf(pol, run, code));
|
|
171
|
+
return code;
|
|
172
|
+
} catch (e) {
|
|
173
|
+
process.stderr.write(`neurarch: no record written: ${e.message}\n`);
|
|
174
|
+
return code === 0 ? 2 : code;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** `neurarch policy apply --attest out.json`: the judged findings from another tool, recorded. */
|
|
179
|
+
export async function finishPolicyApply(att, pol, input, ev) {
|
|
180
|
+
if (!att?.active) return;
|
|
181
|
+
if (!ev) { process.stderr.write('neurarch: no record written: policy apply found no .neurarch.yml, so nothing was judged\n'); return 2; }
|
|
182
|
+
const run = { command: 'policy-apply', model: input.model };
|
|
183
|
+
const findings = ev.judged.map((j) => ({ checker: j.checker, rule: j.rule, severity: j.severity, title: j.title, effective: j.effective, gates: j.gates, waived: !!j.waiver, baseline: j.baseline }));
|
|
184
|
+
try { await write(att, pol, run, ev.exitCode, findings); } catch (e) {
|
|
185
|
+
process.stderr.write(`neurarch: no record written: ${e.message}\n`);
|
|
186
|
+
return 2;
|
|
187
|
+
}
|
|
188
|
+
}
|