diff --git a/CHANGELOG.md b/CHANGELOG.md index 42c28e7..0b766db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## [1.0.5] - 2026-11-18 + +### Fixed +- `is_valid()` raised instead of reporting when a `lawful_basis` body was + malformed (a regression in 1.0.4, which started checking those bodies): an + `expiration` with no offset, a non-string `expiration`, `granted_at` or proof + `timestamp`, a purpose grant, proof mechanism, `content_hash` or `registry` + that is not an object, or a non-string `lawful_basis` value. These are now + validation errors; a timestamp with no offset is read as UTC. +- A `content_hash` with a trailing newline was accepted. +- A `created_at` or `updated_at` offset of 24 hours or more (accepted by + dateutil) is reported as invalid. +- Signed (JWS) and encrypted (JWE) vCons are kept exactly as given on load. The + constructor used to add `created_at` and empty arrays to the container, which + changed the document, and `is_valid()` reported them as missing `uuid`. Now a + signed vCon is validated as a JWS (non-empty `signatures`, each with + `signature` and `protected` or `header`) with its payload validated as a vCon, + and an encrypted vCon is checked as a JWE, with a warning that its content was + not validated. Appendix B6 and B7 now validate. + ## [1.0.4] - 2026-11-18 ### Fixed diff --git a/pyproject.toml b/pyproject.toml index b5ecf3d..b883c34 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "vcon" -version = "1.0.4" +version = "1.0.5" description = "The vCon library - vCon 0.5.0 (draft-ietf-vcon-vcon-core-05) specification implementation" authors = ["Thomas McCarthy-Howe "] license = "MIT" diff --git a/setup.py b/setup.py index b772c63..899008a 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name="vcon", - version="1.0.4", + version="1.0.5", author="Thomas McCarthy-Howe", author_email="ghostofbasho@gmail.com", description="The vCon library - vCon 0.5.0 (draft-ietf-vcon-vcon-core-05) specification implementation", diff --git a/src/vcon/extensions/lawful_basis/validation.py b/src/vcon/extensions/lawful_basis/validation.py index 8e85c0a..f001042 100644 --- a/src/vcon/extensions/lawful_basis/validation.py +++ b/src/vcon/extensions/lawful_basis/validation.py @@ -51,6 +51,29 @@ class ContentHashMismatchError(LawfulBasisValidationError): pass +def _fields(value: Any) -> Dict[str, Any]: + """A malformed (non-object) sub-object is checked as an empty one.""" + return value if isinstance(value, dict) else {} + + +def _member(value: Any, allowed: Any) -> bool: + try: + return value in allowed + except TypeError: # unhashable, e.g. a list + return False + + +def _parse_timestamp(value: Any) -> Optional[datetime]: + """ISO 8601 timestamp, or None. A value with no offset is read as UTC.""" + if not isinstance(value, str): + return None + try: + parsed = datetime.fromisoformat(value.replace('Z', '+00:00')) + except ValueError: + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + class LawfulBasisValidator(ExtensionValidator): """Validator for lawful basis extension.""" @@ -138,19 +161,18 @@ def _validate_lawful_basis_body(self, body: Dict[str, Any]) -> ValidationResult: # Validate lawful_basis if "lawful_basis" in body: lawful_basis = body["lawful_basis"] - if lawful_basis not in self.supported_lawful_bases: + if not _member(lawful_basis, self.supported_lawful_bases): result.add_error(f"Unsupported lawful basis: {lawful_basis}") # Validate expiration if "expiration" in body: expiration = body["expiration"] if expiration is not None: - try: - exp_dt = datetime.fromisoformat(expiration.replace('Z', '+00:00')) - if exp_dt <= datetime.now(timezone.utc): - result.add_warning("Lawful basis has expired") - except ValueError: + exp_dt = _parse_timestamp(expiration) + if exp_dt is None: result.add_error("Invalid expiration timestamp format") + elif exp_dt <= datetime.now(timezone.utc): + result.add_warning("Lawful basis has expired") # Validate purpose_grants if "purpose_grants" in body: @@ -196,6 +218,7 @@ def _validate_lawful_basis_body(self, body: Dict[str, Any]) -> ValidationResult: def _validate_purpose_grant(self, grant: Dict[str, Any]) -> ValidationResult: """Validate a purpose grant.""" result = ValidationResult(True) + grant = _fields(grant) required_fields = ["purpose", "granted", "granted_at"] for field in required_fields: @@ -207,11 +230,8 @@ def _validate_purpose_grant(self, grant: Dict[str, Any]) -> ValidationResult: result.add_error("granted field must be a boolean") # Validate granted_at timestamp - if "granted_at" in grant: - try: - datetime.fromisoformat(grant["granted_at"].replace('Z', '+00:00')) - except ValueError: - result.add_error("Invalid granted_at timestamp format") + if "granted_at" in grant and _parse_timestamp(grant["granted_at"]) is None: + result.add_error("Invalid granted_at timestamp format") # Validate conditions if "conditions" in grant: @@ -226,6 +246,7 @@ def _validate_purpose_grant(self, grant: Dict[str, Any]) -> ValidationResult: def _validate_content_hash(self, content_hash: Dict[str, Any]) -> ValidationResult: """Validate content hash information.""" result = ValidationResult(True) + content_hash = _fields(content_hash) required_fields = ["algorithm", "canonicalization", "value"] for field in required_fields: @@ -235,13 +256,13 @@ def _validate_content_hash(self, content_hash: Dict[str, Any]) -> ValidationResu # Validate algorithm if "algorithm" in content_hash: algorithm = content_hash["algorithm"] - if algorithm not in self.supported_hash_algorithms: + if not _member(algorithm, self.supported_hash_algorithms): result.add_warning(f"Hash algorithm {algorithm!r} is not one this library can verify") # Validate canonicalization if "canonicalization" in content_hash: canonicalization = content_hash["canonicalization"] - if canonicalization not in self.supported_canonicalization: + if not _member(canonicalization, self.supported_canonicalization): result.add_warning(f"Canonicalization method {canonicalization!r} is not one this library can apply") # Validate hash value format @@ -255,6 +276,7 @@ def _validate_content_hash(self, content_hash: Dict[str, Any]) -> ValidationResu def _validate_proof_mechanism(self, proof: Dict[str, Any]) -> ValidationResult: """Validate a proof mechanism.""" result = ValidationResult(True) + proof = _fields(proof) required_fields = ["proof_type", "timestamp", "proof_data"] for field in required_fields: @@ -264,15 +286,12 @@ def _validate_proof_mechanism(self, proof: Dict[str, Any]) -> ValidationResult: # Validate proof_type if "proof_type" in proof: proof_type = proof["proof_type"] - if proof_type not in self.supported_proof_types: + if not _member(proof_type, self.supported_proof_types): result.add_warning(f"Proof type {proof_type!r} is not one of the types the draft defines") # Validate timestamp - if "timestamp" in proof: - try: - datetime.fromisoformat(proof["timestamp"].replace('Z', '+00:00')) - except ValueError: - result.add_error("Invalid timestamp format in proof mechanism") + if "timestamp" in proof and _parse_timestamp(proof["timestamp"]) is None: + result.add_error("Invalid timestamp format in proof mechanism") # Validate proof_data if "proof_data" in proof: @@ -284,6 +303,7 @@ def _validate_proof_mechanism(self, proof: Dict[str, Any]) -> ValidationResult: def _validate_registry_info(self, registry: Dict[str, Any]) -> ValidationResult: """Validate registry information.""" result = ValidationResult(True) + registry = _fields(registry) required_fields = ["type", "url"] for field in required_fields: @@ -293,7 +313,7 @@ def _validate_registry_info(self, registry: Dict[str, Any]) -> ValidationResult: # Validate registry type if "type" in registry: registry_type = registry["type"] - if registry_type not in ["scitt"]: # Add more types as they're defined + if registry_type != "scitt": # Add more types as they're defined result.add_warning(f"Unknown registry type: {registry_type}") # Validate URL format (basic validation) diff --git a/src/vcon/validation.py b/src/vcon/validation.py index fc73338..0f9410e 100644 --- a/src/vcon/validation.py +++ b/src/vcon/validation.py @@ -6,8 +6,11 @@ from __future__ import annotations +import base64 +import binascii import json import re +from datetime import timedelta from typing import Any, Dict, List, Set, Tuple from dateutil import parser @@ -74,7 +77,7 @@ def content_hash_problems(value: Any) -> List[str]: if not isinstance(token, str): problems.append(f"{token!r} is not a string") continue - m = _CONTENT_HASH_RE.match(token) + m = _CONTENT_HASH_RE.fullmatch(token) if not m: problems.append(f"{token!r} is not of the form '-'") continue @@ -212,10 +215,74 @@ def _scan_redacted_refs(obj: Any, found: Set[int]) -> None: _scan_redacted_refs(v, found) +def signed_form(vcon: Any) -> bool: + """True for a JWS General JSON Serialization container (section 6.2).""" + return isinstance(vcon, dict) and "uuid" not in vcon and "payload" in vcon and "signatures" in vcon + + +def encrypted_form(vcon: Any) -> bool: + """True for a JWE General JSON Serialization container (section 6.3).""" + return isinstance(vcon, dict) and "uuid" not in vcon and "ciphertext" in vcon + + +def signed_payload(vcon: Dict[str, Any]) -> Any: + """The decoded JWS payload of a signed vCon, or None if it is not base64url JSON.""" + raw = vcon.get("payload") + if not isinstance(raw, str): + return None + try: + return json.loads(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))) + except (ValueError, binascii.Error, UnicodeDecodeError): + return None + + +def _validate_jws(vcon: Dict[str, Any], dialog_mime_types: List[str]) -> Tuple[List[str], List[str]]: + errors: List[str] = [] + sigs = vcon.get("signatures") + if not isinstance(sigs, list) or not sigs: + errors.append("Signed vCon: 'signatures' must be a non-empty array.") + else: + for n, sig in enumerate(sigs): + if not isinstance(sig, dict): + errors.append(f"Signed vCon: signatures[{n}] must be an object.") + continue + if not isinstance(sig.get("signature"), str): + errors.append(f"Signed vCon: signatures[{n}] is missing 'signature'.") + if not isinstance(sig.get("protected"), str) and not isinstance(sig.get("header"), dict): + errors.append(f"Signed vCon: signatures[{n}] needs 'protected' or 'header'.") + payload = signed_payload(vcon) + if not isinstance(payload, dict): + errors.append("Signed vCon: 'payload' is not a base64url-encoded JSON object.") + return errors, [] + inner_errors, inner_warnings = validate_vcon_dict(payload, dialog_mime_types) + return errors + inner_errors, inner_warnings + + +def _validate_jwe(vcon: Dict[str, Any]) -> Tuple[List[str], List[str]]: + errors: List[str] = [] + for member in ("ciphertext", "iv", "tag"): + if member in vcon and not isinstance(vcon[member], str): + errors.append(f"Encrypted vCon: '{member}' must be a base64url string.") + recipients = vcon.get("recipients") + if "recipients" in vcon and (not isinstance(recipients, list) or not recipients): + errors.append("Encrypted vCon: 'recipients' must be a non-empty array.") + if "protected" in vcon and not isinstance(vcon["protected"], str): + errors.append("Encrypted vCon: 'protected' must be a base64url string.") + return errors, ["Encrypted vCon: the content cannot be validated without decrypting it."] + + def validate_vcon_dict( vcon: Dict[str, Any], dialog_mime_types: List[str] ) -> Tuple[List[str], List[str]]: - """Validate an unsigned vCon dict. Returns ``(errors, warnings)``.""" + """Validate a vCon dict. 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. + """ + if signed_form(vcon): + return _validate_jws(vcon, dialog_mime_types) + if encrypted_form(vcon): + return _validate_jwe(vcon) errors: List[str] = [] warnings: List[str] = [] @@ -226,7 +293,14 @@ def validate_vcon_dict( for ts in ("created_at", "updated_at"): if ts in vcon: try: - parser.parse(vcon[ts]) + parsed = parser.parse(vcon[ts]) + offset = parsed.utcoffset() + if offset is not None and abs(offset) >= timedelta(hours=24): + # dateutil accepts these; datetime (and RFC 3339) do not. + raise ValueError( + "offset must be a timedelta strictly between " + "-timedelta(hours=24) and timedelta(hours=24)." + ) except Exception as e: errors.append( f"Invalid {ts} format. Must be an ISO 8601 datetime string: {str(e)}" diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index c7e5c3c..8584917 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -28,7 +28,7 @@ MigrationReport, migrate_0_4_0_to_0_5_0 as _migrate_0_4_0_to_0_5_0, ) -from .validation import validate_vcon_dict +from .validation import encrypted_form, signed_form, signed_payload, validate_vcon_dict # Set up logger logger = logging.getLogger(__name__) @@ -388,6 +388,13 @@ def __init__( self.vcon_dict = json.loads(json.dumps(vcon_dict)) return + if signed_form(vcon_dict) or encrypted_form(vcon_dict): + # 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. is_valid() checks it. + self.vcon_dict = json.loads(json.dumps(vcon_dict)) + return + # Version field is now optional - no version management required # Handle created_at @@ -2316,17 +2323,26 @@ def get_validation_warnings(self) -> List[str]: def _validate_all(self) -> Tuple[List[str], List[str]]: """Core rules plus the body of every lawful_basis attachment.""" errors, warnings = validate_vcon_dict(self.vcon_dict, Dialog.MIME_TYPES) + # For a signed vCon the attachments are in the payload; an encrypted + # one cannot be read. + content = signed_payload(self.vcon_dict) if signed_form(self.vcon_dict) else self.vcon_dict + if encrypted_form(self.vcon_dict) or not isinstance(content, dict): + content = {} if EXTENSIONS_AVAILABLE: from .extensions.lawful_basis.validation import LawfulBasisValidator validator = LawfulBasisValidator() - attachments = self.vcon_dict.get("attachments") + attachments = content.get("attachments") for i, attachment in enumerate(attachments if isinstance(attachments, list) else []): if not isinstance(attachment, dict) or attachment.get("purpose") != "lawful_basis": continue - if isinstance(self.vcon_dict.get("redacted_from"), dict) and "body" not in attachment: + if isinstance(content.get("redacted_from"), dict) and "body" not in attachment: continue # Scope (party, dialog/session) is checked by the core rules above. - result = validator.validate_attachment(attachment) + try: + result = validator.validate_attachment(attachment) + except Exception as e: # a malformed body must not make is_valid() raise + errors.append(f"Attachment at index {i} (lawful_basis): body could not be checked: {e}") + continue errors.extend(f"Attachment at index {i} (lawful_basis): {e}" for e in result.errors) warnings.extend( f"Attachment at index {i} (lawful_basis): {w}" for w in result.warnings diff --git a/tests/test_fixes_1_0_5.py b/tests/test_fixes_1_0_5.py new file mode 100644 index 0000000..08dc1fd --- /dev/null +++ b/tests/test_fixes_1_0_5.py @@ -0,0 +1,84 @@ +"""Regression tests for the 1.0.5 fixes.""" + +import copy +import json +from pathlib import Path + +import pytest + +from vcon import Vcon, Session, compute_content_hash +from vcon.party import Party +from vcon.validation import content_hash_problems + +T = "2026-01-01T00:00:00Z" +EXAMPLES = Path(__file__).parent / "schema" / "examples" +GRANT = {"purpose": "recording", "granted": True, "granted_at": T} + + +def _with_basis(body): + v = Vcon.build_new() + v.add_party(Party(name="Alice")) + v.add_session(Session(start=T, parties=[0])) + v.add_extension("lawful_basis") + v.vcon_dict["attachments"].append({ + "purpose": "lawful_basis", "start": T, "party": 0, "session": [0], + "encoding": "json", "mediatype": "application/json", "body": body, + }) + return v + + +@pytest.mark.parametrize("body,expected", [ + ({"lawful_basis": "consent", "expiration": "2099-01-01", "purpose_grants": [GRANT]}, None), + ({"lawful_basis": "consent", "expiration": 5, "purpose_grants": [GRANT]}, "Invalid expiration timestamp format"), + ({"lawful_basis": "consent", "expiration": None, "purpose_grants": ["x"]}, + "Purpose grant 0: Missing required field in purpose grant: purpose"), + ({"lawful_basis": ["consent"], "expiration": None, "purpose_grants": [GRANT]}, "Unsupported lawful basis"), + ({"lawful_basis": "consent", "expiration": None, + "purpose_grants": [dict(GRANT, granted_at=1)]}, "Invalid granted_at timestamp format"), + ({"lawful_basis": "consent", "expiration": None, "purpose_grants": [GRANT], + "proof_mechanisms": [{"proof_type": ["x"], "timestamp": None, "proof_data": {}}]}, + "Invalid timestamp format in proof mechanism"), + ({"lawful_basis": "consent", "expiration": None, "purpose_grants": [GRANT], + "content_hash": "sha-256:abc", "registry": 7}, "Missing required field in content_hash"), +]) +def test_malformed_lawful_basis_bodies_are_reported_not_raised(body, expected): + ok, errors = _with_basis(body).is_valid() + if expected is None: + assert ok, errors + else: + assert not ok and any(expected in e for e in errors), errors + + +def test_content_hash_with_trailing_newline_is_rejected(): + h = compute_content_hash(b"x") + assert content_hash_problems(h) == [] + assert content_hash_problems(h + "\n") + + +def test_created_at_offset_of_24_hours_is_invalid(): + v = Vcon({"vcon": "0.5.0", "uuid": "01928e10-193e-8231-b9a2-279e0d16bc46", + "created_at": "2026-01-01T00:00:00+24:00"}) + ok, errors = v.is_valid() + assert not ok and any("offset must be a timedelta" in e for e in errors) + + +@pytest.mark.parametrize("name", ["B6-signed", "B7-encrypted"]) +def test_jws_and_jwe_containers_are_kept_and_validated(name): + raw = json.loads((EXAMPLES / f"{name}.json").read_text()) + v = Vcon(copy.deepcopy(raw)) + assert v.to_dict() == raw # nothing added (no uuid, created_at or arrays) + assert v.is_valid() == (True, []) + + +def test_signed_payload_is_validated(): + raw = json.loads((EXAMPLES / "B6-signed.json").read_text()) + raw["payload"] = "not base64url json" + assert not Vcon(raw).is_valid()[0] + raw = json.loads((EXAMPLES / "B6-signed.json").read_text()) + raw["signatures"] = [] + assert any("signatures" in e for e in Vcon(raw).is_valid()[1]) + + +def test_encrypted_vcon_warns_that_content_is_unchecked(): + raw = json.loads((EXAMPLES / "B7-encrypted.json").read_text()) + assert any("cannot be validated" in w for w in Vcon(raw).get_validation_warnings())