Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Objects. Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`.
- `Vcon.migrate040To050()` static method, `Vcon.migrationReport`, and the `migrateLegacy` and
`strictMigration` options on `new Vcon()` and `Vcon.buildFromJson()`.
- `Vcon.isValid()` and `Vcon.getValidationWarnings()`, backed by `validateVconDict()`.
- Validation parity with the reference library vcon 1.0.4, with the same messages:
- Validation parity with the reference library vcon 1.0.5, with the same messages:
- A malformed `content_hash` (not `<algorithm>-<base64url digest>`, an empty list, or a
`sha512`/`sha256` digest of the wrong length) on a Dialog, attachment, analysis,
`redacted_from` or `amended_from` is an error. `contentHashProblems()` is exported.
Expand All @@ -46,6 +46,12 @@ Objects. Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`.
types, hash algorithms and canonicalization methods are warnings. Exported as
`validateLawfulBasisAttachment()` and `validateLawfulBasisBody()`.
- An unparseable `created_at` or `updated_at` error quotes the reason, as the reference does.
- A JWS container (no `uuid`, has `payload` and `signatures`) or JWE container (no `uuid`,
has `ciphertext`) is kept exactly as given on load: no `uuid`, `created_at` or arrays are
added. `isValid()` checks a JWS's `signatures` and validates its decoded `payload` as a vCon
(including the lawful basis check); a JWE gets type checks on `ciphertext`, `iv`, `tag`,
`protected` and `recipients`, and the warning that its content cannot be validated without
decrypting it. `signedForm()`, `encryptedForm()` and `signedPayload()` are exported.
- `Vcon.sign(key, alg = "RS256")`, `Vcon.verify(key)` and `Vcon.generateKeyPair()` (JWS with
Node `crypto`, no new dependency); `AlgorithmNotPermittedError`. This restores a signing
surface that 0.5.2 removed, because core-05 section 6.2.2 now forbids `alg` "none" and the
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ vcon.sign(privateKey, 'none'); // throws AlgorithmNotPermittedError

Encryption (JWE) is not implemented; wrap the vCon with a library of your choice.

A signed (JWS) or encrypted (JWE) container loaded with `new Vcon(...)` is kept exactly as given. `isValid()` checks a JWS's `signatures` and validates the decoded `payload` as a vCon; for a JWE it checks the member types and `getValidationWarnings()` notes that the content cannot be validated without decrypting it.

### Working with Extensions

