pq-secrets: a zero-trust secrets service on top of pq-kms (each request authorized by an Aere Identity presentation signed for that exact request, per-secret policy whose non-admin grants can only narrow, the same refusal for every unauthorized caller, every operation a signed AIP-23 secret-access envelope); identity: a presentation optionally signed for one exact request; proof-kinds: secret-access with requestHash; conformance 240 rules, 626 vectors

This commit is contained in:
Aere Network committed 2026-10-19 00:30:58 +03:00
1 parent 8c7d72c1a7
commit ad16b1f69b
97 files changed
+4258 -133

No files matched your search

+21 -8
View File
@@ -49,6 +49,19 @@ delegation chain, the verifier's audience and nonce, and the time. Without the v
for someone else would be accepted, so `verify` reports those checks as not judged instead of passing them. A nonce is the
verifier's to make fresh and to accept once: a verifier that reuses one accepts a replay within the presentation's age limit.
**A presentation can also be bound to one request** (since 2026-10-18): `present({ ..., request })` puts `request`, the digest of
what the holder asks the verifier to do (`0x` + 64 lowercase hex, computed by the verifier's own rule from the request), into the
binding before it is signed, and `verifyPresentation(p, { ..., request })` then requires exactly that digest (rule `request`: another
digest, or none at all, is a refusal). Without it the signature covers who the presentation is for, but not what it is used for: a
presentation made for "read secret db" was handed over as "revoke a grant on db" (the adversarial review of the secrets service).
A verifier that gives no request leaves a binding that carries one **not judged** (cause `request`), like the audience and the nonce;
a binding without one, judged by a verifier that gives none, has no request row at all, so every presentation made before the field
existed verifies exactly as before. The model is `transaction_data` in OpenID for Verifiable Presentations 1.0 (Final, 9 July 2025):
section 5.1 (the request parameter), section 8.4 (the data signed with the same key as the proof of possession) and appendix B.3.3
(the `transaction_data_hashes` of the SD-JWT VC Key Binding JWT, SHA-256 by default). `checkCompliance` passes `request` through, and
takes a `cache` (a `Map` made by the caller for one presentation) so that a service judging the same presentation against many
policies verifies its signatures once per distinct pair of trusted issuers and maximum age, with the same result as without it.
Inputs the verifier fetched and cannot read (a malformed status list or revocation) are ignored and reported, never counted against
the credential; a malformed trusted issuer key is the verifier's own error and stops the verification.
@@ -287,15 +300,15 @@ the table says, row by row, what is measured here.
Since 2026-10-05 every refusal of `verifyPresentation` names its rule. A row is `{ name, pass, detail, rule }`; a row that was not
judged is `{ name, pass: null, detail, unjudged }` with its cause. The result carries `rules`, the sorted ids of the rules that
refused, and `unjudged`, the sorted causes of what was not judged. The module exports the lists: `REGULI` (37 rules), `NEJUDECATE`
(7 causes) and `OPRIRI` (the four rules after whose refusal other checks were not made: `form`, `chain-length`, `delegation-form`,
refused, and `unjudged`, the sorted causes of what was not judged. The module exports the lists: `REGULI` (38 rules since 2026-10-18, with `request`), `NEJUDECATE`
(8 causes) and `OPRIRI` (the four rules after whose refusal other checks were not made: `form`, `chain-length`, `delegation-form`,
`unreadable`). A time field that cannot be read (a credential's validity, a delegation's or a presentation's bounds) and a malformed
earlier link are reported as `unreadable`, which is one of the stopping rules: the checks after it are not made. The verifier does
not stop at its first refusal: it makes every check it can reach. `valid` is unchanged: true when
no row failed, also when rows were not judged; a caller that needs "nothing left unjudged" reads `unjudged`.
With these ids the presentation verifier is enrolled in the conformance suite beside this folder (`conformance/`: 37 rules,
65 vectors of the artifact kind `identity-presentation`, each rule taken out of a copy of the verifier in turn). Since 2026-10-18 the
With these ids the presentation verifier is enrolled in the conformance suite beside this folder (`conformance/`: 38 rules,
69 vectors of the artifact kind `identity-presentation`, four of them for `request` since 2026-10-18, each rule taken out of a copy of the verifier in turn). Since 2026-10-18 the
SD-JWT verifier and the SD-JWT VC profile are enrolled there too: `verifySdJwt` names the rule of its refusal (`rule`, one of the 23 of
`REGULI` in `sdjwt.mjs`: `form`, `alg`, `typ`, `crit`, `key`, `signature`, `issuer`, `sd-alg`, `disclosure-form`, `disclosure-twice`,
`digest-twice`, `disclosure-name`, `claim-conflict`, `unreferenced`, `time`, `kb-context`, `kb-required`, `kb-cnf`, `kb-claims`,
@@ -343,10 +356,10 @@ line is reported as not judged. The private key files are written with mode 0600
## Tests
```
node proba-identity.mjs # 46: the paths above, each attack of the adversarial review as its own test, the named rules
node control-negativ-identity.mjs # on a copy, each of 53 guards removed -> its own named test turns red
node proba-conformitate.mjs # 15: compliance policies judged on real presentations, the record without personal data, the command line
node control-negativ-conformitate.mjs # on a copy, each of 14 guards removed -> its own named test turns red
node proba-identity.mjs # 52: the paths above, each attack of the adversarial review as its own test, the named rules
node control-negativ-identity.mjs # on a copy, each of 57 guards removed -> its own named test turns red
node proba-conformitate.mjs # 18: compliance policies judged on real presentations, the record without personal data, the command line
node control-negativ-conformitate.mjs # on a copy, each of 17 guards removed -> its own named test turns red
node proba-travel-rule.mjs # 19: two VASPs with registry credentials, the whole exchange, and each attack of the review
node control-negativ-travel-rule.mjs # on a copy, each of 19 guards removed -> its own named test turns red
node proba-sdjwt.mjs # 25: the RFC 9901 vectors, SD-JWTs issued with AERE keys (EdDSA and ML-DSA-65), each attack, the fixtures of @sd-jwt/core
+29 -5
View File
@@ -64,16 +64,40 @@ function regula(r, claims) {
return false;
}
// 2026-10-18 (B8, revizuirea adversariala a lui pq-secrets): un serviciu care judeca ACEEASI prezentare dupa mai multe politici (un
// grant fiecare) refacea verificarea hibrida intreaga pentru fiecare: 200 de grant-uri, 0,5 s de CPU pentru un apelant fara niciun drept.
// Cu `cache` (un Map facut de apelant pentru O prezentare), verificarea se face o data pentru fiecare pereche distincta (emitentii
// politicii, varsta maxima), singurele lucruri prin care difera de la o politica la alta; contextul (prezentarea, publicul, nonce-ul,
// ceasul, listele de stare, revocarile, cererea) e legat de cache la prima folosire si o folosire cu alt context e o greseala a
// apelantului (arunca). Iesirea lui checkCompliance e aceeasi, cu cache sau fara.
const CONTEXT = Symbol('context');
function verifica(p, o, cache) {
if (cache == null) return verifyPresentation(p, o);
if (!(cache instanceof Map)) throw new Error('compliance: cache is a Map made by the caller for one presentation');
const t = new Date(o.now).getTime(); const ctx = cache.get(CONTEXT);
// listele se compara dupa identitate (aceeasi lista data de apelant), doua liste goale sunt aceeasi (implicitul `[]` e alt obiect la
// fiecare apel)
const aceeasi = (x, y) => x === y || (Array.isArray(x) && Array.isArray(y) && x.length === 0 && y.length === 0);
if (ctx === undefined) cache.set(CONTEXT, { p, audience: o.audience, nonce: o.nonce, t, statusLists: o.statusLists, revocations: o.revocations, request: o.request });
else if (!(ctx.p === p && ctx.audience === o.audience && ctx.nonce === o.nonce && ctx.t === t && aceeasi(ctx.statusLists, o.statusLists) && aceeasi(ctx.revocations, o.revocations) && ctx.request === o.request)) {
throw new Error('compliance: a cache serves one presentation judged in one context (the same presentation, audience, nonce, clock, status lists, revocations and request)');
}
const k = canonical([o.trustedIssuers, o.maxAgeS]);
if (!cache.has(k)) cache.set(k, verifyPresentation(p, o));
return cache.get(k);
}
/**
* Judeca o prezentare dupa o politica. Cere: prezentarea VALIDA, legata de publicul si nonce-ul verificatorului, emitentul intre cei
* ai politicii, starea credentialului JUDECATA (nu doar "nerevocat pentru ca nu stiu") cand politica o cere, si fiecare regula.
* Intoarce { compliant, reasons, policyHash, presentation } fara afirmatiile detinatorului (le are verificatorul in `presentation.claims`
* numai daca le cere explicit, cu `keepClaims`).
* numai daca le cere explicit, cu `keepClaims`). `request` (optional): digestul cererii primite, dat verificatorului de identitate
* (regula lui `request`); `cache` (optional): vezi mai sus.
*/
export function checkCompliance(p, politica, { audience, nonce, now = new Date(), statusLists = [], revocations = [], keepClaims = false } = {}) {
export function checkCompliance(p, politica, { audience, nonce, now = new Date(), statusLists = [], revocations = [], keepClaims = false, request = null, cache = null } = {}) {
const { policy, policyHash } = definePolicy(politica);
if (typeof audience !== 'string' || !audience || typeof nonce !== 'string' || !nonce) throw new Error('compliance: the verifier\'s audience and nonce are required (without them a presentation can be replayed)');
const v = verifyPresentation(p, { audience, nonce, now, trustedIssuers: policy.trustedIssuers, statusLists, revocations, maxAgeS: policy.maxAgeS });
const v = verifica(p, { audience, nonce, now, trustedIssuers: policy.trustedIssuers, statusLists, revocations, maxAgeS: policy.maxAgeS, request }, cache);
const rows = []; const ok = (rule, pass, detail) => { if (!REGULI.includes(rule)) throw new Error('compliance: undeclared rule ' + rule); rows.push({ rule, pass: !!pass, detail: pass ? '' : detail }); };
ok('presentation', v.valid /*PAZA:presentation*/, 'the presentation is not valid: ' + v.rows.filter((r) => r.pass === false).map((r) => r.name + (r.detail ? ' (' + r.detail + ')' : '')).join('; '));
const status = v.rows.find((r) => /^credential: (not revoked|status)/.test(r.name));
@@ -87,8 +111,8 @@ export function checkCompliance(p, politica, { audience, nonce, now = new Date()
// oricine, schimba obiectul fara sa schimbe nimic semnat, deci digestul vechi nu numea unic prezentarea. Semnatura nu intra: ML-DSA
// semneaza aleator, deci aceeasi legatura poate avea oricate semnaturi valide. Fara legatura (prezentare stricata), obiectul intreg.
const legatura = p && typeof p === 'object' && p.binding && typeof p.binding === 'object' && !Array.isArray(p.binding) ? p.binding : null;
return { compliant: !motive.length, reasons: motive, rules: [...new Set(rows.filter((r) => !r.pass).map((r) => r.rule))].sort(), rows, unjudged: v.unjudged, policyHash, policyId: policy.id, holder, notJudged: v.notJudged,
presentationHash: sha(canonical(legatura || p || null)), ...(keepClaims && !motive.length ? { claims } : {}) };
return { compliant: !motive.length, reasons: motive, rules: [...new Set(rows.filter((r) => !r.pass).map((r) => r.rule))].sort(), rows, unjudged: [...v.unjudged], policyHash, policyId: policy.id, holder, notJudged: v.notJudged,
presentationHash: sha(canonical(legatura || p || null)), ...(keepClaims && !motive.length ? { claims: { ...claims } } : {}) };
}
/**
+5 -1
View File
@@ -25,7 +25,11 @@ const PLANTARI = [
['regulile nu mai sunt in forma normala', '}).sort((a, b) => (canonical(a) < canonical(b) ? -1 : 1));', '});', 'politica: forma normala'],
['campuri necunoscute primite in politica', 'if (necunoscute.length) throw', 'if (false) throw', 'CONTROL: politica refuza'],
['id-ul detinatorului scris in inregistrare', 'subject: pseudonim,', 'subject: rez.holder,', 'inregistrarea (plic AIP-23 compliance) NU poarta date personale'],
['afirmatiile intoarse si pentru o judecata neconforma', '...(keepClaims && !motive.length ? { claims } : {})', '...(keepClaims ? { claims } : {})', 'rezultatul nu poarta afirmatiile'],
['afirmatiile intoarse si pentru o judecata neconforma', '...(keepClaims && !motive.length ? { claims: { ...claims } } : {})', '...(keepClaims ? { claims: { ...claims } } : {})', 'rezultatul nu poarta afirmatiile'],
// 2026-10-18 (B8): cererea si cache-ul verificarii
['cererea nu mai ajunge la verificatorul de identitate', 'maxAgeS: policy.maxAgeS, request }, cache);', 'maxAgeS: policy.maxAgeS }, cache);', 'cererea: checkCompliance da cererea'],
['cache-ul nu mai cere acelasi context (verdictul altei prezentari imprumutat)', "else if (!(ctx.p === p && ctx.audience === o.audience", "else if (false && !(ctx.p === p && ctx.audience === o.audience", 'CONTROL: un cache folosit pentru alta prezentare'],
['cache-ul nu mai deosebeste emitentii si varsta politicii', 'const k = canonical([o.trustedIssuers, o.maxAgeS]);', "const k = 'una';", 'cache: aceeasi prezentare dupa patru politici'],
['cheia verificatorului ignorata la pseudonim', '(pseudonymKey ? crypto.createHmac(', '(false ? crypto.createHmac(', 'pseudonimul'],
];
const FISIERE = ['identity.mjs', 'identity-cli.mjs', C, 'proba-conformitate.mjs'];
+5
View File
@@ -26,6 +26,11 @@ const PLANTARI = [
['alta codare base64url a aceleiasi dezvaluiri primita', L, "if (b.toString('base64url') !== enc) throw", 'if (false) throw', 'ATAC: o dezvaluire in alta codare base64url'],
['publicul verificatorului nu se mai compara', L, 'B.audience === audience /*PAZA:audience*/,', 'true,', 'ATAC: reluata la alt verificator'],
['nonce-ul verificatorului nu se mai compara', L, 'B.nonce === nonce /*PAZA:nonce*/,', 'true,', 'ATAC: reluata la alt verificator'],
// 2026-10-18 (B8): cererea
['cererea nu se mai compara (o prezentare pentru get depusa pentru revoke)', L, 'B.request === request /*PAZA:request*/,', 'true,', 'ATAC: o prezentare semnata pentru alta cerere'],
['cererea lipsa din legatura acceptata de un verificator care o cere', L, 'B.request === request /*PAZA:request*/,', '(B.request === undefined || B.request === request),', 'ATAC: o prezentare FARA cerere'],
['present nu mai pune cererea in legatura', L, "...(request != null ? { request } : {}) };", '};', 'cererea: present({ request })'],
['o cerere semnata si nejudecata nu mai e spusa', L, "else if (Object.hasOwn(B, 'request')) nejudecat(", 'else if (false) nejudecat(', 'cererea nejudecata'],
['prospetimea prezentarii nu se mai cere', L, 'Math.abs(acum - t) <= maxAgeS * 1000 /*PAZA:freshness*/,', 'true,', 'ATAC: prezentare veche'],
['oricine poate prezenta credentialul detinatorului', L, 'asteptat && B.presenter.id === asteptat.id && canonical(B.presenter.keys) === canonical(asteptat.keys) /*PAZA:presenter*/,', 'true,', 'ATAC: un strain prezinta'],
['prezentatorul nu mai trebuie sa fie ultimul delegat', L, 'asteptat && B.presenter.id === asteptat.id && canonical(B.presenter.keys) === canonical(asteptat.keys) /*PAZA:presenter*/,', 'true,', 'ATAC: detinatorul prezinta singur'],
+25 -6
View File
@@ -259,20 +259,30 @@ export function statusBit(list, index) {
}
// ---------------------------------------------------------------- prezentarea
// CEREREA (2026-10-18, B8, revizuirea adversariala a lui pq-secrets): fara ea, semnatura prezentatorului acopera verificatorul, nonce-ul
// si momentul, dar NU ce i se cere verificatorului; o prezentare facuta pentru "citeste db" a fost depusa ca "revoca grantul" pe db.
// `request` e digestul cererii pe care detinatorul o face (0x + 64 hex, calculat de verificator intr-un singur loc, din cerere), pus in
// legatura INAINTE de semnare; verificatorul care il da cere ca legatura sa poarte exact acel digest. Modelul, citit 2026-10-18: OpenID
// for Verifiable Presentations 1.0 (Final, 9 iulie 2025), sectiunea 5.1 (parametrul `transaction_data` al cererii), 8.4 (datele
// tranzactiei semnate cu aceeasi cheie ca dovada de posesie a credentialului) si anexa B.3.3 (in Key Binding JWT-ul unui SD-JWT VC:
// `transaction_data_hashes`, sha-256 implicit, peste sirul primit, fara decodare).
const DIGEST = /^0x[0-9a-f]{64}$/;
/**
* Prezinta un credential: arata numai afirmatiile din `reveal` si leaga totul de publicul si nonce-ul verificatorului.
* `presenter` e detinatorul, sau, cu `delegations` (lantul de la detinator la el), delegatul.
* `presenter` e detinatorul, sau, cu `delegations` (lantul de la detinator la el), delegatul. `request` (optional): digestul cererii
* catre verificator (0x + 64 hex), semnat in legatura; fara el legatura e exact cea de pana acum.
*/
export function present({ credential, disclosures = [], reveal = [], presenter, delegations = [], audience, nonce, now = new Date() }) {
export function present({ credential, disclosures = [], reveal = [], presenter, delegations = [], audience, nonce, now = new Date(), request = null }) {
if (!presenter || !presenter.privat) throw new Error('aere-identity: presenting needs the presenter\'s private keys');
if (typeof audience !== 'string' || !audience || typeof nonce !== 'string' || !nonce) throw new Error('aere-identity: a presentation needs the verifier\'s audience and nonce');
if (request != null && (typeof request !== 'string' || !DIGEST.test(request))) throw new Error('aere-identity: request is the digest of the request (0x + 64 lowercase hex)');
const dupa = new Map(disclosures.map((e) => [decodeDisclosure(e).name, e]));
const alese = [];
// o afirmatie in clar se vede oricum: numele ei in `reveal` nu cere nimic
const inClar = (credential && credential.statement && credential.statement.claims) || {};
for (const n of [...new Set(reveal)].sort()) { if (Object.hasOwn(inClar, n)) continue; if (!dupa.has(n)) throw new Error('aere-identity: no disclosure for ' + n); alese.push(dupa.get(n)); }
const binding = { v: VERSION, kind: 'aere-presentation-binding', credentialHash: credentialHash(credential), disclosuresHash: hashOf(alese),
delegations: delegations.map(delegationHash), audience, nonce, createdAt: iso(now), presenter: { id: presenter.id, keys: presenter.public } };
delegations: delegations.map(delegationHash), audience, nonce, createdAt: iso(now), presenter: { id: presenter.id, keys: presenter.public }, ...(request != null ? { request } : {}) };
return { v: VERSION, kind: 'aere-presentation', credential, disclosures: alese, delegations, binding, signature: signText('presentation', canonical(binding), presenter) };
}
@@ -293,11 +303,15 @@ export const CLOCK_SKEW_S = 60;
export const REGULI = ['form', 'issuer-id', 'holder-id', 'credential-signature', 'issuer-trusted', 'credential-window', 'status-list', 'credential-revoked', 'sd-distinct',
'disclosure-readable', 'disclosure-signed', 'disclosure-once', 'disclosure-plain', 'claim-name', 'binding-credential', 'binding-disclosures', 'binding-delegations', 'presenter',
'presentation-signature', 'audience', 'nonce', 'freshness', 'chain-length', 'delegation-form', 'delegation-ids', 'delegation-from', 'delegation-parent', 'delegation-signature',
'delegation-scope', 'delegation-window', 'delegation-depth', 'delegation-narrows', 'delegation-credential', 'delegation-claims', 'delegation-audience', 'delegation-revoked', 'unreadable'];
export const NEJUDECATE = ['issuer-trust', 'status-none', 'status-unread', 'audience', 'nonce', 'revocation-ignored', 'revocations-none'];
'delegation-scope', 'delegation-window', 'delegation-depth', 'delegation-narrows', 'delegation-credential', 'delegation-claims', 'delegation-audience', 'delegation-revoked', 'unreadable',
// 2026-10-18: the presentation commits to the request the verifier received (OpenID4VP transaction_data, SD-JWT transaction_data_hashes)
'request'];
// `request` as a cause: the binding commits to a request and the verifier gave none to compare. A binding with no request, judged by a
// verifier that gives none, has NO request row at all (the rows of every presentation made before the field existed are unchanged).
export const NEJUDECATE = ['issuer-trust', 'status-none', 'status-unread', 'audience', 'nonce', 'revocation-ignored', 'revocations-none', 'request'];
export const OPRIRI = ['form', 'chain-length', 'delegation-form', 'unreadable'];
class Nedeclarata extends Error {}
export function verifyPresentation(p, { audience = null, nonce = null, now = new Date(), trustedIssuers = null, statusLists = [], revocations = [], maxAgeS = 300, clockSkewS = CLOCK_SKEW_S } = {}) {
export function verifyPresentation(p, { audience = null, nonce = null, now = new Date(), trustedIssuers = null, statusLists = [], revocations = [], maxAgeS = 300, clockSkewS = CLOCK_SKEW_S, request = null } = {}) {
const rows = [];
const ok = (rule, name, pass, detail = '') => { if (!REGULI.includes(rule)) throw new Nedeclarata('aere-identity: undeclared rule ' + rule); rows.push({ name, pass: !!pass, detail: pass ? '' : detail, rule }); return !!pass; };
const nejudecat = (cauza, name, detail) => { if (!NEJUDECATE.includes(cauza)) throw new Nedeclarata('aere-identity: undeclared cause ' + cauza); rows.push({ name, pass: null, detail, unjudged: cauza }); };
@@ -313,6 +327,7 @@ export function verifyPresentation(p, { audience = null, nonce = null, now = new
if (trustedIssuers != null && !Array.isArray(trustedIssuers)) throw new Error('verifyPresentation: trustedIssuers is a list of ids or public keys');
const idsIncredere = trustedIssuers == null ? null : trustedIssuers.map((x) => (typeof x === 'string' && ID.test(x) ? x : idOf(x)));
if (!Array.isArray(statusLists) || !Array.isArray(revocations)) throw new Error('verifyPresentation: statusLists and revocations are lists');
if (request != null && (typeof request !== 'string' || !DIGEST.test(request))) throw new Error('verifyPresentation: request is the digest of the request the verifier received (0x + 64 lowercase hex)');
try {
if (!((!!p && p.kind === 'aere-presentation' && p.v === VERSION && !!p.credential && !!p.binding && Array.isArray(p.disclosures) && Array.isArray(p.delegations)) /*PAZA:form*/)) {
ok('form', 'presentation: well formed', false, 'not an aere-presentation'); return gata();
@@ -382,6 +397,10 @@ export function verifyPresentation(p, { audience = null, nonce = null, now = new
else ok('audience', `presentation: made for ${audience}`, B.audience === audience /*PAZA:audience*/, `made for ${B.audience}`);
if (nonce == null) nejudecat('nonce', 'presentation: nonce', 'not judged: without the verifier\'s nonce an old presentation can be replayed');
else ok('nonce', 'presentation: carries the verifier\'s nonce', B.nonce === nonce /*PAZA:nonce*/, 'another nonce');
// the request: given by the verifier, the binding must carry exactly that digest (absent is a refusal); not given, a binding that
// carries one leaves it unjudged, and a binding without one has no row (as before the field existed)
if (request != null) ok('request', 'presentation: commits to the request the verifier received', B.request === request /*PAZA:request*/, Object.hasOwn(B, 'request') ? 'signed for another request' : 'the presentation commits to no request');
else if (Object.hasOwn(B, 'request')) nejudecat('request', 'presentation: request', 'not judged: the presentation commits to a request and the verifier gave none to compare it with');
const t = data(B.createdAt, 'createdAt');
ok('freshness', `presentation: made within ${maxAgeS} s of the verifier's clock`, Math.abs(acum - t) <= maxAgeS * 1000 /*PAZA:freshness*/, `made at ${B.createdAt}`);
// 7. lantul de delegare
+27
View File
@@ -105,6 +105,33 @@ test('plicul verifica la verificatorul AIP-23 de referinta; unul cu rezultatul r
} finally { fs.rmSync(T, { recursive: true, force: true }); }
});
// ---------------------------------------------------------------- 2026-10-18 (B8): cererea si verificarea o data pentru mai multe politici
const CER = '0x' + crypto.createHash('sha256').update('cererea').digest('hex');
const prezC = () => I.present({ credential, disclosures, reveal: ['age_over_18', 'jurisdiction', 'kyc_level'], presenter: hol, audience: AUD, nonce: NONCE, now: NOW, request: CER });
test('cererea: checkCompliance da cererea verificatorului de identitate: aceeasi cerere conform; alta cerere neconform (presentation)', () => {
const p = prezC();
const a = judeca(p, POL, { request: CER }), b = judeca(p, POL, { request: '0x' + '0'.repeat(64) });
cere(a.compliant && !b.compliant && b.rules.includes('presentation') && /commits to the request/.test(b.reasons.join(' ')), JSON.stringify([a.reasons, b.reasons]));
});
test('cache: aceeasi prezentare dupa patru politici (doua perechi de emitenti si varsta) da EXACT aceleasi rezultate cu cache si fara, cu trei verificari in loc de patru (doua politici au aceeasi pereche)', () => {
const p = prezC(); const liste = [LISTA]; const o = { audience: AUD, nonce: NONCE, now: NOW, statusLists: liste, request: CER };
const pol = [POL, { ...POL, id: 'p2', require: [{ claim: 'kyc_level', atLeast: 3 }] }, { ...POL, id: 'p3', maxAgeS: 60 }, { ...POL, id: 'p4', trustedIssuers: [alt.id] }];
// numaratoarea verificarilor: fiecare verifyPresentation citeste o data semnatura prezentarii
let citiri = 0; const numarat = new Proxy(p, { get: (t, k) => { if (k === 'signature') citiri++; return t[k]; } });
const fara = pol.map((x) => checkCompliance(numarat, x, o)); const nFara = citiri; citiri = 0;
const cache = new Map(); const cu = pol.map((x) => checkCompliance(numarat, x, { ...o, cache })); const nCu = citiri;
cere(JSON.stringify(fara) === JSON.stringify(cu), 'rezultatele difera cu cache');
cere(nFara === 4 && nCu === 3, `verificari: fara cache ${nFara}, cu cache ${nCu} (asteptat 4 si 3: POL si p2 au aceeasi pereche)`);
cere(fara[0].compliant && !fara[1].compliant && fara[2].compliant && !fara[3].compliant, JSON.stringify(fara.map((x) => x.compliant)));
});
test('CONTROL: un cache folosit pentru alta prezentare sau alt context arunca (o greseala a apelantului, nu un verdict de imprumut)', () => {
const cache = new Map(); const o = { audience: AUD, nonce: NONCE, now: NOW, statusLists: [LISTA] };
checkCompliance(prezC(), POL, { ...o, cache });
cere(/a cache serves one presentation/.test(arunca(() => checkCompliance(prezC(), POL, { ...o, cache })) || ''), 'alta prezentare a primit verdictul din cache');
const p = prezC(); const c2 = new Map(); checkCompliance(p, POL, { ...o, cache: c2 });
cere(/a cache serves one presentation/.test(arunca(() => checkCompliance(p, POL, { ...o, cache: c2, nonce: 'alt' })) || ''), 'alt nonce a primit verdictul din cache');
cere(/a cache serves one presentation/.test(arunca(() => checkCompliance(p, POL, { ...o, cache: c2, request: CER })) || ''), 'alta cerere a primit verdictul din cache');
});
test('linia de comanda: comply -> COMPLIANT (0) si inregistrarea scrisa fara date personale; o prezentare care nu arata destul -> NOT COMPLIANT (1)', () => {
const T = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-conf-cli-')); const CLI = path.join(AICI, 'identity-cli.mjs');
const run = (...a) => { const r = spawnSync(process.execPath, [CLI, ...a], { cwd: T, encoding: 'utf8' }); return { cod: r.status, out: (r.stdout || '') + (r.stderr || '') }; };
+31
View File
@@ -101,6 +101,37 @@ test('ATAC: reluata la alt verificator (alt public) -> INVALID; cu alt nonce ->
const r1 = I.verifyPresentation(prez(), { ...toate, audience: 'https://other.example' }); cere(picaPe(r1, /made for/), fals(r1) || 'trecut');
const r2 = I.verifyPresentation(prez(), { ...toate, nonce: 'alt' }); cere(picaPe(r2, /nonce/), fals(r2) || 'trecut');
});
// ---------------------------------------------------------------- cererea (2026-10-18, B8): ce i se cere verificatorului, semnat in legatura
const CER = '0x' + crypto.createHash('sha256').update('cererea: get db').digest('hex'), ALTA = '0x' + crypto.createHash('sha256').update('cererea: revoke db').digest('hex');
test('cererea: present({ request }) o pune in legatura semnata; verificatorul care o da cere exact acel digest: VALID, randul request trecut', () => {
const p = prez({ request: CER });
cere(p.binding.request === CER, 'legatura nu poarta cererea: ' + JSON.stringify(Object.keys(p.binding)));
const r = I.verifyPresentation(p, { ...toate, request: CER });
cere(r.valid && r.notJudged === 0 && rand(r, /commits to the request/).pass === true, fals(r) || JSON.stringify(r.rows.filter((x) => x.pass !== true)));
});
test('ATAC: o prezentare semnata pentru alta cerere (get db) depusa pentru alta (revoke db) -> INVALID, regula request', () => {
const r = I.verifyPresentation(prez({ request: CER }), { ...toate, request: ALTA });
cere(!r.valid && r.rules.join(',') === 'request' && /another request/.test(rand(r, /commits to the request/).detail), fals(r) || 'trecut');
});
test('ATAC: o prezentare FARA cerere la un verificator care o cere -> INVALID, regula request ("commits to no request")', () => {
const r = I.verifyPresentation(prez(), { ...toate, request: CER });
cere(!r.valid && r.rules.join(',') === 'request' && /no request/.test(rand(r, /commits to the request/).detail), fals(r) || 'trecut');
});
test('ATAC: cererea rescrisa in legatura dupa semnare -> INVALID (semnatura prezentatorului); cu cererea noua data verificatorului, tot INVALID', () => {
const p = prez({ request: CER }); p.binding.request = ALTA;
const r = I.verifyPresentation(p, { ...toate, request: ALTA });
cere(!r.valid && r.rules.includes('presentation-signature') && !r.rules.includes('request'), fals(r) || 'trecut');
});
test('cererea nejudecata: legatura poarta o cerere, verificatorul nu da niciuna -> VALID cu randul request NEJUDECAT (cauza request); o legatura fara cerere la un verificator fara cerere nu are rand request', () => {
const r = I.verifyPresentation(prez({ request: CER }), toate);
cere(r.valid && r.notJudged === 1 && r.unjudged.join(',') === 'request' && rand(r, /presentation: request/).pass === null, JSON.stringify(r.rows.filter((x) => x.pass !== true)));
const v = I.verifyPresentation(prez(), toate);
cere(v.valid && v.notJudged === 0 && !v.rows.some((x) => /request/.test(x.name)), JSON.stringify(v.rows.filter((x) => /request/.test(x.name))));
});
test('CONTROL: o cerere care nu e un digest e refuzata de present si de verificator (o greseala a celui care o da, nu o prezentare invalida)', () => {
cere(/request is the digest/.test(arunca(() => prez({ request: 'get db' })) || ''), 'present a primit o cerere care nu e digest');
cere(/request is the digest/.test(arunca(() => I.verifyPresentation(prez(), { ...toate, request: CER.toUpperCase().replace('0X', '0x') })) || ''), 'verificatorul a primit un digest cu majuscule');
});
test('ATAC: prezentare veche (301 s) sau din viitor (301 s) -> INVALID', () => {
const r1 = I.verifyPresentation(prez(), { ...toate, now: new Date(NOW.getTime() + 301000) }); cere(picaPe(r1, /within 300 s/), fals(r1) || 'veche trecuta');
const r2 = I.verifyPresentation(prez(), { ...toate, now: new Date(NOW.getTime() - 301000) }); cere(picaPe(r2, /within 300 s/), fals(r2) || 'viitoare trecuta');