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
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 <ghostofbasho@gmail.com>"]
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
60 changes: 40 additions & 20 deletions src/vcon/extensions/lawful_basis/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand Down
80 changes: 77 additions & 3 deletions src/vcon/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 '<algorithm>-<base64url digest>'")
continue
Expand Down Expand Up @@ -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] = []

Expand All @@ -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)}"
Expand Down
24 changes: 20 additions & 4 deletions src/vcon/vcon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading