Aere Proof of Software 1.4.0: an attestation of what was built, from what, by whom and when, verifiable without trusting Aere Network

Every artifact's SHA-256 and size, the SBOM's digest, the git commit and tree of the source, a hybrid signature (classical + ML-DSA,
both required) and, when notarized, a first-seen time on Aere Network covered by the validators' post-quantum certificate. verify
recomputes everything from the files; --rebuild-from repeats an npm pack build from a clone the verifier chose; the SBOM is
re-derived from the committed package-lock.json or, new in 1.4.0, from the committed go.mod and go.sum; --signer requires the
signing keys you expect (1.4.0); a developer credential binds the keys to a person, judged against a trust root you choose. The
builder's declared date can only accuse, never acquit (1.4.0). Includes the GitHub Action and the hybrid signature library it uses.

Laid out as in the development repository (tools/proof-of-software/, sdk-pq-sign/, sdk/) so that nothing is rewritten for
publication. Tests and negative controls measured on 2026-09-29 are listed in README.md.
This commit is contained in:
Aere Network committed 2026-09-29 22:46:57 +03:00
commit 065f84e34a
35 files changed
+3511

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
// Mecanismul comun al controalelor negative ale Proof of Software 1.3.0: o COPIE (pos.mjs + suita + sdk-pq-sign + sdk, intr-un dosar
// temporar; depozitul nu se atinge), un paznic scos in pos.mjs-ul copiei, suita rulata pe copie. Martorul (copia neatinsa) trebuie
// verde; fiecare plantare trebuie sa inroseasca EXACT proba numita, cu suita chiar rulata (rezumatul ei exista). O ancora care nu
// apare exact o data e un esec al controlului (STRICAT), nu o linie informativa.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const RAD = path.resolve(AICI, '..', '..', '..');
export function controleaza(suita, plantari) {
function copie() {
const t = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-cn-'));
for (const d of ['sdk-pq-sign', 'sdk']) fs.cpSync(path.join(RAD, d), path.join(t, d), { recursive: true });
fs.mkdirSync(path.join(t, 'tools', 'proof-of-software', 'test'), { recursive: true });
fs.copyFileSync(path.join(RAD, 'tools', 'proof-of-software', 'pos.mjs'), path.join(t, 'tools', 'proof-of-software', 'pos.mjs'));
fs.copyFileSync(path.join(AICI, suita), path.join(t, 'tools', 'proof-of-software', 'test', suita));
// 1.4.0: fixturile suitelor (dosarele fixturi-*, de ex. go.mod/go.sum reale) merg si ele in copie
for (const d of fs.readdirSync(AICI).filter((n) => n.startsWith('fixturi') && fs.statSync(path.join(AICI, n)).isDirectory())) {
fs.cpSync(path.join(AICI, d), path.join(t, 'tools', 'proof-of-software', 'test', d), { recursive: true });
}
return t;
}
function ruleaza(t) {
const r = spawnSync(process.execPath, [path.join(t, 'tools', 'proof-of-software', 'test', suita)], { encoding: 'utf8', timeout: 400000 });
const out = (r.stdout || '') + (r.stderr || '');
return { cod: r.status, rulat: /\d+ treceri, \d+ esecuri/.test(out), picate: out.split('\n').filter((l) => l.startsWith(' ESEC')) };
}
let rele = 0;
const t0 = copie(); const m = ruleaza(t0); fs.rmSync(t0, { recursive: true, force: true });
if (m.cod === 0 && m.rulat && !m.picate.length) console.log(' OK martorul: copia neatinsa verde'); else { rele++; console.log(` STRICAT martorul nu e verde (cod ${m.cod}, ${m.picate.length} esecuri)`); }
for (const [nume, din, inl, tinta] of plantari) {
const t = copie(); const f = path.join(t, 'tools', 'proof-of-software', 'pos.mjs'); const src = fs.readFileSync(f, 'utf8');
if (src.split(din).length !== 2) { rele++; console.log(` STRICAT ${nume}: ancora apare de ${src.split(din).length - 1} ori`); fs.rmSync(t, { recursive: true, force: true }); continue; }
fs.writeFileSync(f, src.replace(din, inl));
const r = ruleaza(t); fs.rmSync(t, { recursive: true, force: true });
if (!r.rulat) { rele++; console.log(` STRICAT ${nume}: suita nu a ajuns la rezumat (cod ${r.cod})`); continue; }
if (r.picate.some((l) => l.includes(tinta))) console.log(` ROSU cum trebuia ${nume} (proba '${tinta}' pica)`);
else { rele++; console.log(` CONTROL CAZUT ${nume}: proba '${tinta}' a ramas verde (${r.picate.length} esecuri altundeva)`); }
}
console.log(rele ? `CONTROL NEGATIV: ${rele} probleme` : `DOVEDIT: martorul verde, ${plantari.length} din ${plantari.length} paznici scosi -> proba lor rosie`);
return rele ? 1 : 0;
}
@@ -0,0 +1,94 @@
// Dovada ca CONTROALELE NEGATIVE ale actiunii pot iesi rosii din motivul lor: pe o COPIE a actiunii (setul minim de fisiere +
// dependintele fixate, intr-un dosar temporar; depozitul nu se atinge) se scoate cate un paznic cu o conditie falsa la RULARE
// (compileaza, deci un rosu nu poate veni de la sintaxa), se ruleaza test/action.test.mjs pe copie si se cere ca EXACT probele
// paznicului scos sa iasa ESEC, iar toate celelalte OK.
// Trei grupe, fiindca paznicii interactioneaza: fara judecarea notarizarii (grupa B), ecoul cheii din raspunsul 403 nu mai
// ajunge sa fie tiparit, si proba (d) ar ramane verde din alt motiv decat cel masurat; de aceea redactarea (grupa C) se scoate
// singura, cu notarizarea intacta.
// Verdict cu trei valori: VERDE (fiecare paznic scos si-a inrosit proba, restul verde), ROSU (un paznic scos si proba lui a
// ramas verde, sau a picat alta), STRICAT (o ancora de plantare nu s-a gasit exact o data, copia nu compileaza, suita nu a
// rulat pe copie). Un STRICAT e un esec al dovezii, nu o linie informativa.
// node aerenew/tools/proof-of-software/test/action-dovada.mjs
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const RADACINA = path.resolve(AICI, '..', '..', '..');
const SUITA = path.join(AICI, 'action.test.mjs');
const FALS = "process.env.AERE_POS_NICIODATA === '1'";
const GRUPE = {
A: {
plantari: [
['garda fisierelor necomise', ' if (st.out.trim()) {', ` if (st.out.trim() && ${FALS}) {`],
['refuzul verificarii', ' if (!r.valid) throw new Refuz(', ` if (!r.valid && ${FALS}) throw new Refuz(`],
['verificarea atestarii recitite', 'if (!r2.valid || inapoi.statementHash', `if ((!r2.valid && ${FALS}) || inapoi.statementHash`],
['refuzul reconstructiei', " if (picate.some((c) => /^(rebuild|source)/.test(c.name))) throw", ` if (picate.some((c) => /^(rebuild|source)/.test(c.name)) && ${FALS}) throw`],
],
rosii: ['CONTROL NEGATIV (a):', 'CONTROL NEGATIV (a, varianta)', 'CONTROL NEGATIV (c):', 'CONTROL NEGATIV (c, varianta)'],
},
// redactarea, singura: (d) o cere, si (b) o cere si ea (mesajul lui 403 trebuie sa arate cheia ecou ca ***)
C: {
plantari: [
['redactarea secretelor', 'curata(text) { let t = String(text); for (const r of this.re)', `curata(text) { let t = String(text); for (const r of (${FALS} ? this.re : []))`],
],
rosii: ['CONTROL NEGATIV (b):', 'CONTROL NEGATIV (d):'],
},
B: {
plantari: [
['clientul care judeca raspunsul (inlocuit cu un fetch brut)', 'try { d = await new AereCloud({ apiKey: apiBrut, baseUrl: apiBase, fetch: f }).notarize(att.statementHash); } catch (e) {',
"try { d = await (await f(apiBase + '/notarize', { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': apiBrut }, body: JSON.stringify({ hash: att.statementHash }) })).json(); } catch (e) {"],
['judecarea codului HTTP', ' if (cod !== 200) throw new Refuz(', ` if (cod !== 200 && ${FALS}) throw new Refuz(`],
['judecarea chitantei', "|| d.block <= 0) throw new Refuz('notarization answered 200", `|| d.block <= 0) if (${FALS}) throw new Refuz('notarization answered 200`],
],
rosii: ['CONTROL NEGATIV (b):', 'CONTROL NEGATIV (b, varianta): 200 fara txHash'],
},
};
function copie() {
const L = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-dovada-'));
for (const f of ['tools/proof-of-software/pos.mjs', 'tools/proof-of-software/action/index.mjs', 'tools/proof-of-software/action/action.yml', 'sdk/index.mjs', 'sdk/package.json', 'sdk-pq-sign/index.mjs', 'sdk-pq-sign/package.json', 'sdk-pq-sign/package-lock.json']) {
fs.mkdirSync(path.dirname(path.join(L, f)), { recursive: true }); fs.copyFileSync(path.join(RADACINA, f), path.join(L, f));
}
fs.cpSync(path.join(RADACINA, 'sdk-pq-sign', 'node_modules'), path.join(L, 'sdk-pq-sign', 'node_modules'), { recursive: true });
return L;
}
let verdict = 'VERDE';
const slab = (v) => { if (v === 'STRICAT' || verdict === 'STRICAT') verdict = 'STRICAT'; else verdict = 'ROSU'; };
for (const [nume, g] of Object.entries(GRUPE)) {
console.log(`=== grupa ${nume}: ${g.plantari.map((p) => p[0]).join('; ')}`);
const L = copie(); const act = path.join(L, 'tools', 'proof-of-software', 'action', 'index.mjs');
let src = fs.readFileSync(act, 'utf8'); let bun = true;
for (const [ce, ancora, inlocuire] of g.plantari) {
const n = src.split(ancora).length - 1;
if (n !== 1) { console.log(` STRICAT: ancora pentru "${ce}" apare de ${n} ori (se cere exact o data)`); bun = false; continue; }
src = src.replace(ancora, inlocuire);
}
if (!bun) { slab('STRICAT'); continue; }
fs.writeFileSync(act, src);
const chk = spawnSync(process.execPath, ['--check', act], { encoding: 'utf8' });
if (chk.status !== 0) { console.log(' STRICAT: copia cu paznicii scosi nu compileaza: ' + (chk.stderr || '').split('\n').slice(0, 3).join(' | ')); slab('STRICAT'); continue; }
const env = { ...process.env, AERE_POS_ACTIUNE_PROBA: act }; delete env.AERE_POS_NICIODATA;
const r = spawnSync(process.execPath, [SUITA], { encoding: 'utf8', env, maxBuffer: 1 << 26, timeout: 900000 });
const out = r.stdout || '';
if (!out.includes('actiunea: ' + act)) { console.log(' STRICAT: suita nu a rulat pe copie (nu numeste actiunea copiata)'); slab('STRICAT'); continue; }
const ok = [...out.matchAll(/^ {2}OK {3}(.+)$/gm)].map((m) => m[1]);
// randul intreg (numele probelor contin si ele ': ', deci numele nu se poate taia la primul)
const esec = [...out.matchAll(/^ {2}ESEC (.+)$/gm)].map((m) => m[1]);
if (!/^\d+ treceri, \d+ esecuri$/m.test(out) || ok.length + esec.length < 20) { console.log(` STRICAT: suita nu a terminat (${ok.length} OK, ${esec.length} ESEC citite)`); slab('STRICAT'); continue; }
const eRosie = (t) => g.rosii.some((p) => t.startsWith(p));
const rosiiLipsa = g.rosii.filter((p) => !esec.some((t) => t.startsWith(p)));
const rosiiStraine = esec.filter((t) => !eRosie(t));
for (const p of g.rosii) console.log(` ${esec.some((t) => t.startsWith(p)) ? 'ROSIE, cum trebuia' : 'VERDE, deci paznicul scos NU e vazut de proba'}: ${p}`);
for (const m of [...out.matchAll(/^ {2}ESEC (.+)$/gm)].map((x) => x[1])) if (eRosie(m)) console.log(` ${m.slice(0, 40)} ... ${m.slice(-180)}`);
if (rosiiStraine.length) console.log(' au picat si probe care nu tin de paznicii scosi: ' + rosiiStraine.map((x) => x.slice(0, 160)).join(' | '));
if (rosiiLipsa.length || rosiiStraine.length) slab('ROSU');
console.log(` grupa ${nume}: ${ok.length} OK, ${esec.length} ESEC (asteptate ${g.rosii.length})`);
try { fs.rmSync(L, { recursive: true, force: true, maxRetries: 3 }); } catch { console.log(' (copia temporara nu s-a putut sterge: ' + L + ')'); }
}
console.log(`\nDOVADA CONTROALELOR NEGATIVE: ${verdict}`);
process.exitCode = verdict === 'VERDE' ? 0 : verdict === 'ROSU' ? 1 : 2;
@@ -0,0 +1,442 @@
// Probele actiunii GitHub Proof of Software, rulata LOCAL ca de un runner: intrarile in INPUT_* (cu liniuta, ca la runner),
// GITHUB_OUTPUT si GITHUB_STEP_SUMMARY in fisiere temporare, GITHUB_WORKSPACE pe un depozit git de proba cu un pachet npm
// mic, comis. Notarizarea merge la un server HTTP LOCAL (node:http pe 127.0.0.1), injectat prin AERE_POS_API_BASE; nicio
// cerere nu pleaca spre cloud.aere.network. Fiecare control negativ cere MOTIVUL numit (mesajul), nu doar un cod nenul.
// node aerenew/tools/proof-of-software/test/action.test.mjs
import assert from 'node:assert';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { spawn, execFileSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import * as pq from '../../../sdk-pq-sign/index.mjs';
import { INTRARI, IESIRI, linieIesire, Secrete, taieHex } from '../action/index.mjs';
import { packNpmFromTree, verify } from '../pos.mjs';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const DIR_POS = path.resolve(AICI, '..');
// AERE_POS_ACTIUNE_PROBA: numai pentru test/action-dovada.mjs, care ruleaza aceasta suita pe o COPIE a actiunii cu un paznic
// scos, ca sa arate ca proba lui iese rosie
const ACTIUNE = process.env.AERE_POS_ACTIUNE_PROBA || path.join(DIR_POS, 'action', 'index.mjs');
const POS = path.join(DIR_POS, 'pos.mjs');
const RADACINA = path.resolve(DIR_POS, '..', '..');
let treceri = 0; const esecuri = []; const nemasurate = [];
class Nemasurat extends Error {}
async function test(nume, fn) {
try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) {
if (e instanceof Nemasurat) { nemasurate.push(nume); console.log(' NEMASURAT ' + nume + ': ' + e.message); return; }
esecuri.push(nume); console.log(' ESEC ' + nume + ': ' + String(e.message || e).slice(0, 900));
}
}
// fiecare dosar temporar se tine minte si se sterge la capat (AERE_POS_PASTREAZA=1 le lasa, pentru depanare)
const facute = [];
const tmp = (p) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), p)); facute.push(d); return d; };
const sha256 = (p) => '0x' + crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
const gitIn = (cwd, args) => execFileSync('git', ['-c', 'user.name=proba', '-c', '[email protected]', ...args], { cwd, stdio: 'pipe' }).toString().trim();
// ---------------------------------------------------------------- depozitul de proba
function depozitDeProba() {
const G = tmp('aere-pos-act-git-');
gitIn(G, ['init', '-q']); gitIn(G, ['config', 'core.autocrlf', 'false']);
fs.mkdirSync(path.join(G, 'pkg', 'lib'), { recursive: true }); fs.mkdirSync(path.join(G, 'altceva'));
fs.writeFileSync(path.join(G, 'pkg', 'package.json'), JSON.stringify({ name: 'proba-actiune', version: '1.2.3', main: 'lib/index.js', files: ['lib', 'LICENSE', 'README.md'] }, null, 1) + '\n');
fs.writeFileSync(path.join(G, 'pkg', 'lib', 'index.js'), 'module.exports = 1;\n');
fs.writeFileSync(path.join(G, 'pkg', 'LICENSE'), 'line one\nline two\n');
fs.writeFileSync(path.join(G, 'pkg', 'README.md'), '# proba\n\nun pachet de proba\n');
fs.writeFileSync(path.join(G, 'altceva', 'x.txt'), 'nu face parte din pachet\n');
gitIn(G, ['add', '-A']); gitIn(G, ['commit', '-q', '-m', 'pachet de proba']);
return G;
}
// ---------------------------------------------------------------- serverul de notarizare, LOCAL
const TX = '0x' + 'ab'.repeat(32);
let modServer = '200'; const cereri = [];
const server = http.createServer((req, res) => {
let b = ''; req.on('data', (c) => { b += c; });
req.on('end', () => {
cereri.push({ m: req.method, u: req.url, k: req.headers['x-api-key'], b });
const trimite = (cod, o) => { res.writeHead(cod, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
if (req.url === '/v1/leak') return trimite(200, { txHash: '0x' + 'ee'.repeat(32), block: 1 });
if (req.method !== 'POST' || req.url !== '/v1/notarize') return trimite(404, { error: 'not_found' });
let h = null; try { h = JSON.parse(b).hash; } catch { /* corp stricat */ }
if (modServer === '200') return trimite(200, { hash: h, txHash: TX, block: 4242, firstSeenAt: 1790000000, firstTime: true, contract: '0x' + '11'.repeat(20), chainId: 2800 });
if (modServer === '403') return trimite(403, { error: 'invalid api key ' + req.headers['x-api-key'] }); // ecoul cheii: redactarea trebuie sa il taie
if (modServer === '200-fara-tx') return trimite(200, { hash: h });
if (modServer === '302') { res.writeHead(302, { location: `http://127.0.0.1:${server.address().port}/v1/leak` }); return res.end(); }
return trimite(500, { error: 'mod necunoscut' });
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const BAZA = `http://127.0.0.1:${server.address().port}/v1`;
// ---------------------------------------------------------------- rularea actiunii ca un runner
function parseaza(t) {
const o = {}; const L = t.split('\n');
for (let i = 0; i < L.length; i++) {
const l = L[i]; if (!l) continue;
const m = /^([^=<]+)<<(.+)$/.exec(l);
if (m) { const v = []; i++; while (i < L.length && L[i] !== m[2]) v.push(L[i++]); assert.ok(!(m[1] in o), 'output written twice: ' + m[1]); o[m[1]] = v.join('\n'); continue; }
const k = l.indexOf('='); assert.ok(k > 0, 'malformed output line: ' + l); assert.ok(!(l.slice(0, k) in o), 'output written twice'); o[l.slice(0, k)] = l.slice(k + 1);
}
return o;
}
function mediuCurat() { const e = {}; for (const [k, v] of Object.entries(process.env)) if (!/^(INPUT_|GITHUB_|RUNNER_|AERE_POS_)/i.test(k)) e[k] = v; return e; }
const toateRularile = [];
async function ruleaza(eticheta, { workspace, inputs = {}, env = {}, actiune = ACTIUNE, faraImplicite = false, secrete = false }) {
const T = tmp('aere-pos-act-run-');
const OUTF = path.join(T, 'github_output'), SUMF = path.join(T, 'step_summary');
fs.writeFileSync(OUTF, ''); fs.writeFileSync(SUMF, '');
// runner-ul pune in INPUT_* implicitele din action.yml; faraImplicite lasa actiunea sa le puna singura
const inp = faraImplicite ? { ...inputs } : { build: 'npm-pack', 'verify-rebuild': 'true', ...inputs };
const e = { ...mediuCurat(), GITHUB_WORKSPACE: workspace, GITHUB_OUTPUT: OUTF, GITHUB_STEP_SUMMARY: SUMF, RUNNER_TEMP: T, ...env };
for (const [k, v] of Object.entries(inp)) e['INPUT_' + k.toUpperCase()] = v;
cereri.length = 0;
const rez = await new Promise((res, rej) => {
const c = spawn(process.execPath, [actiune], { cwd: workspace, env: e, stdio: ['ignore', 'pipe', 'pipe'] });
let o = '', er = ''; c.stdout.on('data', (d) => { o += d; }); c.stderr.on('data', (d) => { er += d; });
const t = setTimeout(() => c.kill(), 240000);
c.on('error', rej); c.on('close', (cod) => { clearTimeout(t); res({ cod, stdout: o, stderr: er }); });
});
const iesiriBrut = fs.readFileSync(OUTF, 'utf8');
const outDir = path.join(T, 'aere-proof-of-software');
const r = { eticheta, secrete, ...rez, iesiriBrut, iesiri: parseaza(iesiriBrut), sumar: fs.readFileSync(SUMF, 'utf8'), outDir, cereri: [...cereri], mesaj: rez.stdout + '\n' + rez.stderr };
toateRularile.push(r);
return r;
}
const fisiereAtestare = (r) => (fs.existsSync(r.outDir) ? fs.readdirSync(r.outDir).filter((f) => f.endsWith('.json')).map((f) => [`fisier ${f}`, fs.readFileSync(path.join(r.outDir, f), 'utf8')]) : []);
// ---------------------------------------------------------------- secretele plantate, recognoscibile
const CHEI = pq.generateKeyPair({ alg: 'secp256k1+ml-dsa-44', seed: '0x' + 'deadbeef'.repeat(8), classicalSecretKey: '0x' + 'c0ffee00'.repeat(8) });
const CHEIE_TEXT = JSON.stringify(CHEI, null, 1);
// AERE-SINTETIC: cheie API plantata de proba (forma unei chei Cloud, valoare inventata), ca sa se vada ca nu apare in nicio iesire
const API_KEY = 'ak2800.0x' + '1234abcd'.repeat(5) + '.PLANTEDAPISECRET' + 'f00d'.repeat(8);
const pqBare = CHEI.pq.secretKey.slice(2);
// ATENTIE: primii 32 de octeti ai cheii secrete ML-DSA sunt rho, care e si inceputul cheii PUBLICE (publicata in atestare,
// in semnatura). Deci nu se cauta inceputul cheii secrete: se cauta K (octetii 32..63) si o bucata din s1 (128..159).
const SECRETE_CAUTATE = {
'aere-api-key intreaga': API_KEY,
'aere-api-key partea secreta': 'PLANTEDAPISECRET' + 'f00d'.repeat(8),
'marcajul cheii API': 'PLANTEDAPISECRET',
'cheia clasica': CHEI.classical.secretKey.slice(2),
'o bucata din cheia clasica': 'c0ffee00c0ffee00',
'samanta ML-DSA': 'deadbeefdeadbeef',
'K din cheia ML-DSA': pqBare.slice(64, 128),
's1 din cheia ML-DSA': pqBare.slice(256, 320),
'marcajul cheii stricate': 'PLANTEDBADKEY9c0de',
'marcajul cheii API cu rand nou': 'PLANTEDNL',
};
const cautaSecrete = (text) => { const t = String(text).toLowerCase(); return Object.entries(SECRETE_CAUTATE).filter(([, v]) => t.includes(v.toLowerCase())).map(([k]) => k); };
const faraMasti = (s) => s.split(/\r?\n/).filter((l) => !l.startsWith('::add-mask::')).join('\n');
// ================================================================ probele
console.log('actiunea: ' + ACTIUNE);
await test('action.yml si index.mjs declara ACELEASI intrari (cu implicitele si obligativitatea lor) si iesiri; runs node24 cu index.mjs; index.mjs importa static numai module node:', () => {
const y = fs.readFileSync(path.join(DIR_POS, 'action', 'action.yml'), 'utf8');
const L = y.split(/\r?\n/);
const bloc = (nume) => { const i = L.indexOf(nume + ':'); assert.ok(i >= 0, 'no ' + nume + ' block'); const out = []; for (let j = i + 1; j < L.length && (L[j].startsWith(' ') || !L[j].trim()); j++) out.push(L[j]); return out; };
const campuri = (linii) => { const o = {}; let cur = null; for (const l of linii) { const m = /^ {2}([a-z][a-z0-9-]*):/.exec(l); if (m) { cur = m[1]; o[cur] = {}; continue; } const d = /^ {4}(default|required):\s*'?([^']*?)'?\s*$/.exec(l); if (d && cur) o[cur][d[1]] = d[2]; } return o; };
const intrari = campuri(bloc('inputs'));
assert.deepStrictEqual(Object.keys(intrari).sort(), Object.keys(INTRARI).sort());
for (const [k, v] of Object.entries(INTRARI)) {
assert.strictEqual(intrari[k].default, v.default, `default of ${k}`);
assert.strictEqual(intrari[k].required === 'true', v.required === true, `required of ${k}`);
}
assert.deepStrictEqual(Object.keys(campuri(bloc('outputs'))).sort(), [...IESIRI].sort());
assert.match(y, /^ {2}using: node24$/m); assert.match(y, /^ {2}main: index\.mjs$/m);
const src = fs.readFileSync(ACTIUNE, 'utf8');
const statice = [...src.matchAll(/^import .* from '([^']+)';/gm)].map((m) => m[1]);
assert.ok(statice.length >= 5, 'the import scan found nothing (method control)');
assert.deepStrictEqual(statice.filter((s) => !s.startsWith('node:')), [], 'static imports outside node:');
assert.strictEqual([...src.matchAll(/await import\(/g)].length, 2, 'exactly two dynamic imports: pos.mjs and the Cloud client, by relative path');
for (const f of ['action/index.mjs', 'action/action.yml', 'action/README.md', 'action/examples/attest-npm-package.yml', 'test/action.test.mjs']) {
// caracterul se construieste din cod: scris literal (sau ca secventa de evadare, pe care unealta de scriere o
// transforma in caracter) proba s-ar gasi pe ea insasi
assert.ok(!fs.readFileSync(path.join(DIR_POS, f), 'utf8').includes(String.fromCharCode(0x2014)), 'em-dash in ' + f);
}
});
await test('iesirile: nume=valoare pe un rand; o valoare pe mai multe randuri primeste delimitator si se citeste inapoi identic, fara sa poata injecta alta iesire', () => {
assert.strictEqual(linieIesire('a', 'b c'), 'a=b c\n');
const v = 'rand 1\nrand 2\r\nrand 3'; const l = linieIesire('x', v);
assert.match(l, /^x<<ghadelimiter_[0-9a-f-]{36}\n/); assert.deepStrictEqual(parseaza(l), { x: v });
assert.deepStrictEqual(Object.keys(parseaza(linieIesire('x', 'a\ny=z'))), ['x']);
});
await test('curatarea: o valoare secreta dispare si scrisa cu alte litere; sub 8 caractere nu se inregistreaza; un sir hexa lung dintr-un mesaj de biblioteca e taiat, unul scurt nu', () => {
const s = new Secrete(); s.adauga('0x' + 'AbCd'.repeat(16));
assert.strictEqual(s.curata('x 0x' + 'abcd'.repeat(16) + ' y'), 'x *** y');
assert.strictEqual(s.curata('ABCD'.repeat(16)), '***');
assert.deepStrictEqual(s.adauga('scurt'), []);
assert.strictEqual(taieHex('key ' + 'f'.repeat(64) + ' end'), 'key [long hex removed] end');
assert.strictEqual(taieHex('abbrev ' + 'a'.repeat(31)), 'abbrev ' + 'a'.repeat(31));
});
const G = depozitDeProba();
const TGZ_REF = packNpmFromTree(G, 'HEAD:pkg', tmp('aere-pos-act-ref-'));
const SHA_REF = sha256(TGZ_REF);
const R1 = await ruleaza('pozitiv simplu', { workspace: G, inputs: { 'source-path': 'pkg' } });
await test('POZITIV: atestare + reconstructie dintr-o clona curata; iesirile scrise corect; nesemnat si NEnotarizat, iar rezumatul o spune', () => {
assert.strictEqual(R1.cod, 0, R1.mesaj);
const o = R1.iesiri;
assert.deepStrictEqual(Object.keys(o).sort(), ['artifact-path', 'artifact-sha256', 'attestation-path', 'statement-hash', 'tree']);
assert.ok(fs.existsSync(o['artifact-path']) && fs.existsSync(o['attestation-path']));
assert.strictEqual(o['artifact-sha256'], sha256(o['artifact-path']));
assert.strictEqual(o['artifact-sha256'], SHA_REF, 'the artifact is npm pack of the committed tree');
assert.strictEqual(o.tree, gitIn(G, ['rev-parse', 'HEAD:pkg']));
const att = JSON.parse(fs.readFileSync(o['attestation-path'], 'utf8'));
assert.strictEqual(att.statementHash, o['statement-hash']); assert.strictEqual(att.statement.artifacts[0].sha256, o['artifact-sha256']);
assert.strictEqual(att.statement.source.path, 'pkg'); assert.strictEqual(att.statement.source.pathDirty, false);
assert.strictEqual(att.statement.source.commit, gitIn(G, ['rev-parse', 'HEAD'])); assert.strictEqual(att.statement.build.kind, 'npm-pack');
assert.strictEqual(att.signature, null); assert.strictEqual(att.notarization, null);
assert.match(R1.stdout, /OK {3}rebuild: npm pack of the attested tree reproduces proba-actiune-1\.2\.3\.tgz byte for byte/);
assert.match(R1.sumar, /\*\*NOT notarized\*\*/); assert.match(R1.sumar, /\*\*unsigned\*\*/); assert.match(R1.sumar, /reproduced byte for byte from a clean clone/);
assert.strictEqual(R1.cereri.length, 0, 'no request is made without an API key');
});
await test('un STRAIN verifica atestarea iesita cu `pos.mjs verify --rebuild-from` pe clona LUI: VALID, reconstructia reproduce artefactul', () => {
const C = tmp('aere-pos-act-strain-'); gitIn(os.tmpdir(), ['clone', '-q', G, C]);
const out = execFileSync(process.execPath, [POS, 'verify', R1.iesiri['attestation-path'], '--rebuild-from', C, R1.iesiri['artifact-path']], { stdio: 'pipe' }).toString();
assert.match(out, /OK {3}rebuild: npm pack of the attested tree reproduces/); assert.match(out, /VALID: every present claim holds/);
});
modServer = '200';
const R2 = await ruleaza('semnat + notarizat', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': CHEIE_TEXT, 'aere-api-key': API_KEY }, env: { AERE_POS_API_BASE: BAZA }, secrete: true });
await test('POZITIV: semnat hibrid + notarizat (serverul raspunde 200): notarized-tx si proof-url, chitanta in atestare, o singura cerere cu cheia si hash-ul corect; pos.mjs verify citeste chitanta', async () => {
assert.strictEqual(R2.cod, 0, R2.mesaj);
const o = R2.iesiri; const att = JSON.parse(fs.readFileSync(o['attestation-path'], 'utf8'));
assert.strictEqual(o['notarized-tx'], TX); assert.strictEqual(o['proof-url'], `${BAZA}/proof/${att.statementHash}`);
assert.strictEqual(R2.cereri.length, 1); const c = R2.cereri[0];
assert.strictEqual(c.m, 'POST'); assert.strictEqual(c.u, '/v1/notarize'); assert.strictEqual(c.k, API_KEY);
assert.deepStrictEqual(JSON.parse(c.b), { hash: att.statementHash });
assert.strictEqual(att.notarization.txHash, TX); assert.strictEqual(att.notarization.block, 4242); assert.strictEqual(att.notarization.proof, '/v1/proof/' + att.statementHash);
assert.strictEqual(att.signature.alg, 'secp256k1+ml-dsa-44'); assert.strictEqual(att.signature.classicalPublicKey, CHEI.classical.publicKey);
assert.strictEqual(o['artifact-sha256'], SHA_REF, 'signing does not change the artifact');
const lant = { proof: async () => ({ notarized: true, block: 4242, txHash: TX, finality: 'post-quantum', pqAnchor: null }) };
const r = await verify(att, [o['artifact-path']], { cloud: lant });
assert.strictEqual(r.valid, true, JSON.stringify(r.checks));
assert.ok(r.checks.find((x) => x.name.startsWith('hybrid signature') && x.pass === true));
assert.ok(r.checks.find((x) => x.name.startsWith('on chain: first appearance matches the receipt') && x.pass === true));
const r0 = await verify(att, [o['artifact-path']], { cloud: { proof: async () => ({ notarized: true, block: 4243, txHash: TX, finality: 'post-quantum' }) } });
assert.strictEqual(r0.valid, false, 'control: a chain answering another block must make it INVALID');
assert.match(R2.sumar, /tx `0xabab/); assert.doesNotMatch(R2.sumar, /NOT notarized/);
});
const SH = tmp('aere-pos-act-shallow-'); gitIn(os.tmpdir(), ['clone', '-q', '--depth', '1', pathToFileURL(G).href, SH]);
const R3 = await ruleaza('clona superficiala, implicitele actiunii', { workspace: SH, inputs: { 'source-path': 'pkg' }, faraImplicite: true });
await test('POZITIV: spatiu de lucru SUPERFICIAL (ca actions/checkout implicit, fetch-depth 1) si fara INPUT_BUILD/INPUT_VERIFY-REBUILD: implicitele din cod, acelasi artefact', () => {
assert.strictEqual(gitIn(SH, ['rev-parse', '--is-shallow-repository']), 'true', 'control: the workspace really is shallow');
assert.strictEqual(R3.cod, 0, R3.mesaj);
assert.match(R3.stdout, /OK {3}rebuild: npm pack of the attested tree reproduces/);
assert.strictEqual(R3.iesiri['artifact-sha256'], SHA_REF);
});
const DH = tmp('aere-pos-act-detasat-'); gitIn(os.tmpdir(), ['clone', '-q', G, DH]); gitIn(DH, ['config', 'core.autocrlf', 'false']);
gitIn(DH, ['checkout', '-q', '--detach']); fs.writeFileSync(path.join(DH, 'pkg', 'lib', 'index.js'), 'module.exports = 3;\n'); gitIn(DH, ['commit', '-q', '-am', 'commit detasat']);
const R4 = await ruleaza('HEAD detasat', { workspace: DH, inputs: { 'source-path': 'pkg' } });
await test('POZITIV: HEAD detasat pe un commit care nu e pe nicio ramura (ca un checkout de pull request): clona curata il contine si reconstructia trece', () => {
assert.strictEqual(gitIn(DH, ['for-each-ref', '--contains', 'HEAD', 'refs/heads']), '', 'control: no branch contains the commit');
assert.strictEqual(R4.cod, 0, R4.mesaj);
const att = JSON.parse(fs.readFileSync(R4.iesiri['attestation-path'], 'utf8'));
assert.strictEqual(att.statement.source.commit, gitIn(DH, ['rev-parse', 'HEAD']));
assert.notStrictEqual(R4.iesiri['artifact-sha256'], SHA_REF, 'other content, other artifact');
assert.strictEqual(R4.iesiri['artifact-sha256'], sha256(packNpmFromTree(DH, 'HEAD:pkg', tmp('aere-pos-act-ref2-'))));
});
const W = tmp('aere-pos-act-crlf-'); gitIn(os.tmpdir(), ['clone', '-q', '-c', 'core.autocrlf=true', G, W]);
const R5 = await ruleaza('copie de lucru CRLF', { workspace: W, inputs: { 'source-path': 'pkg' } });
await test('POZITIV: copie de lucru cu CRLF (core.autocrlf=true, ca un runner Windows): nu e "murdara", iar artefactul e acelasi, din octetii comisi', () => {
assert.ok(fs.readFileSync(path.join(W, 'pkg', 'LICENSE'), 'utf8').includes('\r\n'), 'control: the checkout really has CRLF');
assert.strictEqual(R5.cod, 0, R5.mesaj);
assert.strictEqual(R5.iesiri['artifact-sha256'], SHA_REF);
});
fs.appendFileSync(path.join(G, 'altceva', 'x.txt'), 'schimbat, in afara pachetului\n');
const R6 = await ruleaza('schimbare in afara source-path', { workspace: G, inputs: { 'source-path': 'pkg' } });
gitIn(G, ['checkout', '-q', '--', 'altceva/x.txt']);
await test('POZITIV (marginea gardei): o schimbare necomisa IN AFARA source-path nu opreste atestarea; declaratia spune dirty=true, pathDirty=false', () => {
assert.strictEqual(R6.cod, 0, R6.mesaj);
const att = JSON.parse(fs.readFileSync(R6.iesiri['attestation-path'], 'utf8'));
assert.strictEqual(att.statement.source.dirty, true); assert.strictEqual(att.statement.source.pathDirty, false);
assert.strictEqual(R6.iesiri['artifact-sha256'], SHA_REF);
});
const R7 = await ruleaza('cheie base64', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': Buffer.from(CHEIE_TEXT).toString('base64'), 'verify-rebuild': 'false' }, secrete: true });
await test('POZITIV: cheia de semnare data ca base64 al fisierului keygen; cu verify-rebuild=false rezumatul spune ca reconstructia NU e verificata', () => {
assert.strictEqual(R7.cod, 0, R7.mesaj);
const att = JSON.parse(fs.readFileSync(R7.iesiri['attestation-path'], 'utf8'));
assert.strictEqual(att.signature.classicalPublicKey, CHEI.classical.publicKey);
assert.match(R7.sumar, /\*\*NOT verified\*\*: verify-rebuild is false/);
assert.doesNotMatch(R7.stdout, /rebuild: npm pack of the attested tree reproduces/);
});
// ---------------------------------------------------------------- controalele negative
fs.writeFileSync(path.join(G, 'pkg', 'nou.txt'), 'necomis\n');
const Ra = await ruleaza('(a) fisier neurmarit', { workspace: G, inputs: { 'source-path': 'pkg' } });
fs.rmSync(path.join(G, 'pkg', 'nou.txt'));
await test('CONTROL NEGATIV (a): un fisier neurmarit in source-path -> refuz cu motivul si fisierul numite; fara iesiri, fara artefact', () => {
assert.notStrictEqual(Ra.cod, 0);
assert.match(Ra.mesaj, /source-path "pkg" has uncommitted or untracked files/); assert.match(Ra.stderr, /\?\? pkg\/nou\.txt/);
assert.match(Ra.stdout, /^::error::source-path "pkg" has uncommitted or untracked files/m);
assert.strictEqual(Ra.iesiriBrut, ''); assert.ok(!fs.existsSync(Ra.outDir) || !fs.readdirSync(Ra.outDir).length);
});
fs.appendFileSync(path.join(G, 'pkg', 'lib', 'index.js'), '// schimbat si necomis\n');
const Ra2 = await ruleaza('(a) fisier modificat', { workspace: G, inputs: { 'source-path': 'pkg' } });
gitIn(G, ['checkout', '-q', '--', 'pkg/lib/index.js']);
await test('CONTROL NEGATIV (a, varianta): un fisier urmarit modificat si necomis in source-path -> refuz, cu fisierul numit', () => {
assert.notStrictEqual(Ra2.cod, 0);
assert.match(Ra2.mesaj, /has uncommitted or untracked files/); assert.match(Ra2.stderr, / M pkg\/lib\/index\.js/);
assert.strictEqual(Ra2.iesiriBrut, '');
});
modServer = '403';
const Rb = await ruleaza('(b) 403', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': CHEIE_TEXT, 'aere-api-key': API_KEY }, env: { AERE_POS_API_BASE: BAZA }, secrete: true });
await test('CONTROL NEGATIV (b): serverul de notarizare raspunde 403 -> actiunea cade, spune HTTP 403 si NOT notarized, nu scrie proof-url; cererea a ajuns (refuzul e pe RASPUNS)', () => {
assert.notStrictEqual(Rb.cod, 0);
assert.match(Rb.mesaj, /notarization refused: HTTP 403 \(invalid api key \*\*\*\); the attestation is NOT notarized/);
assert.strictEqual(Rb.cereri.length, 1, 'the request reached the server');
assert.ok(!('proof-url' in Rb.iesiri) && !('notarized-tx' in Rb.iesiri)); assert.strictEqual(Rb.iesiriBrut, '');
assert.match(Rb.sumar, /The attestation is NOT notarized\./); assert.doesNotMatch(Rb.sumar, /proof:/);
const ramas = fisiereAtestare(Rb); assert.strictEqual(ramas.length, 1); assert.strictEqual(JSON.parse(ramas[0][1]).notarization, null);
});
modServer = '200-fara-tx';
const Rb2 = await ruleaza('(b) 200 fara txHash', { workspace: G, inputs: { 'source-path': 'pkg', 'aere-api-key': API_KEY, 'verify-rebuild': 'false' }, env: { AERE_POS_API_BASE: BAZA }, secrete: true });
await test('CONTROL NEGATIV (b, varianta): 200 fara txHash si bloc -> cade; un 200 gol nu e o notarizare', () => {
assert.notStrictEqual(Rb2.cod, 0);
assert.match(Rb2.mesaj, /notarization answered 200 without a transaction hash and a block; the attestation is NOT notarized/);
assert.strictEqual(Rb2.iesiriBrut, '');
});
modServer = '302';
const Rb3 = await ruleaza('(b) redirectare', { workspace: G, inputs: { 'source-path': 'pkg', 'aere-api-key': API_KEY, 'verify-rebuild': 'false' }, env: { AERE_POS_API_BASE: BAZA }, secrete: true });
await test('CONTROL NEGATIV (b, varianta): o redirectare 302 NU se urmeaza (ar duce x-api-key in alta parte) -> cade; tinta redirectarii nu primeste nimic', () => {
assert.notStrictEqual(Rb3.cod, 0);
assert.match(Rb3.mesaj, /notarization request failed: .*redirect/);
assert.strictEqual(Rb3.cereri.filter((c) => c.u === '/v1/leak').length, 0); assert.strictEqual(Rb3.cereri.length, 1);
assert.strictEqual(Rb3.iesiriBrut, '');
});
const Rb4 = await ruleaza('(b) baza API straina', { workspace: G, inputs: { 'source-path': 'pkg', 'aere-api-key': API_KEY }, env: { AERE_POS_API_BASE: 'https://example.invalid/v1' }, secrete: true });
await test('CONTROL NEGATIV (b, varianta): AERE_POS_API_BASE spre o gazda care nu e loopback -> refuz inainte de orice cerere', () => {
assert.notStrictEqual(Rb4.cod, 0);
assert.match(Rb4.mesaj, /AERE_POS_API_BASE may point only to a loopback address/);
assert.strictEqual(Rb4.iesiriBrut, '');
});
modServer = '200';
const Rc = await ruleaza('(c) artefact alterat dupa atestare', { workspace: G, inputs: { 'source-path': 'pkg', 'aere-api-key': API_KEY }, env: { AERE_POS_TEST_HOOK: 'alter-after-attest', AERE_POS_API_BASE: BAZA }, secrete: true });
await test('CONTROL NEGATIV (c): un octet schimbat in artefact intre atestare si verificare -> verificarea cade pe digestul artefactului; nimic nu se notarizeaza', () => {
assert.notStrictEqual(Rc.cod, 0);
assert.match(Rc.mesaj, /verification of the fresh attestation failed; nothing is notarized/);
assert.match(Rc.mesaj, /FAIL artifact proba-actiune-1\.2\.3\.tgz: sha256 and size match \(got 0x[0-9a-f]{64}\)/);
assert.match(Rc.stdout, /TEST HOOK ACTIVE: alter-after-attest/);
assert.match(Rc.stdout, /OK {3}rebuild: npm pack of the attested tree reproduces/, 'the rebuild itself held: the failure is the one named');
assert.strictEqual(Rc.cereri.length, 0, 'nothing was sent for notarization'); assert.strictEqual(Rc.iesiriBrut, '');
});
const Rc2 = await ruleaza('(c) artefact strain de arbore', { workspace: G, inputs: { 'source-path': 'pkg' }, env: { AERE_POS_TEST_HOOK: 'foreign-artifact' } });
await test('CONTROL NEGATIV (c, varianta): un artefact care NU vine din arborele comis (alterat inainte de atestare) -> digestul tine, reconstructia NU reproduce, refuz', () => {
assert.notStrictEqual(Rc2.cod, 0);
assert.match(Rc2.mesaj, /does NOT reproduce the artifact byte for byte; nothing is notarized/);
assert.match(Rc2.mesaj, /FAIL rebuild: npm pack of the attested tree reproduces proba-actiune-1\.2\.3\.tgz byte for byte \(got 0x[0-9a-f]{64}/);
assert.match(Rc2.stdout, /OK {3}artifact proba-actiune-1\.2\.3\.tgz: sha256 and size match/);
assert.strictEqual(Rc2.iesiriBrut, '');
});
const Rc3 = await ruleaza('(c) artefact strain, fara reconstructie', { workspace: G, inputs: { 'source-path': 'pkg', 'verify-rebuild': 'false' }, env: { AERE_POS_TEST_HOOK: 'foreign-artifact' } });
await test('perechea lui (c, varianta): ACELASI artefact strain cu verify-rebuild=false TRECE (numai digesturile), si rezumatul spune NOT verified: reconstructia e singura care il prinde', () => {
assert.strictEqual(Rc3.cod, 0, Rc3.mesaj);
assert.match(Rc3.sumar, /\*\*NOT verified\*\*/); assert.notStrictEqual(Rc3.iesiri['artifact-sha256'], SHA_REF);
});
const cheieRea = '{"alg":"secp256k1+ml-dsa-44","classical":{"secretKey":"0xPLANTEDBADKEY9c0de' + 'ab'.repeat(20);
const Rd1 = await ruleaza('(d) cheie JSON stricat', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': cheieRea }, secrete: true });
// AERE-SINTETIC: o cheie de semnare de alta forma, inventata pentru proba de refuz
const Rd2 = await ruleaza('(d) cheie de alta forma', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': JSON.stringify({ alg: 'x', secret: 'PLANTEDBADKEY9c0de-forma' }) }, secrete: true });
const alta = pq.generateKeyPair({ alg: 'secp256k1+ml-dsa-44' });
const Rd3 = await ruleaza('(d) cheie publica nepotrivita', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': JSON.stringify({ ...CHEI, classical: { ...CHEI.classical, publicKey: alta.classical.publicKey } }), 'verify-rebuild': 'false' }, secrete: true });
const Rd4 = await ruleaza('(d) cheie API cu rand nou', { workspace: G, inputs: { 'source-path': 'pkg', 'aere-api-key': 'ak2800.0x' + '9876fedc'.repeat(5) + '.PLANTEDNL' + 'beef'.repeat(4) + '\nsecond-line-value' }, env: { AERE_POS_API_BASE: BAZA }, secrete: true });
await test('intrarile secrete stricate sunt refuzate cu motivul numit (JSON stricat, alta forma, cheie publica nepotrivita, rand nou in cheia API), fara sa trimita nimic', () => {
assert.notStrictEqual(Rd1.cod, 0); assert.match(Rd1.mesaj, /signing-key is not valid JSON \(nor base64 of JSON\); its content is not shown/);
assert.notStrictEqual(Rd2.cod, 0); assert.match(Rd2.mesaj, /signing-key is JSON but not a key file written by `pos\.mjs keygen`/);
assert.notStrictEqual(Rd3.cod, 0); assert.match(Rd3.mesaj, /attestation or signing failed: classical public key does not match the secret key/);
assert.notStrictEqual(Rd4.cod, 0); assert.match(Rd4.mesaj, /aere-api-key contains a line break or a control character; nothing was sent/); assert.strictEqual(Rd4.cereri.length, 0);
for (const r of [Rd1, Rd2, Rd3, Rd4]) assert.strictEqual(r.iesiriBrut, '', r.eticheta);
});
await test('CONTROL NEGATIV (d): cheia de semnare si cheia API plantate NU apar in stdout (in afara comenzilor ::add-mask::), stderr, GITHUB_OUTPUT, GITHUB_STEP_SUMMARY, nici in fisierele de atestare, in NICIO rulare cu secrete (reusite sau cazute)', () => {
// controlul pozitiv al metodei: cautarea gaseste ce e sigur acolo
assert.ok(cautaSecrete('x ' + API_KEY + ' y').includes('aere-api-key intreaga'));
assert.ok(cautaSecrete(CHEIE_TEXT.toUpperCase()).includes('K din cheia ML-DSA'), 'the search is case-insensitive');
assert.strictEqual(pqBare.slice(0, 64), CHEI.pq.publicKey.slice(2, 66), 'rho: the start of the ML-DSA secret key IS public (why it is not searched)');
const cuSecrete = toateRularile.filter((r) => r.secrete);
assert.ok(cuSecrete.length >= 10, 'runs with planted secrets: ' + cuSecrete.length);
const gasite = [];
for (const r of cuSecrete) {
assert.ok(/^::add-mask::/m.test(r.stdout), r.eticheta + ': no ::add-mask::');
const locuri = [['stdout', faraMasti(r.stdout)], ['stderr', r.stderr], ['GITHUB_OUTPUT', r.iesiriBrut], ['GITHUB_STEP_SUMMARY', r.sumar], ...fisiereAtestare(r)];
for (const [loc, text] of locuri) { const g = cautaSecrete(text); if (g.length) gasite.push(`${r.eticheta} / ${loc}: ${g.join(', ')}`); }
}
assert.deepStrictEqual(gasite, []);
// mastile chiar poarta secretele: altfel runner-ul nu ar avea ce ascunde, si cautarea de mai sus ar fi fost pe un stdout gol
const masti = (r) => r.stdout.split(/\r?\n/).filter((l) => l.startsWith('::add-mask::')).join('\n');
for (const k of ['aere-api-key intreaga', 'aere-api-key partea secreta', 'cheia clasica', 'K din cheia ML-DSA', 'samanta ML-DSA']) assert.ok(cautaSecrete(masti(R2)).includes(k), 'mask missing: ' + k);
assert.ok(cautaSecrete(masti(Rd1)).includes('marcajul cheii stricate'), 'a key that does not parse is still masked');
assert.ok(cautaSecrete(Rb.cereri.length ? JSON.stringify(Rb.cereri[0]) : '').includes('aere-api-key intreaga'), 'control: the 403 server did receive (and echo) the planted key');
});
const Re = await ruleaza('(e) build necunoscut', { workspace: G, inputs: { 'source-path': 'pkg', build: 'docker' } });
const Rf = await ruleaza('(f) boolean gresit', { workspace: G, inputs: { 'source-path': 'pkg', 'verify-rebuild': 'yes' } });
const Rg = await ruleaza('(g) carlig pe runner', { workspace: G, inputs: { 'source-path': 'pkg' }, env: { GITHUB_ACTIONS: 'true', AERE_POS_TEST_HOOK: 'alter-after-attest' } });
const Rh = await ruleaza('(h) radacina depozitului', { workspace: G, inputs: { 'source-path': '.' } });
const Ri = await ruleaza('(i) out-dir in source-path', { workspace: G, inputs: { 'source-path': 'pkg', 'out-dir': 'pkg/out' } });
const Rj = await ruleaza('(j) source-path lipsa', { workspace: G, inputs: {} });
await test('refuzurile intrarilor, fiecare cu motivul lui: build necunoscut, boolean gresit, carlig de proba pe un runner, radacina depozitului, out-dir in source-path, source-path lipsa', () => {
const cere = (r, re) => { assert.notStrictEqual(r.cod, 0, r.eticheta); assert.match(r.mesaj, re, r.eticheta); assert.strictEqual(r.iesiriBrut, '', r.eticheta); };
cere(Re, /build "docker" is not supported/);
cere(Rf, /input verify-rebuild must be true or false/);
cere(Rg, /AERE_POS_TEST_HOOK is a switch for the local tests and is refused on a GitHub runner/);
cere(Rh, /source-path is the repository root: this version attests a package in a SUBDIRECTORY/);
cere(Ri, /out-dir is inside source-path/);
cere(Rj, /source-path is required/);
assert.ok(!fs.existsSync(path.join(G, 'pkg', 'out')), 'the refused run left nothing inside source-path');
});
// ---------------------------------------------------------------- setul minim de fisiere (ce descarca un runner) si dependintele
function aspectMinim() {
const L = tmp('aere-pos-act-aspect-');
for (const f of ['tools/proof-of-software/pos.mjs', 'tools/proof-of-software/action/index.mjs', 'tools/proof-of-software/action/action.yml', 'sdk/index.mjs', 'sdk/package.json', 'sdk-pq-sign/index.mjs', 'sdk-pq-sign/package.json', 'sdk-pq-sign/package-lock.json']) {
fs.mkdirSync(path.dirname(path.join(L, f)), { recursive: true }); fs.copyFileSync(path.join(RADACINA, f), path.join(L, f));
}
return L;
}
const L1 = aspectMinim();
const Rk = await ruleaza('dependinte lipsa, npm ci offline', { workspace: G, inputs: { 'source-path': 'pkg' }, actiune: path.join(L1, 'tools', 'proof-of-software', 'action', 'index.mjs'), env: { AERE_POS_TEST_HOOK: 'npm-offline' } });
await test('dependinte LIPSA (checkout-ul actiunii fara node_modules, ca pe un runner): actiunea incearca npm ci din package-lock.json; niciodata un ERR_MODULE_NOT_FOUND brut', () => {
assert.doesNotMatch(Rk.mesaj, /ERR_MODULE_NOT_FOUND|Cannot find package/);
assert.match(Rk.stdout, /installing the pinned dependencies of sdk-pq-sign from its package-lock\.json/);
if (Rk.cod === 0) { assert.match(Rk.stdout, /dependencies installed/); assert.strictEqual(Rk.iesiri['artifact-sha256'], SHA_REF); return; }
assert.match(Rk.mesaj, /could not install the pinned dependencies of sdk-pq-sign \(npm ci from its package-lock\.json\)/);
assert.strictEqual(Rk.iesiriBrut, '');
if (!/ENOTCACHED|only-if-cached/.test(Rk.mesaj)) throw new Error('npm ci failed for another reason than an empty offline cache: ' + Rk.stderr.slice(0, 300));
nemasurate.push('instalarea reala a dependintelor pe un runner (npm ci din registru): in proba --offline, cache-ul local nu are pachetele, refuzul iese curat');
});
const L2 = aspectMinim();
fs.cpSync(path.join(RADACINA, 'sdk-pq-sign', 'node_modules'), path.join(L2, 'sdk-pq-sign', 'node_modules'), { recursive: true });
const Rl = await ruleaza('set minim + dependinte', { workspace: G, inputs: { 'source-path': 'pkg', 'signing-key': CHEIE_TEXT }, actiune: path.join(L2, 'tools', 'proof-of-software', 'action', 'index.mjs'), secrete: true });
await test('POZITIV: numai cele 8 fisiere (pos.mjs, action/, sdk, sdk-pq-sign) + dependintele fixate ajung: atestare semnata + reconstructie, acelasi artefact', () => {
assert.strictEqual(Rl.cod, 0, Rl.mesaj);
assert.match(Rl.stdout, /dependencies present/);
assert.strictEqual(Rl.iesiri['artifact-sha256'], SHA_REF);
assert.match(Rl.stdout, /OK {3}rebuild: npm pack of the attested tree reproduces/);
});
server.close();
if (process.env.AERE_POS_PASTREAZA !== '1') {
let ramase = 0;
for (const d of facute) { try { fs.rmSync(d, { recursive: true, force: true, maxRetries: 3 }); } catch { ramase++; } }
console.log(`curatenie: ${facute.length - ramase} dosare temporare sterse, ${ramase} ramase`);
}
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
if (nemasurate.length) console.log(`NEMASURAT (${nemasurate.length}): ${nemasurate.join(' | ')}`);
if (esecuri.length) process.exitCode = 1;
@@ -0,0 +1,14 @@
// Controlul negativ al identitatii constructorului (credential.test.mjs), prin mecanismul comun din _control.mjs: fiecare paznic
// scos intr-o copie trebuie sa inroseasca exact proba lui.
// node aerenew/tools/proof-of-software/test/credential-control-negativ.mjs
import { controleaza } from './_control.mjs';
process.exitCode = controleaza('credential.test.mjs', [
['radacina de incredere nu se mai compara', "keyId(publicKeysOf(trustIssuer)) === keyId(b.issuer && b.issuer.keys)", 'true', '2. CONTROL'],
['semnatarul acreditarii nu mai trebuie sa fie emitentul numit', 'sv.valid && semnatarEmitent,', 'sv.valid,', '6. CONTROL'],
['cheile subiectului nu se mai compara cu semnatarul declaratiei', "!!att.signature && keyId(publicKeysOf(att.signature)) === keyId(b.subject && b.subject.keys)", '!!att.signature', '7. CONTROL'],
['valabilitatea nu se mai judeca', 'Date.parse(t) >= Date.parse(b.validFrom) && Date.parse(t) <= Date.parse(b.validUntil)', 'true', '8. CONTROL'],
['revocarile emitentului se ignora', 'if (rb.credential !== want) continue;', 'continue;', '9. revocarea'],
['timpul lantului se ignora (bate data declarata)', 'const t = chainTime || att.statement.createdAt;', 'const t = att.statement.createdAt;', '10. timpul'],
['data declarata achita din nou (B-18)', 'const declarat = !chainTime;', 'const declarat = false;', '12. B-18'],
]);
@@ -0,0 +1,119 @@
// Proof of Software 1.3.0: identitatea constructorului (acreditarea de dezvoltator emisa de o organizatie). Fiecare afirmatie cu
// perechea ei negativa. Offline: lantul e un obiect `cloud` injectat care raspunde ca Aere Cloud (numai pentru timpul de pe lant).
// node test/credential.test.mjs iesire 0 = toate cum trebuia
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { attest, verify, issueCredential, revokeCredential, publicKeysOf } from '../pos.mjs';
import * as pq from '../../../sdk-pq-sign/index.mjs';
const AICI = path.dirname(fileURLToPath(import.meta.url));
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' — ' + (e.message || e)); } }
const cere = (c, m) => { if (!c) throw new Error(m); };
const check = (r, re) => r.checks.find((c) => re.test(c.name));
const D = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-cred-'));
const A = path.join(D, 'app.tgz'); fs.writeFileSync(A, 'artifact bytes');
const org = pq.generateKeyPair(), alt = pq.generateKeyPair(), dev = pq.generateKeyPair(), strain = pq.generateKeyPair();
const cred = issueCredential({ issuerKeys: org, issuerName: 'Example Org', subjectKeys: publicKeysOf(dev), subjectName: 'Ana Dev', validFrom: '2026-01-01T00:00:00Z', validUntil: '2027-01-01T00:00:00Z' });
const acum = new Date('2026-06-01T00:00:00Z');
const att = await attest({ artifacts: [A], name: 'app', version: '1.0.0', keys: dev, credential: cred, cwd: D, now: acum });
await test('1. atestare sub acreditare, verificata cu radacina de incredere a organizatiei: VALIDA, identitatea judecata pe fiecare punct', async () => {
const r = await verify(att, [A], { trustIssuer: publicKeysOf(org) });
cere(r.valid, JSON.stringify(r.checks.filter((c) => c.pass === false)));
for (const re of [/carries the credential/, /signed by the issuer/, /trust root you gave/, /names the keys that signed/]) cere(check(r, re) && check(r, re).pass === true, 'lipseste sau nu trece: ' + re);
cere(/createdAt, declared by the builder/.test(check(r, /valid at/).name), 'timpul folosit trebuie numit');
// 2026-09-29 (B-18): pe data declarata, "in valabilitate" nu se poate crede (o alege cine tine cheile): nejudecat, nu trecut
cere(check(r, /valid at/).pass === null, 'pe data declarata, valabilitatea trebuie raportata nejudecata');
});
await test('2. CONTROL: alta radacina de incredere (alta organizatie) -> INVALIDA', async () => {
const r = await verify(att, [A], { trustIssuer: publicKeysOf(alt) });
cere(!r.valid && check(r, /trust root/).pass === false, 'trebuia sa pice pe emitent');
});
await test('3. fara radacina de incredere: emitentul NU e judecat, si se spune (nu e trecut drept incredere)', async () => {
const r = await verify(att, [A]);
cere(check(r, /issuer trust/) && check(r, /issuer trust/).pass === null, 'trebuia raportat nejudecat');
});
await test('4. CONTROL: attest cu o acreditare care numeste alte chei decat --keys e refuzat', async () => {
let aruncat = null; try { await attest({ artifacts: [A], keys: strain, credential: cred, cwd: D }); } catch (e) { aruncat = e.message; }
cere(/other keys/.test(aruncat || ''), 'trebuia refuzat: ' + aruncat);
});
await test('5. CONTROL: acreditarea inlocuita in atestare (declaratia numeste alta) -> INVALIDA', async () => {
const alta = issueCredential({ issuerKeys: org, issuerName: 'Example Org', subjectKeys: publicKeysOf(dev), subjectName: 'Altcineva', validFrom: '2026-01-01T00:00:00Z', validUntil: '2027-01-01T00:00:00Z' });
const r = await verify({ ...att, credential: alta }, [A], { trustIssuer: publicKeysOf(org) });
cere(!r.valid && check(r, /carries the credential/).pass === false, 'trebuia prins');
});
await test('6. CONTROL: o acreditare care numeste organizatia dar e semnata de un strain -> INVALIDA (semnatarul nu e emitentul numit)', async () => {
const fals = issueCredential({ issuerKeys: strain, issuerName: 'Example Org', subjectKeys: publicKeysOf(dev), subjectName: 'Ana Dev', validFrom: '2026-01-01T00:00:00Z', validUntil: '2027-01-01T00:00:00Z' });
fals.body.issuer.keys = publicKeysOf(org);
fals.signature = pq.sign(JSON.stringify(fals.body), strain);
const a2 = await attest({ artifacts: [A], keys: dev, credential: fals, cwd: D, now: acum });
const r = await verify(a2, [A], { trustIssuer: publicKeysOf(org) });
cere(!r.valid && check(r, /signed by the issuer/).pass === false, 'trebuia prins');
});
await test('7. CONTROL: declaratia semnata de alte chei decat cele din acreditare -> INVALIDA', async () => {
const a2 = JSON.parse(JSON.stringify(att)); a2.signature = pq.sign(JSON.stringify(a2.statement), strain);
const r = await verify(a2, [A], { trustIssuer: publicKeysOf(org) });
cere(!r.valid && check(r, /names the keys that signed/).pass === false, 'trebuia prins');
});
await test('8. CONTROL: momentul atestarii in afara valabilitatii -> INVALIDA', async () => {
const a2 = await attest({ artifacts: [A], keys: dev, credential: cred, cwd: D, now: new Date('2027-03-01T00:00:00Z') });
const r = await verify(a2, [A], { trustIssuer: publicKeysOf(org) });
cere(!r.valid && check(r, /valid at/).pass === false, 'trebuia prins');
});
await test('9. revocarea: inaintea atestarii -> INVALIDA; dupa ea -> VALIDA; semnata de alt emitent -> ignorata si spusa', async () => {
const inainte = revokeCredential({ issuerKeys: org, credential: cred, revokedAt: '2026-05-01T00:00:00Z', reason: 'cheie pierduta' });
const dupa = revokeCredential({ issuerKeys: org, credential: cred, revokedAt: '2026-07-01T00:00:00Z' });
const straina = revokeCredential({ issuerKeys: alt, credential: cred, revokedAt: '2026-02-01T00:00:00Z' });
const r1 = await verify(att, [A], { trustIssuer: publicKeysOf(org), revocations: [inainte] });
cere(!r1.valid && check(r1, /not revoked/).pass === false, 'revocarea de dinainte trebuia sa pice');
const r2 = await verify(att, [A], { trustIssuer: publicKeysOf(org), revocations: [dupa] });
cere(r2.valid && check(r2, /not revoked/).pass === null, 'revocarea de dupa nu acuza atestarea, dar pe data declarata nici nu o achita (B-18)');
const r3 = await verify(att, [A], { trustIssuer: publicKeysOf(org), revocations: [straina] });
cere(r3.valid && check(r3, /a revocation/).pass === null, 'o revocare straina se ignora si se spune');
const r4 = await verify(att, [A], { trustIssuer: publicKeysOf(org) });
// AERE-SINTETIC: nu e un secret; 'credential: revocations' e numele unei verificari
cere(check(r4, /credential: revocations/).pass === null, 'fara revocari date, se spune ca nu s-a putut vedea');
});
await test('10. timpul de pe LANT bate data declarata: un constructor care isi antedateaza atestarea sub o acreditare expirata e prins', async () => {
// createdAt declarat 2026-06-01 (in valabilitate), dar lantul a vazut-o prima oara pe 2027-02-01 (dupa expirare)
const a2 = JSON.parse(JSON.stringify(att)); a2.notarization = { block: 123, txHash: '0x' + 'ab'.repeat(32) };
const cloud = { proof: async () => ({ notarized: true, block: 123, txHash: '0x' + 'ab'.repeat(32), firstSeenAt: Date.parse('2027-02-01T00:00:00Z') / 1000, finality: 'post-quantum', pqAnchor: null }) };
const r = await verify(a2, [A], { trustIssuer: publicKeysOf(org), cloud });
cere(!r.valid && check(r, /valid at/).pass === false && /first seen on chain/.test(check(r, /valid at/).name), JSON.stringify(check(r, /valid at/)));
const cloudBun = { proof: async () => ({ notarized: true, block: 123, txHash: '0x' + 'ab'.repeat(32), firstSeenAt: Date.parse('2026-06-02T00:00:00Z') / 1000, finality: 'post-quantum', pqAnchor: null }) };
const rb = await verify(a2, [A], { trustIssuer: publicKeysOf(org), cloud: cloudBun });
cere(rb.valid && /first seen on chain/.test(check(rb, /valid at/).name), 'cu timpul lantului in valabilitate trebuia VALIDA');
});
await test('11. CLI cap la cap: pubkey, credential issue, attest --credential, verify --trust-issuer (0), alt emitent (1), revocare (1)', async () => {
const pos = path.join(AICI, '..', 'pos.mjs'); const f = (n) => path.join(D, n);
fs.writeFileSync(f('org.json'), JSON.stringify(org)); fs.writeFileSync(f('dev.json'), JSON.stringify(dev)); fs.writeFileSync(f('alt.json'), JSON.stringify(alt));
const run = (args) => { try { execFileSync(process.execPath, [pos, ...args], { cwd: D, stdio: 'pipe' }); return 0; } catch (e) { return e.status; } };
cere(run(['pubkey', '--keys', f('org.json'), '--out', f('org.pub.json')]) === 0 && run(['pubkey', '--keys', f('dev.json'), '--out', f('dev.pub.json')]) === 0 && run(['pubkey', '--keys', f('alt.json'), '--out', f('alt.pub.json')]) === 0, 'pubkey');
cere(!('secretKey' in (JSON.parse(fs.readFileSync(f('org.pub.json'), 'utf8')).classical || {})) && !JSON.stringify(JSON.parse(fs.readFileSync(f('org.pub.json'), 'utf8'))).includes(org.pq.secretKey), 'fisierul public nu are voie sa poarte cheia secreta');
cere(run(['credential', 'issue', '--issuer-keys', f('org.json'), '--issuer-name', 'Example Org', '--subject-pub', f('dev.pub.json'), '--subject-name', 'Ana Dev', '--valid-days', '30', '--out', f('cred.json')]) === 0, 'credential issue');
cere(run(['attest', '--out', f('att.json'), '--keys', f('dev.json'), '--credential', f('cred.json'), A]) === 0, 'attest');
cere(run(['verify', f('att.json'), '--trust-issuer', f('org.pub.json'), A]) === 0, 'verify cu emitentul bun');
cere(run(['verify', f('att.json'), '--trust-issuer', f('alt.pub.json'), A]) === 1, 'CONTROL: verify cu alt emitent');
cere(run(['credential', 'revoke', '--issuer-keys', f('org.json'), '--credential', f('cred.json'), '--at', '2020-01-01T00:00:00Z', '--out', f('rev.json')]) === 0, 'credential revoke');
cere(run(['verify', f('att.json'), '--trust-issuer', f('org.pub.json'), '--revocations', f('rev.json'), A]) === 1, 'CONTROL: verify cu revocarea');
});
await test('12. B-18: cu cheile unei acreditari REVOCATE, o atestare antedatata inaintea revocarii NU mai trece drept nerevocata; cu timpul lantului dupa revocare e prinsa, inainte e trecuta', async () => {
const rev = revokeCredential({ issuerKeys: org, credential: cred, revokedAt: '2026-09-01T00:00:00Z', reason: 'the keys left the company' });
// hotul semneaza in octombrie, declara iunie
const r = await verify(att, [A], { trustIssuer: publicKeysOf(org), revocations: [rev] });
cere(check(r, /not revoked/).pass === null && check(r, /valid at/).pass === null, 'pe data declarata, revocarea si valabilitatea trebuie raportate nejudecate: ' + JSON.stringify(check(r, /not revoked/)));
const a2 = JSON.parse(JSON.stringify(att)); a2.notarization = { block: 7, txHash: '0x' + 'cd'.repeat(32) };
const lant = (iso) => ({ proof: async () => ({ notarized: true, block: 7, txHash: '0x' + 'cd'.repeat(32), firstSeenAt: Date.parse(iso) / 1000, finality: 'post-quantum', pqAnchor: null }) });
const rDupa = await verify(a2, [A], { trustIssuer: publicKeysOf(org), revocations: [rev], cloud: lant('2026-10-02T00:00:00Z') });
cere(!rDupa.valid && check(rDupa, /not revoked/).pass === false, 'lantul a vazut-o dupa revocare: trebuia prinsa');
const rInainte = await verify(a2, [A], { trustIssuer: publicKeysOf(org), revocations: [rev], cloud: lant('2026-06-02T00:00:00Z') });
cere(rInainte.valid && check(rInainte, /not revoked/).pass === true && check(rInainte, /valid at/).pass === true, 'lantul a vazut-o inainte de revocare, in valabilitate: trecuta');
});
fs.rmSync(D, { recursive: true, force: true });
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
process.exitCode = esecuri.length ? 1 : 0;
@@ -0,0 +1,8 @@
module github.com/golang/mock
require (
golang.org/x/mod v0.4.2
golang.org/x/tools v0.1.1
)
go 1.11
@@ -0,0 +1,28 @@
github.com/yuin/goldmark v1.3.5 h1:dPmz1Snjq0kmkz159iL7S6WzdahUTHnHB5M56WFVifs=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs=
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -0,0 +1,10 @@
module aere.network/pqc
go 1.26.5
require (
github.com/cloudflare/circl v1.6.4
golang.org/x/crypto v0.54.0
)
require golang.org/x/sys v0.47.0 // indirect
@@ -0,0 +1,6 @@
github.com/cloudflare/circl v1.6.4 h1:pOXuDTCEYyzydgUpQ0CQz3LsinKjiSk6nNP5Lt5K64U=
github.com/cloudflare/circl v1.6.4/go.mod h1:YxarevkLlbaHuWsxG6vmYNWBEsSp4pnp7j+4VljMavY=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
@@ -0,0 +1,42 @@
// Controlul negativ al probelor de proveninta a modelelor (model.test.mjs): fiecare paznic se strica pe rand IN pos.mjs (importurile
// relative ale lui pos.mjs nu permit o copie in alt dosar), proba tinta TREBUIE sa pice, iar fisierul se pune la loc in `finally` si
// se compara octet cu octet cu originalul. O plantare care nu se aplica e STRICAT, nu rosu.
// node aerenew/tools/proof-of-software/test/model-control-negativ.mjs
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const POS = path.join(AICI, '..', 'pos.mjs');
const original = fs.readFileSync(POS);
const text = original.toString('utf8');
const PLANTARI = [
['fluxul pierde ultima bucata partiala', 'h.update(n === buf.length ? buf : buf.subarray(0, n))', 'if (n === buf.length) h.update(buf)', 'hash in flux'],
['dosarele ascunse intra in model', "if (e.name.startsWith('.')) continue;", "if (e.name.startsWith('.') && false) continue;", 'ML-BOM CycloneDX 1.6'],
['manifestul fara marimi', "randuri.map((r) => `${r.rel}\\t${r.sha}\\t${r.bytes}\\n`)", "randuri.map((r) => `${r.rel}\\t${r.sha}\\n`)", 'digestul manifestului'],
['verificarea fara --base nu mai cere --base', "if (relativ && !base) ok('artifact names', false,", "if (relativ && !base && false) ok('artifact names', false,", 'FARA --base'],
];
let rele = 0;
try {
for (const [nume, vechi, nou, tinta] of PLANTARI) {
if (text.split(vechi).length !== 2) { console.log(` STRICAT ${nume}: ancora apare de ${text.split(vechi).length - 1} ori`); rele++; continue; }
fs.writeFileSync(POS, text.replace(vechi, nou));
const r = spawnSync(process.execPath, [path.join(AICI, 'model.test.mjs')], { encoding: 'utf8' });
const out = (r.stdout || '') + (r.stderr || '');
const rulate = (out.match(/^ (OK|ESEC) /gm) || []).length;
if (rulate < 8) { console.log(` STRICAT ${nume}: au rulat ${rulate} probe din 8`); rele++; continue; }
const picate = out.split('\n').filter((l) => l.startsWith(' ESEC '));
if (picate.some((l) => l.includes(tinta))) console.log(` ROSU cum trebuia ${nume} (${picate.length} esec, intre ele '${tinta}')`);
else { console.log(` CONTROL CAZUT ${nume}: proba '${tinta}' a ramas verde`); rele++; }
}
} finally {
fs.writeFileSync(POS, original);
}
if (!fs.readFileSync(POS).equals(original)) { console.log(' pos.mjs NU a fost pus la loc octet cu octet'); rele++; }
const m = spawnSync(process.execPath, [path.join(AICI, 'model.test.mjs')], { encoding: 'utf8' });
if (!/8 treceri, 0 esecuri/.test(m.stdout || '')) { console.log(' MARTORUL nu e verde'); rele++; } else console.log(' martor: pos.mjs neatins, 8/8 verde');
console.log(rele ? `CONTROL NEGATIV: ${rele} probleme` : `CONTROL NEGATIV TRECUT (${PLANTARI.length} din ${PLANTARI.length} rosii, pos.mjs pus la loc, martorul verde)`);
process.exitCode = rele ? 1 : 0;
+102
View File
@@ -0,0 +1,102 @@
// Proof of Software 1.2.0, proveninta modelelor AI: ML-BOM CycloneDX 1.6, nume relative la --base, hash in flux. Fiecare afirmatie cu
// perechea ei negativa. Offline.
// node aerenew/tools/proof-of-software/test/model.test.mjs
import assert from 'node:assert';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' -> ' + String(e.message || e).slice(0, 240)); } }
// pragul fluxului coborat la 1 KiB INAINTE de import, ca un fisier de 3 MiB sa treaca prin ramura in flux
process.env.AERE_POS_FLUX_PESTE = '1024';
const POS = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'pos.mjs');
const { modelBom, sha256File, attest, verify, buildStatement } = await import('../pos.mjs');
const sha = (b) => '0x' + crypto.createHash('sha256').update(b).digest('hex');
const D = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-model-'));
const M = path.join(D, 'tiny-lm');
fs.mkdirSync(path.join(M, 'tokenizer'), { recursive: true });
fs.mkdirSync(path.join(M, '.cache'));
const shard1 = crypto.randomBytes(3 * 1024 * 1024 + 17), shard2 = crypto.randomBytes(200 * 1024);
fs.writeFileSync(path.join(M, 'config.json'), JSON.stringify({ architectures: ['TinyLMForCausalLM'], model_type: 'tiny_lm', hidden_size: 64 }));
fs.writeFileSync(path.join(M, 'model-00001-of-00002.safetensors'), shard1);
fs.writeFileSync(path.join(M, 'model-00002-of-00002.safetensors'), shard2);
fs.writeFileSync(path.join(M, 'tokenizer', 'config.json'), JSON.stringify({ vocab_size: 512 }));
fs.writeFileSync(path.join(M, 'README.md'), '# tiny-lm\n');
fs.writeFileSync(path.join(M, '.cache', 'ignored.bin'), 'not part of the model');
const DATE = path.join(D, 'train.jsonl'); fs.writeFileSync(DATE, '{"text":"hello"}\n{"text":"world"}\n');
await test('hash in flux (fisier de 3 MiB peste pragul de 1 KiB) = hash-ul intregului fisier, calculat independent', () => {
assert.strictEqual(sha256File(path.join(M, 'model-00001-of-00002.safetensors')), sha(shard1));
assert.strictEqual(sha256File(path.join(M, 'model-00002-of-00002.safetensors')), sha(shard2));
});
const { bom, files, manifestSha256 } = modelBom({ dir: M, name: 'tiny-lm', version: '0.1', task: 'text-generation', datasets: ['train=' + DATE] });
await test('ML-BOM CycloneDX 1.6: componenta machine-learning-model, arhitectura din config.json, fiecare fisier cu SHA-256 corect, dosarul ascuns sarit', () => {
assert.deepStrictEqual([bom.bomFormat, bom.specVersion, bom.version], ['CycloneDX', '1.6', 1]);
assert.match(bom.serialNumber, /^urn:uuid:[0-9a-f-]{36}$/);
const m = bom.metadata.component;
assert.deepStrictEqual([m.type, m['bom-ref'], m.name, m.version], ['machine-learning-model', 'model', 'tiny-lm', '0.1']);
assert.deepStrictEqual(m.modelCard.modelParameters, { task: 'text-generation', architectureFamily: 'tiny_lm', modelArchitecture: 'TinyLMForCausalLM', datasets: [{ ref: 'data:train' }] });
const fisiere = bom.components.filter((c) => c.type === 'file');
assert.deepStrictEqual(fisiere.map((c) => c.name), ['README.md', 'config.json', 'model-00001-of-00002.safetensors', 'model-00002-of-00002.safetensors', 'tokenizer/config.json']);
assert.strictEqual(fisiere.find((c) => c.name === 'model-00001-of-00002.safetensors').hashes[0].content, sha(shard1).slice(2));
assert.ok(!bom.components.some((c) => /ignored/.test(c.name)), 'dosarul ascuns .cache a intrat in model');
const refs = bom.components.map((c) => c['bom-ref']); assert.strictEqual(new Set(refs).size, refs.length, 'bom-ref duplicat');
assert.deepStrictEqual(bom.dependencies[0].dependsOn.sort(), refs.sort());
const d = bom.components.find((c) => c.type === 'data'); assert.strictEqual(d.hashes[0].content, sha(fs.readFileSync(DATE)).slice(2));
assert.strictEqual(files.length, 5);
});
await test('digestul manifestului se reface din regula scrisa in BOM, si se schimba la un octet atins (pereche negativa)', () => {
const linii = bom.components.filter((c) => c.type === 'file').map((c) => `${c.name}\t0x${c.hashes[0].content}\t${c.properties[0].value}\n`).join('');
assert.strictEqual(sha(Buffer.from(linii, 'utf8')), manifestSha256);
assert.strictEqual(bom.metadata.component.properties.find((p) => p.name === 'aere:manifestSha256').value, manifestSha256);
const b = Buffer.from(shard2); b[7] ^= 1; const alt = path.join(D, 'alt'); fs.cpSync(M, alt, { recursive: true });
fs.writeFileSync(path.join(alt, 'model-00002-of-00002.safetensors'), b);
assert.notStrictEqual(modelBom({ dir: alt }).manifestSha256, manifestSha256);
});
await test('fara --base doua config.json se ciocnesc (refuz cu indicatia --base); cu --base au nume relative distincte', () => {
assert.throws(() => buildStatement({ artifacts: files, cwd: D }), /share the name .*use --base/);
const s = buildStatement({ artifacts: files, base: M, cwd: D });
assert.strictEqual(s.artifactNames, 'relative-path');
assert.deepStrictEqual(s.artifacts.map((a) => a.name).sort(), ['README.md', 'config.json', 'model-00001-of-00002.safetensors', 'model-00002-of-00002.safetensors', 'tokenizer/config.json']);
assert.throws(() => buildStatement({ artifacts: [DATE], base: M, cwd: D }), /not inside --base/);
});
const BOMF = path.join(D, 'mlbom.json'); fs.writeFileSync(BOMF, JSON.stringify(bom));
const att = await attest({ artifacts: files, base: M, sbom: BOMF, name: 'tiny-lm', version: '0.1', cwd: D });
await test('atestare cu --base + ML-BOM, verificare cu --base: VALID', async () => {
const r = await verify(att, [...files, BOMF], { base: M });
assert.ok(r.valid, JSON.stringify(r.checks.filter((c) => c.pass === false)));
assert.ok(r.checks.some((c) => c.name === 'sbom mlbom.json: sha256 matches' && c.pass === true));
});
await test('un octet schimbat intr-o greutate: INVALID, cu numele fisierului; o greutate lipsa: INVALID (lipsa nu e valida)', async () => {
const cop = path.join(D, 'copie'); fs.cpSync(M, cop, { recursive: true });
const b = Buffer.from(shard1); b[b.length - 1] ^= 1; fs.writeFileSync(path.join(cop, 'model-00001-of-00002.safetensors'), b);
const fis = files.map((p) => path.join(cop, path.relative(M, p)));
const r = await verify(att, [...fis, BOMF], { base: cop });
assert.strictEqual(r.valid, false);
assert.ok(r.checks.some((c) => c.pass === false && c.name === 'artifact model-00001-of-00002.safetensors: sha256 and size match'), JSON.stringify(r.checks.filter((c) => c.pass === false)));
const r2 = await verify(att, [...files.filter((p) => !/00002/.test(p)), BOMF], { base: M });
assert.strictEqual(r2.valid, false); assert.ok(r2.checks.some((c) => c.pass === false && /00002.*present/.test(c.name)));
});
await test('o atestare cu nume relative verificata FARA --base: INVALID cu motivul numit (nu potrivire pe bazenume)', async () => {
const r = await verify(att, [...files, BOMF], {});
assert.strictEqual(r.valid, false); assert.ok(r.checks.some((c) => c.pass === false && /pass --base/.test(c.detail)), JSON.stringify(r.checks.filter((c) => c.pass === false)).slice(0, 300));
});
await test('CLI: model-bom scrie fisierul si numara fisierele; un --dataset fara NUME=FISIER e refuzat', () => {
const out = path.join(D, 'cli-mlbom.json');
const t = execFileSync(process.execPath, [POS, 'model-bom', '--model-dir', M, '--out', out, '--name', 'tiny-lm'], { encoding: 'utf8' });
assert.match(t, /ML-BOM written to .*: 5 file\(s\), 0 dataset\(s\)/);
assert.strictEqual(JSON.parse(fs.readFileSync(out, 'utf8')).metadata.component.type, 'machine-learning-model');
let refuz = ''; try { execFileSync(process.execPath, [POS, 'model-bom', '--model-dir', M, '--out', out, '--dataset', 'fara-egal'], { encoding: 'utf8', stdio: 'pipe' }); } catch (e) { refuz = String(e.stderr); }
assert.match(refuz, /--dataset takes NAME=FILE/);
});
fs.rmSync(D, { recursive: true, force: true });
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
process.exitCode = esecuri.length ? 1 : 0;
+150
View File
@@ -0,0 +1,150 @@
// Proof of Software: fiecare afirmatie cu perechea ei negativa. Offline; cu AERE_SCRIE=1 si AERE_CHEIE_FISIER face o
// notarizare reala (o tranzactie pe 2800) si citeste dovada ei.
import assert from 'node:assert';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { attest, verify, buildStatement, packNpmFromTree } from '../pos.mjs';
import * as pq from '../../../sdk-pq-sign/index.mjs';
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' — ' + (e.message || e)); } }
const D = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-'));
const A = path.join(D, 'app.tgz'), B = path.join(D, 'app.sha'), S = path.join(D, 'sbom.json');
fs.writeFileSync(A, Buffer.from('binary artifact bytes 12345')); fs.writeFileSync(B, 'checksums'); fs.writeFileSync(S, JSON.stringify({ bomFormat: 'CycloneDX', components: [] }));
const keys = pq.generateKeyPair({ alg: 'secp256k1+ml-dsa-65' });
await test('statement: artifacts with sha256 + size, sbom hashed, builder, time', () => {
const s = buildStatement({ artifacts: [A, B], sbom: S, name: 'app', version: '1.0.0', cwd: D });
assert.strictEqual(s.artifacts.length, 2); assert.match(s.artifacts[0].sha256, /^0x[0-9a-f]{64}$/); assert.strictEqual(s.artifacts[0].bytes, 27);
assert.strictEqual(s.sbom.name, 'sbom.json'); assert.strictEqual(s.subject.version, '1.0.0'); assert.ok(s.createdAt);
});
await test('two artifacts with the same name are refused (verification matches by name)', () => {
const D2 = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-')); fs.mkdirSync(path.join(D2, 'x')); fs.writeFileSync(path.join(D2, 'x', 'app.tgz'), 'a');
assert.throws(() => buildStatement({ artifacts: [A, path.join(D2, 'x', 'app.tgz')], cwd: D }), /share the name/);
});
const att = await attest({ artifacts: [A, B], sbom: S, name: 'app', version: '1.0.0', keys, cwd: D });
await test('attest + verify with the same files: VALID, signature both halves, on chain absent (reported, not assumed)', async () => {
const r = await verify(att, [A, B, S]);
assert.strictEqual(r.valid, true, JSON.stringify(r.checks));
assert.ok(r.checks.find((c) => c.name.startsWith('hybrid signature') && c.pass === true));
assert.ok(r.checks.find((c) => c.name === 'on chain' && c.pass === null));
});
await test('a tampered artifact (one byte) makes verification INVALID', async () => {
const T = path.join(D, 'app.tgz.tampered'); fs.mkdirSync(path.join(D, 't'), { recursive: true }); const T2 = path.join(D, 't', 'app.tgz');
fs.writeFileSync(T2, Buffer.from('binary artifact bytes 12346'));
const r = await verify(att, [T2, B, S]); assert.strictEqual(r.valid, false); assert.ok(r.checks.find((c) => c.name.includes('app.tgz') && c.pass === false));
});
await test('a missing artifact is INVALID (absent artifact is a failure, absent SBOM is only reported)', async () => {
const r = await verify(att, [A]); assert.strictEqual(r.valid, false);
assert.ok(r.checks.find((c) => c.name.includes('app.sha') && c.pass === false));
assert.ok(r.checks.find((c) => c.name.startsWith('sbom') && c.pass === null));
});
await test('an edited statement (version changed) breaks statementHash and the signature', async () => {
const e = JSON.parse(JSON.stringify(att)); e.statement.subject.version = '1.0.1';
const r = await verify(e, [A, B, S]); assert.strictEqual(r.valid, false);
assert.ok(r.checks.find((c) => c.name.startsWith('statementHash') && c.pass === false));
assert.ok(r.checks.find((c) => c.name.startsWith('hybrid signature') && c.pass === false));
});
await test('a flipped bit in the post-quantum half of the signature is INVALID', async () => {
const e = JSON.parse(JSON.stringify(att)); const b = pq.fromHex(e.signature.pqSignature); b[5] ^= 1; e.signature.pqSignature = pq.toHex(b);
const r = await verify(e, [A, B, S]); assert.strictEqual(r.valid, false);
});
await test('without keys: no signature, still VALID on digests alone, signature reported absent', async () => {
const a2 = await attest({ artifacts: [A], cwd: D }); const r = await verify(a2, [A]);
assert.strictEqual(r.valid, true); assert.ok(r.checks.find((c) => c.name === 'hybrid signature' && c.pass === null));
});
await test('CLI: keygen, attest, verify round trip through files; tampered file fails with exit 1', () => {
const pos = path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..', 'pos.mjs');
const K = path.join(D, 'keys.json'), O = path.join(D, 'attestation.json');
execFileSync('node', [pos, 'keygen', '--out', K, '--alg', 'ed25519+ml-dsa-44'], { stdio: 'pipe' });
const out = execFileSync('node', [pos, 'attest', '--out', O, '--name', 'app', '--version', '2', '--sbom', S, '--keys', K, A, B], { stdio: 'pipe' }).toString();
assert.match(out, /signature ed25519\+ml-dsa-44/);
const v = execFileSync('node', [pos, 'verify', O, A, B, S], { stdio: 'pipe' }).toString(); assert.match(v, /VALID: every present claim holds/);
let code = 0; try { execFileSync('node', [pos, 'verify', O, path.join(D, 't', 'app.tgz'), B, S], { stdio: 'pipe' }); } catch (e) { code = e.status; }
assert.strictEqual(code, 1);
});
// ---- legarea de ARBORELE git si verificarea prin RECONSTRUCTIE (1.1.0). Un depozit de proba cu un pachet npm mic.
const G = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-git-'));
const g = (args, cwd = G) => execFileSync('git', ['-c', 'core.autocrlf=false', '-c', 'user.name=proba', '-c', '[email protected]', ...args], { cwd, stdio: 'pipe' }).toString().trim();
g(['init', '-q']); fs.mkdirSync(path.join(G, 'pkg', 'lib'), { recursive: true }); fs.mkdirSync(path.join(G, 'altceva'));
fs.writeFileSync(path.join(G, 'pkg', 'package.json'), JSON.stringify({ name: 'proba-pos', version: '0.0.1', main: 'lib/index.js', files: ['lib', 'LICENSE'] }, null, 1) + '\n');
fs.writeFileSync(path.join(G, 'pkg', 'lib', 'index.js'), 'module.exports = 1;\n'); fs.writeFileSync(path.join(G, 'pkg', 'LICENSE'), 'line one\nline two\n');
fs.writeFileSync(path.join(G, 'altceva', 'x.txt'), 'nu face parte din pachet\n');
g(['add', '-A']); g(['commit', '-q', '-m', 'pachet de proba']);
const OUT1 = path.join(G, '..', path.basename(G) + '-out'); fs.mkdirSync(OUT1);
const TGZ = packNpmFromTree(G, 'HEAD:pkg', OUT1);
await test('source tree: --source-path records path, tree and pathDirty; build records npm-pack and the npm version', () => {
const s = buildStatement({ artifacts: [TGZ], sourcePath: 'pkg', build: 'npm-pack', cwd: G });
assert.strictEqual(s.source.path, 'pkg'); assert.strictEqual(s.source.tree, g(['rev-parse', 'HEAD:pkg'])); assert.strictEqual(s.source.pathDirty, false);
assert.strictEqual(s.build.kind, 'npm-pack'); assert.match(s.build.npm, /^\d+\./);
assert.throws(() => buildStatement({ artifacts: [TGZ], sourcePath: 'nu-exista', cwd: G }), /not tracked at HEAD/);
});
await test('the listing of a tree does not depend on the directory it is asked from (ls-tree --full-tree)', () => {
const o = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-sub-'));
const t2 = packNpmFromTree(path.join(G, 'altceva'), 'HEAD:pkg', o);
assert.strictEqual(fs.readFileSync(t2).equals(fs.readFileSync(TGZ)), true, 'same tree asked from a subdirectory gave other bytes');
});
await test('the artifact is a function of the COMMITTED tree: CRLF in the working copy changes a working-copy pack, not this one', () => {
fs.writeFileSync(path.join(G, 'pkg', 'LICENSE'), 'line one\r\nline two\r\n');
const o = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-crlf-'));
const again = packNpmFromTree(G, 'HEAD:pkg', o);
assert.strictEqual(fs.readFileSync(again).equals(fs.readFileSync(TGZ)), true);
const wc = execFileSync('npm pack --silent --pack-destination "' + o + '"', { cwd: path.join(G, 'pkg'), shell: true, stdio: 'pipe' }).toString().trim().split(/\r?\n/).pop();
fs.renameSync(path.join(o, wc), path.join(o, 'din-copia-de-lucru.tgz'));
assert.strictEqual(fs.readFileSync(path.join(o, 'din-copia-de-lucru.tgz')).equals(fs.readFileSync(TGZ)), false, 'control: the working-copy pack should differ');
fs.writeFileSync(path.join(G, 'pkg', 'LICENSE'), 'line one\nline two\n');
});
const attG = await attest({ artifacts: [TGZ], name: 'proba-pos', version: '0.0.1', sourcePath: 'pkg', build: 'npm-pack', keys, cwd: G });
await test('verify --rebuild-from: a clone chosen by the verifier reproduces the attested artifact byte for byte', async () => {
const C = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-clona-')); g(['clone', '-q', G, C], os.tmpdir());
const r = await verify(attG, [TGZ], { rebuildFrom: C });
assert.strictEqual(r.valid, true, JSON.stringify(r.checks));
assert.ok(r.checks.find((c) => c.name.startsWith('rebuild: npm pack of the attested tree reproduces') && c.pass === true));
const r0 = await verify(attG, [TGZ]); assert.ok(r0.checks.find((c) => c.name === 'rebuild' && c.pass === null), 'without --rebuild-from the rebuild is reported as not attempted');
});
await test('an artifact that did NOT come from the attested tree fails the rebuild (digest differs), though its own digest matches', async () => {
fs.writeFileSync(path.join(G, 'pkg', 'lib', 'index.js'), 'module.exports = 2; // schimbat si necomis\n');
const o = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-strain-'));
const wc = execFileSync('npm pack --silent --pack-destination "' + o + '"', { cwd: path.join(G, 'pkg'), shell: true, stdio: 'pipe' }).toString().trim().split(/\r?\n/).pop();
const strain = path.join(o, wc);
const a = await attest({ artifacts: [strain], sourcePath: 'pkg', build: 'npm-pack', cwd: G });
assert.strictEqual(a.statement.source.pathDirty, true, 'the statement itself says the path was dirty');
const plain = await verify(a, [strain]); assert.strictEqual(plain.valid, true, 'digests alone hold: that is why the rebuild matters');
const r = await verify(a, [strain], { rebuildFrom: G }); assert.strictEqual(r.valid, false);
assert.ok(r.checks.find((c) => c.name.startsWith('rebuild: npm pack of the attested tree reproduces') && c.pass === false && /got 0x/.test(c.detail)));
g(['checkout', '-q', '--', 'pkg/lib/index.js']);
});
await test('a clone that does not hold the attested commit fails on the SOURCE check, before any build', async () => {
const E = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-gol-')); g(['init', '-q'], E); fs.writeFileSync(path.join(E, 'a'), 'a'); g(['add', '-A'], E); g(['commit', '-q', '-m', 'alt depozit'], E);
const r = await verify(attG, [TGZ], { rebuildFrom: E }); assert.strictEqual(r.valid, false);
assert.ok(r.checks.find((c) => c.name.startsWith('source:') && c.pass === false && /not in this clone/.test(c.detail)));
assert.ok(!r.checks.find((c) => c.name.startsWith('rebuild: npm pack')), 'no build was attempted');
});
await test('a statement without a source tree cannot be rebuilt, and asking for it is INVALID, not silently skipped', async () => {
const r = await verify(att, [A, B, S], { rebuildFrom: G }); assert.strictEqual(r.valid, false);
assert.ok(r.checks.find((c) => c.name === 'rebuild: the statement names a source tree' && c.pass === false));
});
const CHEIE_F = process.env.AERE_CHEIE_FISIER;
if (process.env.AERE_SCRIE === '1' && CHEIE_F) {
const { AereCloud } = await import('../../../sdk/index.mjs');
const cloud = new AereCloud({ apiKey: fs.readFileSync(CHEIE_F, 'utf8').trim() });
await test('LIVE: attest with notarization on chain 2800, then verify reads the proof (notarized, receipt matches)', async () => {
const a = await attest({ artifacts: [A, B], sbom: S, name: 'app', version: 'live', keys, cloud, cwd: D });
assert.ok(a.notarization && a.notarization.txHash && a.notarization.block > 0, JSON.stringify(a.notarization));
await new Promise((r) => setTimeout(r, 4000));
const r = await verify(a, [A, B, S], { cloud });
assert.strictEqual(r.valid, true, JSON.stringify(r.checks));
assert.ok(r.checks.find((c) => c.name === 'on chain: statementHash is notarized' && c.pass === true));
console.log(' ' + r.checks.filter((c) => c.name.startsWith('on chain')).map((c) => c.name).join(' | '));
});
} else console.log(' (sarit) notarizarea reala: AERE_SCRIE=1 si AERE_CHEIE_FISIER=<fisier> (scrie o tranzactie pe 2800)');
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
if (esecuri.length) process.exitCode = 1;
@@ -0,0 +1,10 @@
// Controlul negativ al SBOM-ului re-derivat din lockfile-ul comis (sbom.test.mjs), prin mecanismul comun din _control.mjs.
// node aerenew/tools/proof-of-software/test/sbom-control-negativ.mjs
import { controleaza } from './_control.mjs';
process.exitCode = controleaza('sbom.test.mjs', [
['comparatia SBOM-ului cu lockfile-ul scoasa', 'const aceleasi = JSON.stringify(a) === JSON.stringify(b);', 'const aceleasi = true;', 'CONTROL: o componenta scoasa'],
// ancora pe partea STABILA a randului (1.4.0 i-a adaugat `props` la coada si ancora veche a murit: STRICAT, prins de chiar acest control)
['hash-urile de integritate scoase din forma semantica', "hashes: (c.hashes || []).map((h) => `${h.alg}:${String(h.content).toLowerCase()}`).sort(),", 'hashes: [],', 'CONTROL: un hash de integritate'],
['un arbore fara lockfile trecut drept re-derivat', "if (!fs.existsSync(path.join(src, 'package-lock.json'))) return { lipsa:", "if (false) return { lipsa:", 'fara package-lock'],
]);
@@ -0,0 +1,14 @@
// Controlul negativ al SBOM-ului Go (sbom-go.test.mjs, Proof of Software 1.4.0), prin mecanismul comun din _control.mjs: fiecare
// paznic scos intr-o copie a lui pos.mjs trebuie sa inroseasca EXACT proba lui, cu suita chiar rulata.
// node aerenew/tools/proof-of-software/test/sbom-go-control-negativ.mjs
import { controleaza } from './_control.mjs';
process.exitCode = controleaza('sbom-go.test.mjs', [
['hash-ul h1 scos din forma semantica', 'props: aere(c.properties) });', 'props: [] });', 'CONTROL: un hash h1 schimbat'],
['SBOM-ul Go judecat ca unul npm', 'const go = esteSbomGo(atestat);', 'const go = false;', 'verify --rebuild-from: arborele e cel atestat'],
['o atestare fara npm pack declarata falsa la reconstructie (forma 1.3.0)', "checks.push({ name: 'rebuild: artifacts', pass: null, detail:", "checks.push({ name: 'rebuild: artifacts', pass: false, detail:", 'verify --rebuild-from: arborele e cel atestat'],
['modulele fixate numai prin go.mod listate drept componente', '.filter((e) => e.h1).map((e) => {', '.filter((e) => true).map((e) => {', 'gomock: numai modulele cu continut'],
['un arbore fara go.sum trecut drept re-derivat', "const goSum = blob('go.sum'); if (goSum == null) return { lipsa:", "const goSum = blob('go.sum') ?? ''; if (false) return { lipsa:", 'un arbore fara go.sum'],
['numarul de serie aleator (SBOM-ul nu mai e determinist)', 'const b = crypto.createHash(\'sha256\').update(JSON.stringify({ metadata, components })).digest();', 'const b = crypto.randomBytes(32);', 'determinist'],
['radacina scoasa din comparatie', 'return { radacina: radacina && radacina.purl, meta:', 'return { radacina: null, meta:', 'CONTROL: SBOM-ul spune alt modul radacina'],
]);
@@ -0,0 +1,111 @@
// Proof of Software 1.4.0: SBOM-ul unui modul Go, derivat determinist din go.mod si go.sum COMISE, si judecat la verify --rebuild-from.
// Fixturile sunt fisiere REALE, scrise de unealta Go: go.mod/go.sum din sdk-go (al nostru) si din github.com/golang/[email protected] (din
// memoria de module a lui Go, un go.sum cu multe module fixate numai prin go.mod). Fiecare afirmatie cu perechea ei negativa. Offline.
// node test/sbom-go.test.mjs iesire 0 = toate cum trebuia
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { attest, verify, sbomGo, sbomGoFromTree, sbomSemantica } from '../pos.mjs';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const POS = path.resolve(AICI, '..', 'pos.mjs');
const FX = path.join(AICI, 'fixturi-go');
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' — ' + (e.message || e)); } }
const cere = (c, m) => { if (!c) throw new Error(m); };
const g = (args, cwd) => execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
const check = (r, re) => r.checks.find((c) => re.test(c.name));
const citeste = (d) => ({ goMod: fs.readFileSync(path.join(FX, d, 'go.mod'), 'utf8'), goSum: fs.readFileSync(path.join(FX, d, 'go.sum'), 'utf8') });
const SDK = citeste('sdk-go'), MOCK = citeste('gomock');
const bSdk = sbomGo({ ...SDK, version: 'v1.0.0' }), bMock = sbomGo({ ...MOCK, version: 'v1.6.0' });
const prop = (c, n) => ((c.properties || []).find((x) => x.name === n) || {}).value;
await test('sdk-go: trei module cu continut fixat in go.sum, cu purl pkg:golang si hash-ul h1 ca proprietate; radacina din go.mod', () => {
cere(bSdk.components.length === 3, 'componente: ' + bSdk.components.length);
cere(bSdk.components.map((c) => c.purl).join(' ') === 'pkg:golang/github.com/cloudflare/[email protected] pkg:golang/golang.org/x/[email protected] pkg:golang/golang.org/x/[email protected]', bSdk.components.map((c) => c.purl).join(' '));
cere(bSdk.metadata.component.purl === 'pkg:golang/aere.network/[email protected]', bSdk.metadata.component.purl);
cere(bSdk.components.every((c) => /^h1:[A-Za-z0-9+/]{43}=$/.test(prop(c, 'aere:go-sum-h1')) && !(c.hashes || []).length), 'h1 ca proprietate, fara hashes SHA-256');
});
await test('gomock: numai modulele cu continut fixat sunt componente; cele fixate numai prin go.mod se numara (numaratoare independenta)', () => {
// numaratoarea independenta, alt cod decat cel masurat: perechi distincte "modul versiune", cu si fara randul de continut
const randuri = MOCK.goSum.split('\n').filter(Boolean).map((l) => l.split(' '));
const cuContinut = new Set(randuri.filter((r) => !r[1].endsWith('/go.mod')).map((r) => r[0] + ' ' + r[1]));
const toate = new Set(randuri.map((r) => r[0] + ' ' + r[1].replace(/\/go\.mod$/, '')));
cere(bMock.components.length === cuContinut.size && cuContinut.size === 5, `componente ${bMock.components.length}, asteptat ${cuContinut.size}`);
cere(Number(prop(bMock.metadata, 'aere:go-sum-go-mod-only')) === toate.size - cuContinut.size && toate.size - cuContinut.size > 10, `numai go.mod: ${prop(bMock.metadata, 'aere:go-sum-go-mod-only')} fata de ${toate.size - cuContinut.size}`);
cere(bMock.components.some((c) => c.purl === 'pkg:golang/golang.org/x/[email protected]'), 'x/tools v0.1.1 lipseste');
});
await test('determinist: aceleasi fisiere dau aceiasi octeti (fara timp; numarul de serie e UUID derivat din continut)', () => {
const alt = sbomGo({ ...SDK, version: 'v1.0.0' });
cere(JSON.stringify(alt) === JSON.stringify(bSdk), 'doua derivari difera');
cere(/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(bSdk.serialNumber), bSdk.serialNumber);
cere(sbomGo({ ...SDK, version: 'v1.0.1' }).serialNumber !== bSdk.serialNumber, 'CONTROL: alta versiune, alt numar de serie');
});
await test('CONTROL POZITIV al metodei: hash-ul h1 citit din go.sum e chiar cel pe care Go l-a calculat la descarcarea modulului', () => {
const cache = (() => { try { return execFileSync('go', ['env', 'GOMODCACHE'], { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim(); } catch { return null; } })();
const perechi = bSdk.components.map((c) => ({ c, f: cache && path.join(cache, 'cache', 'download', ...c.name.split('/'), '@v', c.version + '.ziphash') })).filter((x) => x.f && fs.existsSync(x.f));
if (!perechi.length) { console.log(' SARIT (nicio arhiva a acestor module in memoria de module Go de pe aceasta masina)'); return; }
for (const { c, f } of perechi) cere(fs.readFileSync(f, 'utf8').trim() === prop(c, 'aere:go-sum-h1'), `${c.name}: ${fs.readFileSync(f, 'utf8').trim()} fata de ${prop(c, 'aere:go-sum-h1')}`);
console.log(` (${perechi.length} din ${bSdk.components.length} module comparate cu memoria de module Go)`);
});
await test('CONTROL: un rand de go.sum care nu are forma lui, sau un go.mod fara modul -> refuzat, nu ghicit', () => {
let e1 = null; try { sbomGo({ goMod: SDK.goMod, goSum: SDK.goSum + 'rand stricat\n', version: 'v1' }); } catch (e) { e1 = e.message; }
let e2 = null; try { sbomGo({ goMod: 'go 1.21\n', goSum: SDK.goSum, version: 'v1' }); } catch (e) { e2 = e.message; }
cere(/go.sum line \d+/.test(e1 || '') && /names no module/.test(e2 || ''), `${e1} | ${e2}`);
});
// fluxul intreg, intr-un depozit git temporar: SBOM-ul scris de `sbom-go` din arborele comis, atestat, verificat cu --rebuild-from
const G = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-go-g-'));
g(['init', '-q'], G); g(['config', 'user.email', '[email protected]'], G); g(['config', 'user.name', 'proba'], G); g(['config', 'core.autocrlf', 'false'], G);
const M = path.join(G, 'mod'); fs.mkdirSync(M, { recursive: true });
fs.writeFileSync(path.join(M, 'go.mod'), SDK.goMod); fs.writeFileSync(path.join(M, 'go.sum'), SDK.goSum);
fs.writeFileSync(path.join(M, 'main.go'), 'package main\n\nfunc main() {}\n');
fs.mkdirSync(path.join(G, 'fara'), { recursive: true }); fs.writeFileSync(path.join(G, 'fara', 'go.mod'), 'module example.com/fara\n\ngo 1.21\n');
g(['add', '-A'], G); g(['commit', '-q', '-m', 'modul de proba'], G);
const C = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-go-c-')); g(['clone', '-q', G, C], os.tmpdir());
const OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-go-o-'));
const BIN = path.join(OUT, 'app-linux-amd64'); fs.writeFileSync(BIN, 'binarul construit altfel decat cu npm pack');
const S = path.join(OUT, 'app.sbom.cdx.json');
const cli = execFileSync(process.execPath, [POS, 'sbom-go', '--source-path', 'mod', '--version', 'v1.0.0', '--out', S], { cwd: G, stdio: ['ignore', 'pipe', 'pipe'] }).toString();
const att = await attest({ artifacts: [BIN], sbom: S, name: 'app', version: 'v1.0.0', sourcePath: 'mod', cwd: G });
await test('sbom-go (linia de comanda) scrie din arborele COMIS exact SBOM-ul pe care il re-deriva verificarea', () => {
const r = sbomGoFromTree(G, g(['rev-parse', 'HEAD'], G), 'mod', 'v1.0.0');
cere(/3 module\(s\) pinned/.test(cli), cli);
cere(fs.readFileSync(S, 'utf8') === JSON.stringify(r.bom, null, 1) + '\n', 'fisierul scris difera de derivarea din arbore');
});
await test('verify --rebuild-from: arborele e cel atestat, SBOM-ul spune ce fixeaza go.sum-ul comis, iar artefactele nereconstruite sunt ABSENTE, nu false (VALID)', async () => {
const r = await verify(att, [BIN, S], { rebuildFrom: C });
const sb = check(r, /attested SBOM says what the committed go.sum pins/), art = check(r, /^rebuild: artifacts$/);
cere(r.valid && sb && sb.pass === true && art && art.pass === null, JSON.stringify(r.checks.filter((c) => c.pass !== true)));
});
async function editat(nume, schimba) {
const bom = JSON.parse(fs.readFileSync(S, 'utf8')); schimba(bom);
const d = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-go-e-')); const f = path.join(d, 'app.sbom.cdx.json'); fs.writeFileSync(f, JSON.stringify(bom, null, 1));
const a = await attest({ artifacts: [BIN], sbom: f, name: 'app', version: 'v1.0.0', sourcePath: 'mod', cwd: G });
const simplu = await verify(a, [BIN, f]);
const r = await verify(a, [BIN, f], { rebuildFrom: C });
fs.rmSync(d, { recursive: true, force: true });
cere(simplu.valid, `${nume}: fara reconstructie, digestul singur trece (de asta conteaza comparatia)`);
const sb = check(r, /attested SBOM says/);
cere(!r.valid && sb && sb.pass === false, `${nume}: trebuia prins; ${JSON.stringify(sb)}`);
}
await test('CONTROL: un modul scos din SBOM de mana, re-atestat -> prins la reconstructie', () => editat('scos', (b) => { b.components = b.components.filter((c) => !/circl/.test(c.name)); }));
await test('CONTROL: o versiune schimbata in SBOM (si purl-ul ei) -> prins', () => editat('versiune', (b) => { const c = b.components.find((x) => /x\/sys/.test(x.name)); c.version = 'v0.48.0'; c.purl = c.purl.replace('v0.47.0', 'v0.48.0'); c['bom-ref'] = c.purl; }));
await test('CONTROL: un hash h1 schimbat in SBOM -> prins', () => editat('h1', (b) => { const c = b.components[0]; c.properties = [{ name: 'aere:go-sum-h1', value: 'h1:' + 'A'.repeat(43) + '=' }]; }));
await test('CONTROL: SBOM-ul spune alt modul radacina decat go.mod-ul comis -> prins', () => editat('radacina', (b) => { b.metadata.component.name = 'example.com/altul'; b.metadata.component.purl = 'pkg:golang/example.com/[email protected]'; }));
await test('un arbore fara go.sum comis: SBOM-ul nu se poate re-deriva, si se spune (nu e trecut drept VALID)', () => {
const r = sbomGoFromTree(G, g(['rev-parse', 'HEAD'], G), 'fara', 'v1');
cere(!r.bom && /no go.sum/.test(r.lipsa || ''), JSON.stringify(r).slice(0, 120));
});
await test('forma semantica: un SBOM npm (fara proprietati aere:) e judecat ca inainte; un SBOM Go poarta h1 in comparatie', () => {
const npm = { metadata: { component: { purl: 'pkg:npm/x@1' } }, components: [{ purl: 'pkg:npm/a@1', hashes: [{ alg: 'SHA-512', content: 'AB' }], properties: [{ name: 'cdx:npm:package:path', value: 'node_modules/a' }] }] };
cere(JSON.stringify(sbomSemantica(npm).componente[0].props) === '[]', 'proprietatile npm nu intra');
cere(sbomSemantica(bSdk).componente.every((c) => c.props.length === 1), 'fiecare componenta Go are h1 in forma semantica');
});
for (const d of [G, C, OUT]) fs.rmSync(d, { recursive: true, force: true });
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
process.exitCode = esecuri.length ? 1 : 0;
@@ -0,0 +1,83 @@
// Proof of Software 1.3.0: SBOM-ul atestat e judecat fata de lockfile-ul COMIS (verify --rebuild-from). Fiecare afirmatie cu perechea
// ei negativa. Offline: un depozit git temporar cu un pachet si un package-lock.json scris aici; `npm sbom --package-lock-only` nu
// cere retea.
// node test/sbom.test.mjs iesire 0 = toate cum trebuia
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { attest, verify, packNpmFromTree, sbomSemantica, sbomNpmFromTree } from '../pos.mjs';
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' — ' + (e.message || e)); } }
const cere = (c, m) => { if (!c) throw new Error(m); };
const g = (args, cwd) => execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
const check = (r, re) => r.checks.find((c) => re.test(c.name));
const G = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-sbom-g-'));
g(['init', '-q'], G); g(['config', 'user.email', '[email protected]'], G); g(['config', 'user.name', 'proba'], G); g(['config', 'core.autocrlf', 'false'], G);
const P = path.join(G, 'pkg'); fs.mkdirSync(path.join(P, 'lib'), { recursive: true });
fs.writeFileSync(path.join(P, 'package.json'), JSON.stringify({ name: 'proba-sbom', version: '0.1.0', license: 'MIT', main: 'lib/index.js', dependencies: { 'dep-a': '1.0.0', 'dep-b': '2.0.0' } }, null, 2) + '\n');
fs.writeFileSync(path.join(P, 'lib', 'index.js'), 'module.exports = 1;\n');
const integ = (s) => 'sha512-' + Buffer.from(s.padEnd(64, 'x')).toString('base64');
const lock = {
name: 'proba-sbom', version: '0.1.0', lockfileVersion: 3, requires: true,
packages: {
'': { name: 'proba-sbom', version: '0.1.0', license: 'MIT', dependencies: { 'dep-a': '1.0.0', 'dep-b': '2.0.0' } },
'node_modules/dep-a': { version: '1.0.0', resolved: 'https://registry.npmjs.org/dep-a/-/dep-a-1.0.0.tgz', integrity: integ('dep-a-1.0.0'), license: 'MIT', dependencies: { 'dep-c': '3.0.0' } },
'node_modules/dep-b': { version: '2.0.0', resolved: 'https://registry.npmjs.org/dep-b/-/dep-b-2.0.0.tgz', integrity: integ('dep-b-2.0.0'), license: 'MIT' },
'node_modules/dep-c': { version: '3.0.0', resolved: 'https://registry.npmjs.org/dep-c/-/dep-c-3.0.0.tgz', integrity: integ('dep-c-3.0.0'), license: 'ISC' },
},
};
fs.writeFileSync(path.join(P, 'package-lock.json'), JSON.stringify(lock, null, 2) + '\n');
// un al doilea pachet, FARA lockfile comis
fs.mkdirSync(path.join(G, 'fara'), { recursive: true });
fs.writeFileSync(path.join(G, 'fara', 'package.json'), JSON.stringify({ name: 'fara-lock', version: '0.0.1', license: 'MIT' }) + '\n');
g(['add', '-A'], G); g(['commit', '-q', '-m', 'pachet de proba'], G);
const C = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-sbom-c-')); g(['clone', '-q', G, C], os.tmpdir());
const OUT = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-sbom-o-'));
const TGZ = packNpmFromTree(G, 'HEAD:pkg', OUT);
const scrieSbom = (nume, bom) => { const f = path.join(OUT, nume); fs.writeFileSync(f, JSON.stringify(bom, null, 2)); return f; };
const r1 = sbomNpmFromTree(G, 'HEAD:pkg'); const r2 = sbomNpmFromTree(G, 'HEAD:pkg');
const S = scrieSbom('proba-sbom.sbom.cdx.json', r1.bom);
const att = await attest({ artifacts: [TGZ], sbom: S, name: 'proba-sbom', version: '0.1.0', sourcePath: 'pkg', build: 'npm-pack', cwd: G });
await test('npm sbom din lockfile-ul comis: trei componente, si doua rulari difera in octeti (numar de serie, timp) dar nu in continut', () => {
cere(r1.bom && r1.bom.components.length === 3, 'componente: ' + (r1.bom && r1.bom.components.length) + (r1.lipsa ? ' ' + r1.lipsa : ''));
cere(JSON.stringify(r1.bom) !== JSON.stringify(r2.bom), 'doua rulari ar trebui sa difere in octeti (altfel testul de mai jos nu masoara nimic)');
cere(JSON.stringify(sbomSemantica(r1.bom)) === JSON.stringify(sbomSemantica(r2.bom)), 'forma semantica trebuie sa fie aceeasi');
});
await test('verify --rebuild-from cu SBOM-ul dat: SBOM-ul spune ce spune lockfile-ul comis (VALID)', async () => {
const r = await verify(att, [TGZ, S], { rebuildFrom: C });
cere(r.valid && check(r, /attested SBOM says what the committed lockfile says/) && check(r, /attested SBOM says/).pass === true, JSON.stringify(r.checks.filter((c) => c.pass !== true)));
});
await test('un SBOM regenerat (alt numar de serie, alt timp) si re-atestat trece: judecata e pe continut, nu pe octeti', async () => {
const S2 = scrieSbom('proba-sbom.sbom.cdx.json', sbomNpmFromTree(G, 'HEAD:pkg').bom);
const a2 = await attest({ artifacts: [TGZ], sbom: S2, name: 'proba-sbom', version: '0.1.0', sourcePath: 'pkg', build: 'npm-pack', cwd: G });
const r = await verify(a2, [TGZ, S2], { rebuildFrom: C }); cere(r.valid, 'trebuia VALID');
fs.writeFileSync(S, JSON.stringify(r1.bom, null, 2));
});
async function editat(nume, schimba) {
const bom = JSON.parse(JSON.stringify(r1.bom)); schimba(bom);
const d = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-sbom-e-')); const f = path.join(d, 'proba-sbom.sbom.cdx.json'); fs.writeFileSync(f, JSON.stringify(bom, null, 2));
const a = await attest({ artifacts: [TGZ], sbom: f, name: 'proba-sbom', version: '0.1.0', sourcePath: 'pkg', build: 'npm-pack', cwd: G });
const simplu = await verify(a, [TGZ, f]);
const r = await verify(a, [TGZ, f], { rebuildFrom: C });
cere(simplu.valid, `${nume}: fara reconstructie, digestul singur trece (de asta conteaza comparatia)`);
cere(!r.valid && check(r, /attested SBOM says/).pass === false, `${nume}: trebuia prins; ${JSON.stringify(check(r, /attested SBOM says/))}`);
}
await test('CONTROL: o componenta scoasa din SBOM de mana, re-atestat -> prins la reconstructie', () => editat('scoasa', (b) => { b.components = b.components.filter((c) => !/dep-c/.test(c.name)); b.dependencies = (b.dependencies || []).map((d) => ({ ...d, dependsOn: (d.dependsOn || []).filter((x) => !/dep-c/.test(x)) })).filter((d) => !/dep-c/.test(d.ref)); }));
await test('CONTROL: o versiune schimbata in SBOM (si purl-ul ei) -> prins', () => editat('versiune', (b) => { const c = b.components.find((x) => x.name === 'dep-b'); c.version = '2.0.1'; c.purl = c.purl.replace('2.0.0', '2.0.1'); }));
await test('CONTROL: un hash de integritate schimbat in SBOM -> prins', () => editat('hash', (b) => { const c = b.components.find((x) => (x.hashes || []).length); c.hashes[0].content = 'ab'.repeat(64); }));
await test('SBOM-ul atestat nedat lui verify: comparatia nu se face, si se spune', async () => {
const r = await verify(att, [TGZ], { rebuildFrom: C });
cere(check(r, /^rebuild: SBOM$/) && check(r, /^rebuild: SBOM$/).pass === null, 'trebuia raportat nefacut');
});
await test('un arbore fara package-lock.json comis: SBOM-ul nu se poate re-deriva, si se spune (nu e trecut drept VALID)', () => {
const r = sbomNpmFromTree(G, 'HEAD:fara');
cere(!r.bom && /no package-lock/.test(r.lipsa || ''), JSON.stringify(r).slice(0, 120));
});
for (const d of [G, C, OUT]) fs.rmSync(d, { recursive: true, force: true });
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
process.exitCode = esecuri.length ? 1 : 0;
@@ -0,0 +1,11 @@
// Controlul negativ al semnatarului (semnatar.test.mjs, B-18), prin mecanismul comun din _control.mjs: fiecare paznic scos intr-o
// copie a lui pos.mjs trebuie sa inroseasca exact proba lui.
// node aerenew/tools/proof-of-software/test/semnatar-control-negativ.mjs
import { controleaza } from './_control.mjs';
process.exitCode = controleaza('semnatar.test.mjs', [
['--signer nu mai compara cheile', "!!semnatar && semnatar === keyId(publicKeysOf(signer))", '!!semnatar', '3. ATAC'],
['o atestare nesemnata trece de --signer', "!!semnatar && semnatar === keyId(publicKeysOf(signer))", 'true', '5. o atestare nesemnata'],
['randul "signer" nejudecat nu mai apare', "else if (!(att.statement.builder && att.statement.builder.credential && trustIssuer)) checks.push({ name: 'signer', pass: null,", "else if (false) checks.push({ name: 'signer', pass: null,", '2. fara --signer'],
['amprenta cheilor scoasa din numele verificarii', "by keys ${semnatar ? semnatar.slice(0, 18) : '?'}:", ':', '1. numele verificarii'],
]);
@@ -0,0 +1,67 @@
// Proof of Software, B-18 (2026-09-29): o semnatura valida spune ca NISTE chei au semnat, nu CARE. Pe 1.4.0 un strain isi semna cu
// cheile lui declaratia despre artefactul lui (acelasi nume si versiune) si verificarea spunea VALID fara sa numeasca semnatarul. Acum
// numele verificarii poarta amprenta cheilor, `--signer` cere cheile asteptate, iar fara el (si fara o acreditare judecata) se spune
// nejudecat. Fiecare afirmatie cu perechea ei negativa. Offline.
// node test/semnatar.test.mjs iesire 0 = toate cum trebuia
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { attest, verify, publicKeysOf, issueCredential } from '../pos.mjs';
import * as pq from '../../../sdk-pq-sign/index.mjs';
const AICI = path.dirname(fileURLToPath(import.meta.url));
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' — ' + (e.message || e)); } }
const cere = (c, m) => { if (!c) throw new Error(m); };
const check = (r, re) => r.checks.find((c) => re.test(c.name));
const D = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pos-semnatar-'));
const BUN = path.join(D, 'app.tgz'); fs.writeFileSync(BUN, 'artefactul constructorului');
fs.mkdirSync(path.join(D, 'strain')); const RAU = path.join(D, 'strain', 'app.tgz'); fs.writeFileSync(RAU, 'artefactul unui strain');
const dev = pq.generateKeyPair(), strain = pq.generateKeyPair(), org = pq.generateKeyPair();
const aBun = await attest({ artifacts: [BUN], name: 'app', version: '1.0.0', keys: dev, cwd: D });
const aRau = await attest({ artifacts: [RAU], name: 'app', version: '1.0.0', keys: strain, cwd: D });
await test('1. numele verificarii semnaturii poarta amprenta cheilor care au semnat (doua chei -> doua amprente)', async () => {
const r1 = await verify(aBun, [BUN]), r2 = await verify(aRau, [RAU]);
const n1 = check(r1, /^hybrid signature/).name, n2 = check(r2, /^hybrid signature/).name;
cere(/by keys 0x[0-9a-f]{16}/.test(n1) && n1 !== n2, `${n1} | ${n2}`);
});
await test('2. fara --signer si fara acreditare judecata: cine a semnat e raportat NEJUDECAT, nu tacut', async () => {
const r = await verify(aRau, [RAU]);
cere(r.valid && check(r, /^signer$/) && check(r, /^signer$/).pass === null && /anyone can sign/.test(check(r, /^signer$/).detail), JSON.stringify(check(r, /^signer$/)));
});
await test('3. ATAC: atestarea strainului, verificata cu --signer = cheile constructorului -> INVALIDA', async () => {
const r = await verify(aRau, [RAU], { signer: publicKeysOf(dev) });
cere(!r.valid && check(r, /signed by the keys you gave/).pass === false, JSON.stringify(check(r, /signed by the keys you gave/)));
});
await test('4. CONTROL: atestarea constructorului, cu --signer = cheile lui (fisierul public) -> VALIDA', async () => {
const r = await verify(aBun, [BUN], { signer: publicKeysOf(dev) });
cere(r.valid && check(r, /signed by the keys you gave/).pass === true, JSON.stringify(r.checks.filter((c) => c.pass === false)));
});
await test('5. o atestare nesemnata, cu --signer -> INVALIDA (nu "absenta")', async () => {
const a = await attest({ artifacts: [BUN], name: 'app', version: '1.0.0', cwd: D });
const r = await verify(a, [BUN], { signer: publicKeysOf(dev) });
cere(!r.valid && /not signed/.test(check(r, /signed by the keys you gave/).detail), JSON.stringify(check(r, /signed by the keys you gave/)));
});
await test('6. cu o acreditare judecata (--trust-issuer), semnatarul e judecat de acreditare si randul "signer" nu mai apare', async () => {
const cred = issueCredential({ issuerKeys: org, issuerName: 'Org', subjectKeys: publicKeysOf(dev), subjectName: 'Dev', validFrom: '2026-01-01T00:00:00Z', validUntil: '2027-01-01T00:00:00Z' });
const a = await attest({ artifacts: [BUN], name: 'app', version: '1.0.0', keys: dev, credential: cred, cwd: D, now: new Date('2026-06-01T00:00:00Z') });
const r = await verify(a, [BUN], { trustIssuer: publicKeysOf(org) });
cere(!check(r, /^signer$/) && check(r, /names the keys that signed/).pass === true, JSON.stringify(r.checks.map((c) => c.name)));
});
await test('7. linia de comanda: verify --signer (0 pentru constructor, 1 pentru strain), si "not judged" numarat pe randul de verdict', async () => {
const pos = path.join(AICI, '..', 'pos.mjs'); const f = (n) => path.join(D, n);
fs.writeFileSync(f('dev.json'), JSON.stringify(dev));
execFileSync(process.execPath, [pos, 'pubkey', '--keys', f('dev.json'), '--out', f('dev.pub.json')], { stdio: 'pipe' });
fs.writeFileSync(f('bun.json'), JSON.stringify(aBun)); fs.writeFileSync(f('rau.json'), JSON.stringify(aRau));
const run = (args) => { try { return { cod: 0, out: execFileSync(process.execPath, [pos, ...args], { stdio: 'pipe' }).toString() }; } catch (e) { return { cod: e.status, out: String(e.stdout || '') }; } };
const b = run(['verify', f('bun.json'), '--signer', f('dev.pub.json'), BUN]), r = run(['verify', f('rau.json'), '--signer', f('dev.pub.json'), RAU]);
const fara = run(['verify', f('rau.json'), RAU]);
cere(b.cod === 0 && r.cod === 1 && fara.cod === 0 && /not judged/.test(fara.out), `${b.cod} ${r.cod} ${fara.cod} ${fara.out.split('\n').slice(-2).join(' ')}`);
});
fs.rmSync(D, { recursive: true, force: true });
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
process.exitCode = esecuri.length ? 1 : 0;