diff --git a/CHANGELOG.md b/CHANGELOG.md index e268a85..729f3c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 `-`, 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. @@ -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 diff --git a/README.md b/README.md index f3c67b9..b445f32 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/__tests__/jws-jwe-validation.test.ts b/src/__tests__/jws-jwe-validation.test.ts new file mode 100644 index 0000000..ae90f7b --- /dev/null +++ b/src/__tests__/jws-jwe-validation.test.ts @@ -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 { + 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(); + }); +}); diff --git a/src/index.ts b/src/index.ts index aa1ced2..4c370aa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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, @@ -78,6 +78,9 @@ export { validateEvent, extensionsInUse, contentHashProblems, + signedForm, + encryptedForm, + signedPayload, validateLawfulBasisAttachment, validateLawfulBasisBody, LawfulBasisValidationResult, diff --git a/src/util.ts b/src/util.ts index f17d816..cb50865 100644 --- a/src/util.ts +++ b/src/util.ts @@ -208,6 +208,77 @@ export function base64UrlDecodeToString(input: string): string { return new TextDecoder().decode(bytes); } +const B64_VALUES: Record = {}; +'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, "\\'")}'`; diff --git a/src/validation.ts b/src/validation.ts index 33971fa..966d34b 100644 --- a/src/validation.ts +++ b/src/validation.ts @@ -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'; @@ -238,11 +238,77 @@ function scanRedactedRefs(obj: unknown, found: Set): 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): unknown { + return decodeJsonPayload(vcon.payload); +} + +function validateJws( + vcon: Record, + 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): { 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, 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[] = []; diff --git a/src/vcon.ts b/src/vcon.ts index a4b0b9f..c862da9 100644 --- a/src/vcon.ts +++ b/src/vcon.ts @@ -21,9 +21,9 @@ import { Dialog as DialogClass } from './dialog'; import { Session as SessionClass } from './session'; import { Event as EventClass } from './event'; import { migrate040To050, MigrationReport } from './migration'; -import { validateVconDict } from './validation'; +import { encryptedForm, signedForm, signedPayload, validateVconDict } from './validation'; import { validateLawfulBasisAttachment } from './lawful-basis'; -import { base64UrlDecodeToString, clone, isPlainObject, warn } from './util'; +import { base64UrlDecodeToString, clone, decodeJsonPayload, isPlainObject, warn } from './util'; /** A JWS used `alg` "none" (forbidden by core-05) or an unsupported algorithm. */ export class AlgorithmNotPermittedError extends Error { @@ -66,7 +66,7 @@ function isLegacy040(dict: any): boolean { if (dict.vcon === LEGACY_VCON_VERSION) return true; if (!('vcon' in dict) && typeof dict.payload === 'string' && 'signatures' in dict) { try { - const payload = JSON.parse(base64UrlDecodeToString(dict.payload)); + const payload = decodeJsonPayload(dict.payload); return isPlainObject(payload) && payload.vcon === LEGACY_VCON_VERSION; } catch { return false; @@ -152,6 +152,14 @@ export class Vcon { return; } + if (signedForm(input) || encryptedForm(input)) { + // A JWS or JWE container (core-05 sections 6.2, 6.3) is kept exactly as + // given: adding uuid, created_at or empty arrays would change (and for + // JWS, invalidate) the document. isValid() checks it. + this.data = clone(input) as VconData; + return; + } + const created = input.created_at instanceof Date ? input.created_at.toISOString() : input.created_at; this.data = { uuid: input.uuid || uuidv4(), @@ -601,10 +609,14 @@ export class Vcon { private validateAll(): { errors: string[]; warnings: string[] } { const data = clone(this.data) as Record; const { errors, warnings } = validateVconDict(data); - const attachments = Array.isArray(data.attachments) ? data.attachments : []; + // For a signed vCon the attachments are in the payload; an encrypted one cannot be read. + let content: unknown = signedForm(data) ? signedPayload(data) : data; + if (encryptedForm(data) || !isPlainObject(content)) content = {}; + const body = content as Record; + const attachments = Array.isArray(body.attachments) ? body.attachments : []; attachments.forEach((attachment: unknown, i: number) => { if (!isPlainObject(attachment) || attachment.purpose !== 'lawful_basis') return; - if (isPlainObject(data.redacted_from) && !('body' in attachment)) return; + if (isPlainObject(body.redacted_from) && !('body' in attachment)) return; // Scope (party, dialog/session) is checked by the core rules above. const result = validateLawfulBasisAttachment(attachment); errors.push(...result.errors.map(e => `Attachment at index ${i} (lawful_basis): ${e}`));