```typescript
Expand Down
140 changes: 140 additions & 0 deletions src/__tests__/jws-jwe-validation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import { Vcon } from '../vcon';
import { Party } from '../party';
import { encryptedForm, signedForm, signedPayload, validateVconDict } from '../validation';
import { decodeJsonPayload, lenientBase64UrlDecode } from '../util';

/**
* Signed (JWS) and encrypted (JWE) vCons, as the reference library handles
* them from vcon 1.0.5: kept as given on load and validated as containers.
*/

const T = '2026-01-15T10:30:00Z';
const b64 = (v: unknown) => Buffer.from(JSON.stringify(v)).toString('base64url');
const PROT = b64({ alg: 'RS256', typ: 'JWS' });

function inner(): Record<string, any> {
const v = Vcon.buildNew();
v.addParty(new Party({ name: 'Alice' }));
v.addSession({ start: T, parties: [0] });
return JSON.parse(v.toJson());
}

const jws = (payload: unknown, signatures: unknown = [{ protected: PROT, signature: 'abc' }]) => ({ payload, signatures });

describe('container detection', () => {
it('recognises JWS and JWE containers without a uuid', () => {
expect(signedForm(jws('x'))).toBe(true);
expect(signedForm({ uuid: 'u', payload: 'x', signatures: [] })).toBe(false);
expect(encryptedForm({ ciphertext: 'c' })).toBe(true);
expect(encryptedForm({ uuid: 'u', ciphertext: 'c' })).toBe(false);
expect(signedPayload(jws(b64({ a: 1 })))).toEqual({ a: 1 });
});
});

describe('loading', () => {
it('keeps a JWS container exactly as given', () => {
const c = jws(b64(inner()));
const v = new Vcon(c);
expect(v.data).toEqual(c);
expect('uuid' in v.data).toBe(false);
expect('created_at' in v.data).toBe(false);
});

it('keeps a JWE container exactly as given', () => {
const c = { protected: 'eyJ', recipients: [{}], iv: 'a', ciphertext: 'b', tag: 'c' };
expect(new Vcon(c).data).toEqual(c);
});
});

describe('JWS validation', () => {
it('validates the payload as a vCon', () => {
const v = new Vcon(jws(b64(inner())));
expect(v.isValid()).toEqual({ valid: true, errors: [] });
const bad = inner();
delete bad.created_at;
expect(new Vcon(jws(b64(bad))).isValid().errors).toEqual(['Missing required field: created_at']);
});

it('reports a payload that is not base64url JSON', () => {
expect(new Vcon(jws('not*base64*json')).isValid().errors).toEqual([
"Signed vCon: 'payload' is not a base64url-encoded JSON object."
]);
expect(new Vcon(jws(b64([1]))).isValid().errors).toEqual([
"Signed vCon: 'payload' is not a base64url-encoded JSON object."
]);
});

it('checks the signatures array', () => {
const p = b64(inner());
expect(new Vcon(jws(p, [])).isValid().errors).toEqual(["Signed vCon: 'signatures' must be a non-empty array."]);
expect(new Vcon(jws(p, ['x'])).isValid().errors).toEqual(['Signed vCon: signatures[0] must be an object.']);
expect(new Vcon(jws(p, [{ header: 'x', signature: 5 }])).isValid().errors).toEqual([
"Signed vCon: signatures[0] is missing 'signature'.",
"Signed vCon: signatures[0] needs 'protected' or 'header'."
]);
});

it('accepts a signature with only an unprotected header', () => {
expect(new Vcon(jws(b64(inner()), [{ header: { alg: 'RS256' }, signature: 'abc' }])).isValid().valid).toBe(true);
});

it('runs the lawful basis check on the payload attachments', () => {
const body = inner();
body.extensions = ['lawful_basis'];
body.attachments = [{
purpose: 'lawful_basis', start: T, party: 0, session: 0, encoding: 'json', mediatype: 'application/json',
body: { lawful_basis: 'consent', expiration: '2020-01-01T00:00:00Z', purpose_grants: [{ purpose: 'x' }] }
}];
const v = new Vcon(jws(b64(body)));
expect(v.isValid().errors).toEqual([
'Attachment at index 0 (lawful_basis): Purpose grant 0: Missing required field in purpose grant: granted, Missing required field in purpose grant: granted_at'
]);
expect(v.getValidationWarnings()).toEqual(['Attachment at index 0 (lawful_basis): Lawful basis has expired']);
});

it('still validates a vCon signed in place (with uuid) as a vCon', () => {
const v = new Vcon(inner());
v.sign(Vcon.generateKeyPair().privateKey);
expect(v.isValid().valid).toBe(true);
});
});

describe('JWE validation', () => {
it('only warns that the content cannot be checked', () => {
const v = new Vcon({ protected: 'eyJ', recipients: [{}], iv: 'a', ciphertext: 'b', tag: 'c' });
expect(v.isValid()).toEqual({ valid: true, errors: [] });
expect(v.getValidationWarnings()).toEqual(['Encrypted vCon: the content cannot be validated without decrypting it.']);
});

it('checks member types and recipients', () => {
expect(validateVconDict({ protected: {}, iv: 1, ciphertext: null, tag: [], recipients: [] }).errors).toEqual([
"Encrypted vCon: 'ciphertext' must be a base64url string.",
"Encrypted vCon: 'iv' must be a base64url string.",
"Encrypted vCon: 'tag' must be a base64url string.",
"Encrypted vCon: 'recipients' must be a non-empty array.",
"Encrypted vCon: 'protected' must be a base64url string."
]);
expect(validateVconDict({ ciphertext: 'b', recipients: {} }).errors).toEqual([
"Encrypted vCon: 'recipients' must be a non-empty array."
]);
});

it('does not look at attachments next to the ciphertext', () => {
const v = new Vcon({ ciphertext: 'b', attachments: [{ purpose: 'lawful_basis', body: {} }] });
expect(v.isValid().valid).toBe(true);
});
});

describe('payload decoding follows Python base64.urlsafe_b64decode', () => {
it('skips characters outside the alphabet and accepts both alphabets', () => {
expect(decodeJsonPayload('!!' + b64({ a: 1 }) + ' \n')).toEqual({ a: 1 });
expect(decodeJsonPayload(Buffer.from('{"a":"?>"}').toString('base64'))).toEqual({ a: '?>' });
});

it('rejects a dangling quantum, non-ASCII input and non-UTF-8 bytes', () => {
expect(lenientBase64UrlDecode('AAAAA')).toBeUndefined();
expect(decodeJsonPayload(b64({ a: 1 }) + 'é')).toBeUndefined();
expect(decodeJsonPayload(Buffer.from([0xff, 0xfa, 0x7b, 0x7d]).toString('base64url'))).toBeUndefined();
expect(decodeJsonPayload(5)).toBeUndefined();
});
});
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
CORE_EVENT_TYPES,
RuleCode
} from './event';
import { validateVconDict, extensionsInUse, contentHashProblems } from './validation';
import { validateVconDict, extensionsInUse, contentHashProblems, signedForm, encryptedForm, signedPayload } from './validation';
import {
validateLawfulBasisAttachment,
validateLawfulBasisBody,
Expand Down Expand Up @@ -78,6 +78,9 @@ export {
validateEvent,
extensionsInUse,
contentHashProblems,
signedForm,
encryptedForm,
signedPayload,
validateLawfulBasisAttachment,
validateLawfulBasisBody,
LawfulBasisValidationResult,
Expand Down
71 changes: 71 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,77 @@ export function base64UrlDecodeToString(input: string): string {
return new TextDecoder().decode(bytes);
}

const B64_VALUES: Record<string, number> = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('').forEach((c, i) => {
B64_VALUES[c] = i;
});

/**
* Decode base64 or base64url the way Python's `base64.urlsafe_b64decode` does
* (non-strict binascii): characters outside the alphabet are skipped, decoding
* stops at complete padding, and a dangling partial quantum is an error
* (undefined). Non-ASCII input is an error too.
*/
export function lenientBase64UrlDecode(input: string): Uint8Array | undefined {
if ([...input].some(c => c.charCodeAt(0) > 0x7f)) return undefined;
const s = input.replace(/-/g, '+').replace(/_/g, '/');
const out: number[] = [];
let quadPos = 0;
let left = 0;
let pads = 0;
for (const c of s) {
if (c === '=') {
if (quadPos >= 2 && quadPos + ++pads >= 4) return Uint8Array.from(out);
continue;
}
const v = B64_VALUES[c];
if (v === undefined) continue;
pads = 0;
switch (quadPos) {
case 0:
left = v;
quadPos = 1;
break;
case 1:
out.push(((left << 2) | (v >> 4)) & 0xff);
left = v & 0x0f;
quadPos = 2;
break;
case 2:
out.push(((left << 4) | (v >> 2)) & 0xff);
left = v & 0x03;
quadPos = 3;
break;
default:
out.push(((left << 6) | v) & 0xff);
quadPos = 0;
}
}
return quadPos === 0 ? Uint8Array.from(out) : undefined;
}

/**
* The value of a JWS `payload` decoded as Python's
* `json.loads(base64.urlsafe_b64decode(raw + padding))` would, or undefined if
* that raises.
*/
export function decodeJsonPayload(raw: unknown): unknown {
if (typeof raw !== 'string') return undefined;
const bytes = lenientBase64UrlDecode(raw + '='.repeat((4 - (raw.length % 4)) % 4));
if (!bytes) return undefined;
let encoding = 'utf-8';
let start = 0;
if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) start = 3;
else if (bytes[0] === 0xff && bytes[1] === 0xfe) encoding = 'utf-16le';
else if (bytes[0] === 0xfe && bytes[1] === 0xff) encoding = 'utf-16be';
try {
const text = new TextDecoder(encoding, { fatal: true }).decode(bytes.subarray(start));
return JSON.parse(text.replace(/^\ufeff/, ''));
} catch {
return undefined;
}
}

/** Python-style repr for report messages: strings in single quotes, other values as JSON. */
export function repr(value: unknown): string {
if (typeof value === 'string') return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
Expand Down
70 changes: 68 additions & 2 deletions src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import { CORE_EVENT_TYPES, validateEvent } from './event';
import { SESSION_REFERENCE_TYPES, validateSession } from './session';
import { asList, dateTimeProblem, isIndex, isPlainObject, parseDateTime, pyRepr } from './util';
import { asList, dateTimeProblem, decodeJsonPayload, isIndex, isPlainObject, parseDateTime, pyRepr } from './util';

export const SYNTAX_VERSION = '0.5.0';

Expand Down Expand Up @@ -238,11 +238,77 @@ function scanRedactedRefs(obj: unknown, found: Set<number>): void {
}
}

/** Validate an unsigned vCon object. Returns `{ errors, warnings }`. */
/** True for a JWS General JSON Serialization container (section 6.2). */
export function signedForm(vcon: unknown): boolean {
return isPlainObject(vcon) && !('uuid' in vcon) && 'payload' in vcon && 'signatures' in vcon;
}

/** True for a JWE General JSON Serialization container (section 6.3). */
export function encryptedForm(vcon: unknown): boolean {
return isPlainObject(vcon) && !('uuid' in vcon) && 'ciphertext' in vcon;
}

/** The decoded JWS payload of a signed vCon, or undefined if it is not base64url JSON. */
export function signedPayload(vcon: Record<string, any>): unknown {
return decodeJsonPayload(vcon.payload);
}

function validateJws(
vcon: Record<string, any>,
dialogMimeTypes: string[]
): { errors: string[]; warnings: string[] } {
const errors: string[] = [];
const sigs = vcon.signatures;
if (!Array.isArray(sigs) || sigs.length === 0) {
errors.push("Signed vCon: 'signatures' must be a non-empty array.");
} else {
sigs.forEach((sig, n) => {
if (!isPlainObject(sig)) {
errors.push(`Signed vCon: signatures[${n}] must be an object.`);
return;
}
if (typeof sig.signature !== 'string') errors.push(`Signed vCon: signatures[${n}] is missing 'signature'.`);
if (typeof sig.protected !== 'string' && !isPlainObject(sig.header)) {
errors.push(`Signed vCon: signatures[${n}] needs 'protected' or 'header'.`);
}
});
}
const payload = signedPayload(vcon);
if (!isPlainObject(payload)) {
errors.push("Signed vCon: 'payload' is not a base64url-encoded JSON object.");
return { errors, warnings: [] };
}
const inner = validateVconDict(payload, dialogMimeTypes);
return { errors: [...errors, ...inner.errors], warnings: inner.warnings };
}

function validateJwe(vcon: Record<string, any>): { errors: string[]; warnings: string[] } {
const errors: string[] = [];
for (const member of ['ciphertext', 'iv', 'tag']) {
if (member in vcon && typeof vcon[member] !== 'string') {
errors.push(`Encrypted vCon: '${member}' must be a base64url string.`);
}
}
if ('recipients' in vcon && (!Array.isArray(vcon.recipients) || vcon.recipients.length === 0)) {
errors.push("Encrypted vCon: 'recipients' must be a non-empty array.");
}
if ('protected' in vcon && typeof vcon.protected !== 'string') {
errors.push("Encrypted vCon: 'protected' must be a base64url string.");
}
return { errors, warnings: ['Encrypted vCon: the content cannot be validated without decrypting it.'] };
}

/**
* Validate a vCon object. Returns `{ errors, warnings }`. A signed (JWS) vCon
* is checked as a JWS and its payload as a vCon; an encrypted (JWE) vCon is
* checked as a JWE only.
*/
export function validateVconDict(
vcon: Record<string, any>,
dialogMimeTypes: string[] = DIALOG_MIME_TYPES
): { errors: string[]; warnings: string[] } {
if (signedForm(vcon)) return validateJws(vcon, dialogMimeTypes);
if (encryptedForm(vcon)) return validateJwe(vcon);
const errors: string[] = [];
const warnings: string[] = [];

Expand Down
Loading
Loading