From 28f23d1cd2b18e75a5cc91fc2160c4c6644efee1 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:03:56 -0500 Subject: [PATCH 01/12] Port the library to vCon core-05 (syntax 0.5.0) Add Session, Session_Reference and Event objects with the top-level sessions and events arrays, and enforce the per-event-type parameter table in validation. Rename redacted/amended to redacted_from/amended_from, add Attachment.session, and require party plus dialog or session on attachments. Remove the transfer and recording-set dialog types and the party_history, originator and transfer parameters from Dialog; allow empty Dialog objects. Reject JWS alg "none" on sign and verify. Make is_valid() require that extensions lists every extension in use, that a Session exists when there is dialog or events, and that references resolve. Add migrate_0_4_0_to_0_5_0(), a table-driven implementation of Appendix A.1 that keeps every index stable by leaving removed dialogs as {} and returns a report of inferred values, fallbacks and unresolved items. Readers migrate documents that declare 0.4.0 on load. Vendor the core-05 Appendix C schema and Appendix B examples for the tests. Co-Authored-By: Claude Opus 5.5 --- src/vcon/__init__.py | 27 +- src/vcon/dialog.py | 116 +- src/vcon/event.py | 312 +++++ src/vcon/migration.py | 1094 ++++++++++++++++ src/vcon/party.py | 70 - src/vcon/session.py | 178 +++ src/vcon/validation.py | 493 +++++++ src/vcon/vcon.py | 681 ++++++---- tests/schema/SOURCE.md | 26 +- .../B1-two-party-call-inline-recording.json | 71 + .../examples/B2-email-thread-multipart.json | 58 + .../schema/examples/B3-email-thread-text.json | 71 + .../B4-two-party-call-external-recording.json | 45 + .../B5-two-party-call-with-analysis.json | 1075 ++++++++++++++++ tests/schema/examples/B6-signed.json | 17 + tests/schema/examples/B7-encrypted.json | 15 + tests/schema/examples/B8-redacted.json | 165 +++ tests/schema/examples/B9-amended-signed.json | 59 + tests/schema/vcon_json_schema.json | 1138 +++++++++++------ tests/test_core05_changes.py | 388 ++++++ tests/test_core05_examples.py | 128 ++ tests/test_dialog.py | 44 +- tests/test_dialog_extra.py | 39 +- tests/test_migration_0_4_0.py | 764 +++++++++++ tests/test_party.py | 44 +- tests/test_schema_compliance.py | 20 +- tests/test_session_event.py | 281 ++++ tests/test_vcon.py | 106 +- 28 files changed, 6568 insertions(+), 957 deletions(-) create mode 100644 src/vcon/event.py create mode 100644 src/vcon/migration.py create mode 100644 src/vcon/session.py create mode 100644 src/vcon/validation.py create mode 100644 tests/schema/examples/B1-two-party-call-inline-recording.json create mode 100644 tests/schema/examples/B2-email-thread-multipart.json create mode 100644 tests/schema/examples/B3-email-thread-text.json create mode 100644 tests/schema/examples/B4-two-party-call-external-recording.json create mode 100644 tests/schema/examples/B5-two-party-call-with-analysis.json create mode 100644 tests/schema/examples/B6-signed.json create mode 100644 tests/schema/examples/B7-encrypted.json create mode 100644 tests/schema/examples/B8-redacted.json create mode 100644 tests/schema/examples/B9-amended-signed.json create mode 100644 tests/test_core05_changes.py create mode 100644 tests/test_core05_examples.py create mode 100644 tests/test_migration_0_4_0.py create mode 100644 tests/test_session_event.py diff --git a/src/vcon/__init__.py b/src/vcon/__init__.py index 1ab223c..8e79e9d 100644 --- a/src/vcon/__init__.py +++ b/src/vcon/__init__.py @@ -1,4 +1,25 @@ -from .vcon import Vcon -from .dialog import compute_content_hash, parse_content_hash_algorithm +from .vcon import Vcon, AlgorithmNotPermittedError +from .dialog import Dialog, compute_content_hash, parse_content_hash_algorithm +from .session import Session, SessionReference +from .event import Event +from .migration import ( + MigrationError, + MigrationReport, + MigrationResult, + migrate_0_4_0_to_0_5_0, +) -__all__ = ["Vcon", "compute_content_hash", "parse_content_hash_algorithm"] +__all__ = [ + "Vcon", + "Dialog", + "Session", + "SessionReference", + "Event", + "AlgorithmNotPermittedError", + "MigrationError", + "MigrationReport", + "MigrationResult", + "migrate_0_4_0_to_0_5_0", + "compute_content_hash", + "parse_content_hash_algorithm", +] diff --git a/src/vcon/dialog.py b/src/vcon/dialog.py index 71121b5..5ec79c7 100644 --- a/src/vcon/dialog.py +++ b/src/vcon/dialog.py @@ -6,7 +6,6 @@ import tempfile from datetime import datetime from typing import Optional, List, Dict, Union, Any, Tuple -from .party import PartyHistory from dateutil import parser MIME_TYPES = [ @@ -131,6 +130,24 @@ def parse_content_hash_algorithm(content_hash: str) -> Optional[str]: return None +_REMOVED_DIALOG_PARAMETERS = frozenset({ + "originator", "party_history", "transfer", "transferee", "transferor", + "transfer_target", "original", "consultation", "target_dialog", + "recordings", "recording_set", +}) + + +def _reject_removed_parameters(kwargs: Dict[str, Any]) -> None: + removed = sorted(set(kwargs) & _REMOVED_DIALOG_PARAMETERS) + if removed: + raise ValueError( + f"Dialog parameter(s) {removed} were removed in vCon 0.5.0: " + "originator belongs to the Session Object; party_history and the transfer " + "parameters are Event Objects; recordings/recording_set are replaced by " + "the Session Object." + ) + + class Dialog: """ A class representing a dialog segment in a vCon conversation. @@ -138,7 +155,6 @@ class Dialog: A dialog represents a piece of conversation content, which can be: - text: Text-based communication (email, chat, SMS) - recording: Audio/video recording of the conversation - - transfer: Call transfer operation between parties - incomplete: Failed or incomplete conversation setup - video: Video content with metadata @@ -152,19 +168,16 @@ class Dialog: - Text formats: Plain text, multipart messages - Images: JPEG, TIFF, PDF - New in vCon 0.4.0: - - session_id: Session identifier for tracking - - content_hash: Hash for externally referenced files (replaces alg/signature) - - application: Application identifier for the dialog - - message_id: Message identifier for email/text dialogs - - Updated media type validation with specification-compliant types - - New disposition values for incomplete dialogs - - Party history with event tracking (join, drop, hold, unhold, mute, unmute) - - Transfer dialog features: - - transfer_target: Target party for transfers - - target_dialog: Target dialog reference - - Support for consultation and original call tracking + Changes in vCon 0.5.0 (draft-ietf-vcon-vcon-core-05): + - ``parties`` lists the contributors only. The receivers are in the + ``parties`` of the Session Object that references the dialog. + - ``originator`` moved to the Session Object. + - ``party_history`` was replaced by Event Objects (``vcon.event.Event``). + - The ``transfer`` and ``recording-set`` dialog types were removed. Transfers + are Events; a recording set is a Session. + - An empty Dialog Object (``Dialog.placeholder()``, serialized as ``{}``) + holds a position in the dialog array so that indices do not change. + - ``redacted_segments`` was added. """ MIME_TYPES = [ @@ -204,7 +217,6 @@ class Dialog: VALID_TYPES = [ "recording", "text", - "transfer", "incomplete", "audio", "video" @@ -225,20 +237,12 @@ def __init__( type: str, start: Union[datetime, str], parties: List[int], - originator: Optional[int] = None, mediatype: Optional[str] = None, filename: Optional[str] = None, body: Optional[str] = None, encoding: Optional[str] = None, url: Optional[str] = None, disposition: Optional[str] = None, - party_history: Optional[List[PartyHistory]] = None, - transferee: Optional[int] = None, - transferor: Optional[int] = None, - transfer_target: Optional[int] = None, - original: Optional[int] = None, - consultation: Optional[int] = None, - target_dialog: Optional[int] = None, campaign: Optional[str] = None, interaction: Optional[str] = None, skill: Optional[str] = None, @@ -246,7 +250,6 @@ def __init__( meta: Optional[dict] = None, # New parameters for signaling and extended functionality metadata: Optional[Dict[str, Any]] = None, - transfer: Optional[Dict[str, Any]] = None, signaling: Optional[Dict[str, Any]] = None, # New parameters for video metadata resolution: Optional[str] = None, @@ -260,18 +263,17 @@ def __init__( # Additional fields from specification application: Optional[str] = None, message_id: Optional[str] = None, + redacted_segments: Optional[List[Dict[str, Any]]] = None, **kwargs, ) -> None: """ Initialize a Dialog object. - :param type: the type of the dialog (e.g. "text", "recording", "transfer", "incomplete", "video") + :param type: the type of the dialog (e.g. "text", "recording", "incomplete", "video") :type type: str :param start: the start time of the dialog :type start: datetime - :param parties: the parties involved in the dialog + :param parties: the parties that contributed to the dialog (the receivers are in the Session Object) :type parties: List[int] - :param originator: the party that originated the dialog - :type originator: int or None :param mediatype: the MIME type of the dialog body :type mediatype: str or None :param filename: the filename of the dialog body @@ -284,20 +286,6 @@ def __init__( :type url: str or None :param disposition: the disposition of the dialog :type disposition: str or None - :param party_history: the history of parties involved in the dialog - :type party_history: List[PartyHistory] or None - :param transferee: the party that the dialog was transferred to - :type transferee: int or None - :param transferor: the party that transferred the dialog - :type transferor: int or None - :param transfer_target: the target of the transfer - :type transfer_target: int or None - :param original: the original dialog - :type original: int or None - :param consultation: the consultation dialog - :type consultation: int or None - :param target_dialog: the target dialog - :type target_dialog: int or None :param campaign: the campaign that the dialog is associated with :type campaign: str or None :param interaction: the interaction that the dialog is associated with @@ -310,8 +298,6 @@ def __init__( :type meta: dict or None :param metadata: structured metadata for the dialog (newer format) :type metadata: dict or None - :param transfer: transfer-specific information - :type transfer: dict or None :param signaling: signaling-specific information :type signaling: dict or None :param resolution: video resolution (e.g., "1920x1080") @@ -332,9 +318,13 @@ def __init__( :type application: str or None :param message_id: Message identifier for email/text dialogs :type message_id: str or None + :param redacted_segments: Redacted_segments Objects (start, end, optional parties) + :type redacted_segments: list or None :param kwargs: Additional attributes to be set on the dialog """ + _reject_removed_parameters(kwargs) + # Validate dialog type if type not in self.VALID_TYPES: raise ValueError(f"Invalid dialog type: {type}. Must be one of {self.VALID_TYPES}") @@ -416,6 +406,10 @@ def to_dict(self): :return: a dictionary containing all non-None Dialog object attributes :rtype: dict """ + # An empty placeholder Dialog Object serializes as {}. + if getattr(self, "_placeholder", False): + return {} + # Check to see if the start time provided. If not, # set the start time to the current time if not hasattr(self, "start"): @@ -424,19 +418,14 @@ def to_dict(self): # Get all attributes of the object dialog_dict = self.__dict__.copy() - # Handle party_history specially - if hasattr(self, "party_history") and self.party_history: - dialog_dict["party_history"] = [ - party_history.to_dict() for party_history in self.party_history - ] - # meta/metadata are always initialized to {} for backward-compat # attribute access (see __init__); omit them from the serialized # form when still empty rather than emitting empty placeholders. return { k: v for k, v in dialog_dict.items() - if v is not None and not (k in ("meta", "metadata") and v == {}) + if v is not None and k != "_placeholder" + and not (k in ("meta", "metadata") and v == {}) } def add_external_data(self, url: str, filename: str, mediatype: str) -> None: @@ -524,14 +513,25 @@ def is_recording(self) -> bool: """ return hasattr(self, "type") and self.type == "recording" - def is_transfer(self) -> bool: + def is_placeholder(self) -> bool: """ - Check if the dialog is a transfer dialog. - :return: True if the dialog is a transfer dialog, False otherwise - :rtype: bool + Check if the dialog is an empty placeholder Dialog Object (``{}``). """ - return hasattr(self, "type") and self.type == "transfer" - + return getattr(self, "_placeholder", False) + + @classmethod + def placeholder(cls) -> "Dialog": + """ + Create an empty Dialog Object (core-05 section 4.5.1). + + It has no parameters and no meaning; it holds a position in the dialog + array so that the indices of the other Dialog Objects, and the references + to them, do not change. It serializes as ``{}``. + """ + obj = cls.__new__(cls) + obj._placeholder = True + return obj + def is_incomplete(self) -> bool: """ Check if the dialog is an incomplete dialog. diff --git a/src/vcon/event.py b/src/vcon/event.py new file mode 100644 index 0000000..aa36061 --- /dev/null +++ b/src/vcon/event.py @@ -0,0 +1,312 @@ +"""Event Object (draft-ietf-vcon-vcon-core-05, section 4.3) and the events array. + +An Event is a point-in-time occurrence inside one or more Sessions: a party +joining or dropping, a key press, a call transfer step, or a change of the +parties contributing to a recording channel. + +The per-type parameter applicability table of section 4.3.1.5 is held in +``EVENT_PARAMETER_RULES`` and enforced by :func:`validate_event` and by +``Vcon.is_valid()``. + +Rule codes (section 4.3.1.5): + +* ``M`` the parameter MUST be present +* ``O`` the parameter is optional +* ``SN`` the parameter SHOULD NOT be present (reported as a warning) +* ``X`` the parameter MUST NOT be present +""" + +from __future__ import annotations + +import logging +from typing import Any, Dict, List, Optional, Tuple, Union + +from dateutil import parser +from datetime import datetime + +logger = logging.getLogger(__name__) + +PARTY_EVENT_TYPES = ("join", "drop", "hold", "unhold", "mute", "unmute") +KEY_EVENT_TYPES = ("keydown", "keyup") +TRANSFER_EVENT_TYPES = ( + "consultation-start", + "blind-transfer", + "consultative-transfer", + "transfer-abandoned", +) +CHANNEL_CONTRIBUTORS_EVENT_TYPE = "channel-contributors" + +#: Every Event type token defined by core-05 (section 4.3.1). +CORE_EVENT_TYPES = ( + PARTY_EVENT_TYPES + + KEY_EVENT_TYPES + + TRANSFER_EVENT_TYPES + + (CHANNEL_CONTRIBUTORS_EVENT_TYPE,) +) + +#: Event parameters other than ``type`` and ``time``, in the order of 4.3. +EVENT_PARAMETERS = ( + "type", + "time", + "sessions", + "party", + "dialog", + "channel", + "contributors", + "button", + "transferee", + "transfer_target", + "consultation", + "target_session", +) + +_X_ALL_TRANSFER = { + "transferee": "X", + "transfer_target": "X", + "consultation": "X", + "target_session": "X", +} + + +def _rules(**overrides: str) -> Dict[str, str]: + base = { + "type": "M", + "time": "M", + "sessions": "M", + "party": "M", + "dialog": "SN", + "channel": "X", + "contributors": "X", + "button": "X", + } + base.update(_X_ALL_TRANSFER) + base.update(overrides) + return base + + +#: Parameter applicability by Event type (section 4.3.1.5 tables). +EVENT_PARAMETER_RULES: Dict[str, Dict[str, str]] = {} +for _t in PARTY_EVENT_TYPES: + EVENT_PARAMETER_RULES[_t] = _rules() +for _t in KEY_EVENT_TYPES: + EVENT_PARAMETER_RULES[_t] = _rules(button="M") +EVENT_PARAMETER_RULES["consultation-start"] = _rules( + transferee="M", transfer_target="M", consultation="M", target_session="X" +) +EVENT_PARAMETER_RULES["blind-transfer"] = _rules( + transferee="M", transfer_target="M", consultation="X", target_session="M" +) +EVENT_PARAMETER_RULES["consultative-transfer"] = _rules( + transferee="M", transfer_target="M", consultation="M", target_session="M" +) +EVENT_PARAMETER_RULES["transfer-abandoned"] = _rules( + transferee="M", transfer_target="O", consultation="O", target_session="X" +) +EVENT_PARAMETER_RULES[CHANNEL_CONTRIBUTORS_EVENT_TYPE] = { + "type": "M", + "time": "M", + "sessions": "X", + "party": "X", + "dialog": "M", + "channel": "M", + "contributors": "O", + "button": "X", + "transferee": "X", + "transfer_target": "X", + "consultation": "X", + "target_session": "X", +} +del _t + + +def _is_index(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +def _is_index_or_list(value: Any) -> bool: + if _is_index(value): + return True + return isinstance(value, list) and all(_is_index(v) for v in value) + + +def validate_event( + event: Any, + *, + party_count: Optional[int] = None, + dialog_count: Optional[int] = None, + session_count: Optional[int] = None, + label: str = "Event", +) -> Tuple[List[str], List[str]]: + """Validate one Event Object dict against core-05 section 4.3. + + Returns ``(errors, warnings)``. ``SN`` violations are warnings, ``M`` and + ``X`` violations are errors. An Event whose type is not a core token is only + checked for ``type`` and ``time`` (section 2.5: it belongs to an extension). + Index values are range-checked only when the matching count is supplied. + """ + errors: List[str] = [] + warnings: List[str] = [] + if not isinstance(event, dict): + return [f"{label} must be a dictionary."], warnings + + etype = event.get("type") + if not isinstance(etype, str) or not etype: + errors.append(f"{label} is missing required field: type") + if "time" not in event: + errors.append(f"{label} is missing required field: time") + else: + try: + if not isinstance(event["time"], str): + raise ValueError("not a string") + parser.parse(event["time"]) + except Exception: + errors.append(f"{label} has an invalid 'time' format. Must be an ISO 8601 datetime string.") + + rules = EVENT_PARAMETER_RULES.get(etype) if isinstance(etype, str) else None + if rules is not None: + for param, code in rules.items(): + present = param in event + if code == "M" and not present: + errors.append(f"{label} of type '{etype}' is missing required field: {param}") + elif code == "X" and present: + errors.append(f"{label} of type '{etype}' must not have field: {param}") + elif code == "SN" and present: + warnings.append(f"{label} of type '{etype}' should not have field: {param}") + + # Type and range checks on the parameters that are present. + def check_index(param: str, count: Optional[int], noun: str) -> None: + if param not in event: + return + val = event[param] + if not _is_index(val): + errors.append(f"{label} field '{param}' must be a non-negative integer.") + elif count is not None and val >= count: + errors.append(f"{label} references invalid {noun} index: {val}") + + for param, count, noun in ( + ("party", party_count, "party"), + ("transferee", party_count, "party"), + ("transfer_target", party_count, "party"), + ("consultation", session_count, "session"), + ("target_session", session_count, "session"), + ): + check_index(param, count, noun) + + if "dialog" in event: + val = event["dialog"] + if _is_index(val): + idxs = [val] + elif isinstance(val, list) and etype not in CORE_EVENT_TYPES and all(_is_index(v) for v in val): + idxs = val # extension event types may use an array (4.3.5) + else: + idxs = [] + errors.append(f"{label} field 'dialog' must be a non-negative integer.") + for v in idxs: + if dialog_count is not None and v >= dialog_count: + errors.append(f"{label} references invalid dialog index: {v}") + + if "channel" in event and not _is_index(event["channel"]): + errors.append(f"{label} field 'channel' must be a non-negative integer.") + + if "sessions" in event: + val = event["sessions"] + if not _is_index_or_list(val): + errors.append(f"{label} field 'sessions' must be an index or a list of indices.") + else: + idxs = val if isinstance(val, list) else [val] + if etype in TRANSFER_EVENT_TYPES and isinstance(val, list): + errors.append( + f"{label} of type '{etype}' must reference a single session index in 'sessions'." + ) + for v in idxs: + if session_count is not None and v >= session_count: + errors.append(f"{label} references invalid session index: {v}") + + if "contributors" in event: + val = event["contributors"] + if val is not None and not _is_index_or_list(val): + errors.append(f"{label} field 'contributors' must be an index, a list of indices or null.") + else: + for v in ([] if val is None else (val if isinstance(val, list) else [val])): + if party_count is not None and v >= party_count: + errors.append(f"{label} references invalid party index: {v}") + + if "button" in event and not isinstance(event["button"], str): + errors.append(f"{label} field 'button' must be a string.") + + return errors, warnings + + +class Event: + """An Event Object (core-05 section 4.3). + + Args: + type: Event type token, for example ``"join"`` or ``"blind-transfer"``. + time: When the event occurred (``datetime`` or ISO 8601 string). + sessions: Session index or list of indices (not for channel-contributors). + party: Party index (not for channel-contributors). + dialog: Dialog index (channel-contributors; SHOULD NOT be used otherwise). + channel: Channel index (channel-contributors only). + contributors: Party index, list of indices, or ``None`` (channel-contributors only). + button: DTMF digit or key label (keydown and keyup only). + transferee, transfer_target: Party indices (transfer types). + consultation, target_session: Session indices (transfer types). + validate: Apply the parameter applicability table and raise + ``ValueError`` on an ``M``/``X`` violation (default True). + **extra: Parameters defined by a vCon extension. + """ + + def __init__( + self, + type: str, + time: Union[datetime, str], + sessions: Optional[Union[int, List[int]]] = None, + party: Optional[int] = None, + dialog: Optional[Union[int, List[int]]] = None, + channel: Optional[int] = None, + contributors: Optional[Union[int, List[int]]] = None, + button: Optional[str] = None, + transferee: Optional[int] = None, + transfer_target: Optional[int] = None, + consultation: Optional[int] = None, + target_session: Optional[int] = None, + validate: bool = True, + **extra: Any, + ) -> None: + if isinstance(time, datetime): + time = time.isoformat() + self.type = type + self.time = time + self.sessions = sessions + self.party = party + self.dialog = dialog + self.channel = channel + self.contributors = contributors + self.button = button + self.transferee = transferee + self.transfer_target = transfer_target + self.consultation = consultation + self.target_session = target_session + self.extra = {k: v for k, v in extra.items() if v is not None} + if validate: + errors, warnings = validate_event(self.to_dict()) + for w in warnings: + logger.warning(w) + if errors: + raise ValueError("; ".join(errors)) + + def to_dict(self) -> Dict[str, Any]: + """Serialize, omitting parameters that are ``None``.""" + out: Dict[str, Any] = {} + for name in EVENT_PARAMETERS: + value = getattr(self, name) + if value is not None: + out[name] = value + out.update(self.extra) + return out + + @classmethod + def from_dict(cls, data: Dict[str, Any], validate: bool = False) -> "Event": + known = {k: data[k] for k in EVENT_PARAMETERS if k in data} + extra = {k: v for k, v in data.items() if k not in EVENT_PARAMETERS} + return cls(validate=validate, **known, **extra) diff --git a/src/vcon/migration.py b/src/vcon/migration.py new file mode 100644 index 0000000..55cb9cb --- /dev/null +++ b/src/vcon/migration.py @@ -0,0 +1,1094 @@ +"""Migrate a vCon from syntax 0.4.0 to 0.5.0 (draft-ietf-vcon-vcon-core-05, Appendix A.1). + +The migration is table driven. ``MIGRATION_STEPS`` holds one ``MigrationStep`` +per step T1..T15 of the ordered transform table; each step is one function that +mutates a shared ``_Context``. If a later edit of Appendix A.1 changes one step, +only that function (or its table entry) needs to change. + +Execution order (the draft gives none; this order is inferred so that every +``dialog`` index stays valid): the steps that read the 0.4.0 ``dialog`` array +run before any array is rewritten, and ``T10`` blanks the removed Dialogs in +place at the end, so the array length and every other index are unchanged. + + T13 T15 T1 -> T8 T9 T9b T6 -> T2 T7 T3 T4(+T5) -> T10 T10b -> T11 T12 T14 + +Nothing is invented silently. Every value the draft does not dictate is listed +in the :class:`MigrationReport` (kind ``inferred``), every field that had to be +filled by a fallback is listed (kind ``fallback``), and every problem the +migration could not resolve is listed (kind ``unresolved``). In strict mode a +fallback raises :class:`MigrationError` instead. + +A signed 0.4.0 vCon is migrated as the unsigned payload. The migration never +signs; the report sets ``resign_required``. +""" + +from __future__ import annotations + +import base64 +import copy +import json +import logging +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple + +from dateutil import parser + +from .validation import extensions_in_use, validate_vcon_dict + +logger = logging.getLogger(__name__) + +SOURCE_VERSION = "0.4.0" +TARGET_VERSION = "0.5.0" + + +class MigrationError(ValueError): + """The vCon cannot be migrated (or, in strict mode, a MUST field has no source).""" + + +# --------------------------------------------------------------------------- +# Report +# --------------------------------------------------------------------------- + +#: A value the draft does not dictate; a documented default was applied. +INFERRED = "inferred" +#: A MUST field with no source was filled with the documented fallback. +FALLBACK = "fallback" +#: A problem left for a person to resolve. +UNRESOLVED = "unresolved" +#: Informational. +INFO = "info" + + +@dataclass +class ReportEntry: + step: str + kind: str + message: str + code: Optional[str] = None # AMB-n identifier from the implementation spec + details: Dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"step": self.step, "kind": self.kind, "message": self.message} + if self.code: + out["code"] = self.code + if self.details: + out["details"] = self.details + return out + + +@dataclass +class MigrationReport: + """What a migration did that the draft did not dictate.""" + + source_version: Optional[str] = None + target_version: str = TARGET_VERSION + strict: bool = False + #: True when the input was signed: the signature is dropped and the result is unsigned. + resign_required: bool = False + entries: List[ReportEntry] = field(default_factory=list) + #: Original content of every Dialog replaced by ``{}``, keyed by its (unchanged) index. + removed_dialogs: Dict[int, Dict[str, Any]] = field(default_factory=dict) + #: Steps that ran, in order. + steps_run: List[str] = field(default_factory=list) + + def add( + self, + step: str, + kind: str, + message: str, + code: Optional[str] = None, + **details: Any, + ) -> None: + self.entries.append(ReportEntry(step, kind, message, code, details)) + + def _of(self, kind: str) -> List[ReportEntry]: + return [e for e in self.entries if e.kind == kind] + + @property + def inferred(self) -> List[ReportEntry]: + return self._of(INFERRED) + + @property + def fallbacks(self) -> List[ReportEntry]: + return self._of(FALLBACK) + + @property + def unresolved(self) -> List[ReportEntry]: + return self._of(UNRESOLVED) + + @property + def notes(self) -> List[ReportEntry]: + return self._of(INFO) + + def to_dict(self) -> Dict[str, Any]: + return { + "source_version": self.source_version, + "target_version": self.target_version, + "strict": self.strict, + "resign_required": self.resign_required, + "steps_run": list(self.steps_run), + "entries": [e.to_dict() for e in self.entries], + "removed_dialogs": {str(k): v for k, v in self.removed_dialogs.items()}, + } + + def summary(self) -> str: + return ( + f"{len(self.inferred)} inferred, {len(self.fallbacks)} fallback, " + f"{len(self.unresolved)} unresolved" + + ("; re-signing required" if self.resign_required else "") + ) + + +class MigrationResult(NamedTuple): + """Result of a migration. Unpacks as ``(vcon, report)``.""" + + vcon: Dict[str, Any] + report: MigrationReport + + +# --------------------------------------------------------------------------- +# Context and helpers +# --------------------------------------------------------------------------- + + +def _is_int(v: Any) -> bool: + return isinstance(v, int) and not isinstance(v, bool) + + +def _parse_dt(value: Any) -> Optional[datetime]: + if not isinstance(value, str): + return None + try: + dt = parser.parse(value) + except Exception: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt + + +def _num(seconds: float) -> Any: + seconds = round(seconds, 6) + return int(seconds) if float(seconds).is_integer() else seconds + + +def _plain_parties(value: Any) -> List[int]: + """Flat list of int party indices of a 0.4.0 Dialog ``parties`` value.""" + out: List[int] = [] + items = value if isinstance(value, list) else ([] if value is None else [value]) + for v in items: + if isinstance(v, list): + out.extend(x for x in v if _is_int(x)) + elif _is_int(v): + out.append(v) + return out + + +def _union(lists: List[List[int]]) -> List[int]: + seen: List[int] = [] + for lst in lists: + for v in lst: + if v not in seen: + seen.append(v) + return seen + + +def _rename_key(d: Dict[str, Any], old: str, new: str) -> Dict[str, Any]: + return {(new if k == old else k): v for k, v in d.items()} + + +class _Context: + def __init__(self, data: Dict[str, Any], strict: bool, report: MigrationReport) -> None: + self.out: Dict[str, Any] = data + self.src: Dict[str, Any] = copy.deepcopy(data) # refreshed by T13 after unwrapping + self.strict = strict + self.report = report + self.sessions: List[Dict[str, Any]] = [] + self.events: List[Dict[str, Any]] = [] + #: receivers contributed to the Session by each (kept) Dialog index + self.receivers: Dict[int, List[int]] = {} + #: originator value taken from each (kept) Dialog index + self.originators: Dict[int, int] = {} + #: Session indices each Dialog index belongs to + self.dialog_sessions: Dict[int, List[int]] = {} + #: recording-set Dialog index -> Session index (T7) + self.rs_session: Dict[int, int] = {} + #: transfer Dialog index -> Session index of its original call (T4) + self.transfer_session: Dict[int, int] = {} + self._role_sessions: Dict[int, int] = {} + self._empty_party: Optional[int] = None + self.catch_all: Optional[int] = None + + # -- source views --------------------------------------------------- + @property + def dialogs(self) -> List[Any]: + d = self.src.get("dialog") + return d if isinstance(d, list) else [] + + @property + def removed(self) -> Dict[int, str]: + """Dialog index -> removed type, for transfer and recording-set Dialogs.""" + return { + i: d["type"] + for i, d in enumerate(self.dialogs) + if isinstance(d, dict) and d.get("type") in ("transfer", "recording-set") + } + + def kept(self) -> List[int]: + rem = self.removed + return [i for i, d in enumerate(self.dialogs) if i not in rem and isinstance(d, dict) and d] + + # -- helpers -------------------------------------------------------- + def need_fallback(self, step: str, message: str, code: Optional[str] = None, **details: Any) -> None: + """Record a fallback for a MUST field, or raise in strict mode.""" + if self.strict: + raise MigrationError(f"{step}: {message} (strict mode: no source for a required field)") + self.report.add(step, FALLBACK, message, code, **details) + + def new_session(self, session: Dict[str, Any]) -> int: + self.sessions.append(session) + return len(self.sessions) - 1 + + def empty_party(self, step: str, role: str) -> int: + """Index of an empty Party Object, appended once (4.3.9: unknown party).""" + if self._empty_party is None: + parties = self.out.setdefault("parties", []) + parties.append({}) + self._empty_party = len(parties) - 1 + self.report.add( + step, INFERRED, + f"Appended an empty Party Object at parties[{self._empty_party}] to stand for unknown parties.", + None, party=self._empty_party, + ) + return self._empty_party + + def dialog_start(self, idx: Any) -> Optional[str]: + """Start of a Dialog, or of a recording-set's earliest recording.""" + if not _is_int(idx) or not 0 <= idx < len(self.dialogs): + return None + d = self.dialogs[idx] + if not isinstance(d, dict): + return None + if _parse_dt(d.get("start")): + return d["start"] + if d.get("type") == "recording-set": + starts = [ + (self.dialogs[r].get("start")) + for r in (d.get("recordings") or []) + if _is_int(r) and 0 <= r < len(self.dialogs) and isinstance(self.dialogs[r], dict) + ] + starts = [s for s in starts if _parse_dt(s)] + if starts: + return min(starts, key=_parse_dt) + return None + + def span(self, idxs: List[int]) -> Tuple[Optional[str], Optional[Any]]: + """Derived (start, duration) of a group of Dialogs. + + start is the earliest Dialog start. duration runs from that start to the + latest Dialog end (start plus duration, or start when no duration is + known), and is only derived when at least one Dialog has a duration. + """ + items = [ + (i, _parse_dt(self.dialogs[i].get("start"))) + for i in idxs + if isinstance(self.dialogs[i], dict) + ] + items = [(i, s) for i, s in items if s is not None] + if not items: + return None, None + first_i, first = min(items, key=lambda t: t[1]) + start_str = self.dialogs[first_i]["start"] + ends = [] + any_duration = False + for i, s in items: + dur = self.dialogs[i].get("duration") + if isinstance(dur, (int, float)) and not isinstance(dur, bool): + any_duration = True + ends.append(s.timestamp() + dur) + else: + ends.append(s.timestamp()) + if not any_duration: + return start_str, None + return start_str, _num(max(ends) - first.timestamp()) + + def make_session(self, step: str, idxs: List[int], label: str) -> Dict[str, Any]: + """Build a Session for a group of kept Dialogs from derived values.""" + session: Dict[str, Any] = {} + start, duration = self.span(idxs) + if start is not None: + session["start"] = start + if duration is not None: + session["duration"] = duration + parties = _union([self.receivers.get(i, []) for i in idxs]) + if parties: + session["parties"] = parties + orig = [self.originators[i] for i in idxs if i in self.originators] + if orig: + chosen = orig[0] + others = sorted({o for o in orig[1:] if o != chosen}) + if others: + self.report.add( + step, UNRESOLVED, + f"{label}: Dialogs name different originators; kept {chosen}, " + f"did not record {others}.", None, kept=chosen, dropped=others, + ) + if not parties or chosen != parties[0]: + session["originator"] = chosen + session["dialog"] = list(idxs) + # key order: start, duration, parties, originator, dialog + order = ("start", "duration", "parties", "originator", "session_id", "sessions", "dialog") + session = {k: session[k] for k in order if k in session} + if start is not None or duration is not None: + self.report.add( + step, INFERRED, + f"{label}: start/duration derived from its Dialogs (earliest start; " + "duration to the latest end when any Dialog has a duration).", + None, start=start, duration=duration, + ) + return session + + +# --------------------------------------------------------------------------- +# Steps +# --------------------------------------------------------------------------- + + +def _step_t1_version(ctx: _Context) -> None: + """T1: ``vcon`` "0.4.0" -> "0.5.0".""" + if "vcon" not in ctx.out: + ctx.report.add("T1", INFERRED, "Input had no 'vcon' parameter; set to '0.5.0' (AMB-12: writers emit it).", "AMB-12") + ctx.out["vcon"] = TARGET_VERSION + + +def _step_t2_sessions(ctx: _Context) -> None: + """T2: add one Session which references all (kept) Dialog Objects. + + The removed transfer and recording-set positions are skipped (they become + ``{}``; T10). Receivers (T8, T9, T9b) and the originator (T6) have already + been collected, so the Session is built in one go. + """ + kept = ctx.kept() + if not kept: + return + ctx.catch_all = ctx.new_session(ctx.make_session("T2", kept, "Session 0 (all Dialogs)")) + for i in kept: + ctx.dialog_sessions.setdefault(i, []).append(ctx.catch_all) + ctx.report.add( + "T2", INFO, + f"Added Session {ctx.catch_all} referencing {len(kept)} Dialog Object(s).", + ) + + +def _step_t3_party_history(ctx: _Context) -> None: + """T3: each Dialog ``party_history`` entry becomes an Event; ``event`` is renamed ``type``. + + The Event's ``sessions`` references the Session(s) for the Dialog it came + from and the Event does not reference the Dialog (SHOULD NOT, 4.3.5). + """ + dialogs = ctx.out.get("dialog") + if not isinstance(dialogs, list): + return + for i, src_d in enumerate(ctx.dialogs): + if not isinstance(src_d, dict) or "party_history" not in src_d: + continue + if src_d.get("type") == "transfer": + ctx.report.add( + "T3", UNRESOLVED, + f"dialog[{i}] is a transfer Dialog with party_history; the entries are not migrated " + "(A.1 covers party_history on non-transfer Dialogs). Original kept in removed_dialogs.", + None, dialog=i, + ) + continue + if src_d.get("type") == "recording-set": + sess = [ctx.rs_session[i]] if i in ctx.rs_session else [] + else: + sess = sorted(ctx.dialog_sessions.get(i, [])) + if len(sess) > 1: + ctx.report.add( + "T3", INFERRED, + f"dialog[{i}] belongs to Sessions {sess}; its party_history Events list all of them " + "in 'sessions' (4.3.3: an Event applies only to the Sessions listed).", + "AMB-3", dialog=i, sessions=sess, + ) + history = src_d["party_history"] + if not isinstance(history, list): + ctx.report.add("T3", UNRESOLVED, f"dialog[{i}] party_history is not a list; dropped.", None, dialog=i) + else: + for n, entry in enumerate(history): + if not isinstance(entry, dict) or "event" not in entry: + ctx.report.add( + "T3", UNRESOLVED, + f"dialog[{i}].party_history[{n}] has no 'event'; entry not migrated.", + None, dialog=i, entry=entry, + ) + continue + ev: Dict[str, Any] = {"type": entry["event"]} + if _parse_dt(entry.get("time")): + ev["time"] = entry["time"] + else: + fb = src_d.get("start") + ctx.need_fallback( + "T3", + f"dialog[{i}].party_history[{n}] has no usable time; used the Dialog start " + f"({fb!r}) as the Event time.", None, dialog=i, + ) + if fb is None: + raise MigrationError( + f"T3: dialog[{i}].party_history[{n}] has no time and the Dialog has no start" + ) + ev["time"] = fb + if sess: + ev["sessions"] = sess[0] if len(sess) == 1 else sess + if _is_int(entry.get("party")): + ev["party"] = entry["party"] + else: + ctx.need_fallback( + "T3", + f"dialog[{i}].party_history[{n}] has no party; referenced an empty Party Object.", + None, dialog=i, + ) + ev["party"] = ctx.empty_party("T3", "party") + if entry["event"] in ("keydown", "keyup") and "button" in entry: + ev["button"] = entry["button"] + elif "button" in entry: + ctx.report.add( + "T3", UNRESOLVED, + f"dialog[{i}].party_history[{n}] has 'button' on a '{entry['event']}' event " + "(only keydown and keyup carry it); button not migrated.", None, dialog=i, + ) + ctx.events.append(ev) + if src_d.get("type") != "recording-set" and isinstance(dialogs[i], dict): + dialogs[i].pop("party_history", None) + + +def _step_t4_transfers(ctx: _Context) -> None: + """T4 (with T5): each ``transfer`` Dialog becomes one or two transfer Events. + + ``transferor`` becomes ``party``. ``original``, ``consultation`` and + ``target_dialog`` become Session indices (T5): the recording-set's Session, + otherwise a Session that lists that Dialog. + """ + for k, kind in ctx.removed.items(): + if kind != "transfer": + continue + tr = ctx.dialogs[k] + step = "T4" + + def session_for(ref: Any, role: str, required: bool) -> Optional[int]: + """T5: Session index for a Dialog reference held by a transfer Dialog.""" + if ref is None: + return None + if not _is_int(ref) or not 0 <= ref < len(ctx.dialogs): + ctx.report.add(step, UNRESOLVED, f"transfer dialog[{k}] {role}={ref!r} is not a Dialog index.", None, dialog=k) + return None + if ref in ctx.rs_session: + ctx.report.add( + "T5", INFO, + f"transfer dialog[{k}] {role} -> dialog[{ref}] is a recording-set; using its Session {ctx.rs_session[ref]}.", + ) + return ctx.rs_session[ref] + if ref in ctx.removed: + idx = ctx.new_session({}) + ctx.report.add( + "T5", UNRESOLVED, + f"transfer dialog[{k}] {role} -> dialog[{ref}] is itself a removed {ctx.removed[ref]} Dialog; " + f"created placeholder Session {idx} with no parameters.", None, dialog=k, + ) + return idx + if ref in ctx._role_sessions: + return ctx._role_sessions[ref] + sess = ctx.make_session("T5", [ref], f"Session for transfer {role} (dialog[{ref}])") + idx = ctx.new_session(sess) + ctx._role_sessions[ref] = idx + ctx.dialog_sessions.setdefault(ref, []).append(idx) + ctx.report.add( + "T5", INFERRED, + f"transfer dialog[{k}] {role} -> created Session {idx} listing dialog[{ref}] " + "(A.1: referenced through a Session Object).", None, dialog=k, session=idx, + ) + return idx + + def placeholder(role: str, why: str, required_fallback: bool) -> int: + idx = ctx.new_session({}) + msg = f"transfer dialog[{k}] has no {role} ({why}); created placeholder Session {idx} with no parameters (4.3.1.3)." + if required_fallback: + ctx.need_fallback(step, msg, None, dialog=k, session=idx) + else: + ctx.report.add(step, INFERRED, msg, "AMB-7", dialog=k, session=idx) + return idx + + # Session of the original call (sessions: M, single index). + orig_ref = tr.get("original") + sidx = session_for(orig_ref, "original", True) + if sidx is None: + sidx = placeholder("original", "'sessions' is required on every transfer Event", True) + ctx.transfer_session[k] = sidx + + def party_ref(key: str, role: str, required: bool) -> Optional[int]: + val = tr.get(key) + if _is_int(val): + return val + if not required: + return None + ctx.need_fallback( + step, + f"transfer dialog[{k}] has no {key} ({role}); referenced an empty Party Object (4.3.9).", + None, dialog=k, + ) + return ctx.empty_party(step, role) + + transferor = party_ref("transferor", "Transferor, becomes 'party'", True) + transferee = party_ref("transferee", "Transferee", True) + + cons_ref = tr.get("consultation") + target_ref = tr.get("target_dialog") + cons_sess = session_for(cons_ref, "consultation", False) if cons_ref is not None else None + if cons_ref is not None and cons_sess is None: + cons_sess = placeholder("usable consultation", "consultation Dialog index could not be resolved", False) + target_sess = session_for(target_ref, "target_dialog", False) if target_ref is not None else None + has_target_party = _is_int(tr.get("transfer_target")) + + # Event types (AMB-7). + types: List[str] = [] + if cons_ref is not None: + types.append("consultation-start") + if target_ref is not None or has_target_party: + types.append("consultative-transfer" if cons_ref is not None else "blind-transfer") + else: + types.append("transfer-abandoned") + ctx.report.add( + step, INFERRED, + f"transfer dialog[{k}] mapped to Event type(s) {types} " + "(consultation present -> consultation-start + consultative-transfer; otherwise blind-transfer; " + "no target_dialog and no transfer_target -> transfer-abandoned).", + "AMB-7", dialog=k, types=types, + ) + if "blind-transfer" in types or "consultative-transfer" in types: + if target_sess is None: + target_sess = placeholder( + "target_dialog", + "the target call was not captured; 4.3.1.3 uses a placeholder Session in that case", False, + ) + + def event_time(which: str) -> str: + own = tr.get("start") + if _parse_dt(own): + return own + cands: List[Tuple[Optional[str], str]] = [] + if which == "consult": + cands.append((ctx.dialog_start(cons_ref), f"start of consultation dialog[{cons_ref}]")) + else: + cands.append((ctx.dialog_start(target_ref), f"start of target dialog[{target_ref}]")) + if cons_ref is not None: + cd = ctx.dialogs[cons_ref] if _is_int(cons_ref) and 0 <= cons_ref < len(ctx.dialogs) else None + cs, dur = _parse_dt(ctx.dialog_start(cons_ref)), (cd or {}).get("duration") if isinstance(cd, dict) else None + if cs is not None and isinstance(dur, (int, float)) and not isinstance(dur, bool): + end = datetime.fromtimestamp(cs.timestamp() + dur, tz=timezone.utc).isoformat() + cands.append((end, f"end of consultation dialog[{cons_ref}] (start + duration)")) + cands.append((ctx.dialog_start(cons_ref), f"start of consultation dialog[{cons_ref}]")) + for value, src in cands: + if value and _parse_dt(value): + ctx.report.add( + step, INFERRED, + f"transfer dialog[{k}] has no start; Event time taken from the {src}, " + "not from the transfer Dialog's own start.", "AMB-7", dialog=k, source=src, time=value, + ) + return value + created = ctx.out.get("created_at") + if _parse_dt(created): + ctx.need_fallback( + step, + f"transfer dialog[{k}] has no start and no other time source; used the vCon created_at " + f"({created!r}) as the Event time.", "AMB-7", dialog=k, + ) + return created + raise MigrationError( + f"{step}: transfer dialog[{k}] has no start and the vCon has no created_at; no time can be sourced" + ) + + base: Dict[str, Any] = {} + for t in types: + ev: Dict[str, Any] = {"type": t} + ev["time"] = event_time("consult" if t == "consultation-start" else "transfer") + ev["sessions"] = sidx + ev["party"] = transferor + ev["transferee"] = transferee + need_target = t != "transfer-abandoned" + tt = party_ref("transfer_target", "Transfer Target", need_target) + if tt is not None: + ev["transfer_target"] = tt + if t in ("consultation-start", "consultative-transfer"): + ev["consultation"] = cons_sess + elif t == "transfer-abandoned" and cons_sess is not None: + ev["consultation"] = cons_sess + if t in ("blind-transfer", "consultative-transfer"): + ev["target_session"] = target_sess + ctx.events.append(ev) + extra = sorted( + set(tr) + - {"type", "start", "transferee", "transferor", "transfer_target", "original", "consultation", "target_dialog", "parties", "originator", "party_history"} + ) + if extra or tr.get("parties"): + ctx.report.add( + step, UNRESOLVED, + f"transfer dialog[{k}] had parameters with no Event equivalent " + f"({extra + (['parties'] if tr.get('parties') else [])}); not migrated. " + "Original kept in report.removed_dialogs.", None, dialog=k, + ) + + +def _step_t6_originator(ctx: _Context) -> None: + """T6: ``originator`` moves from the Dialog to the Session (only when not the first party).""" + dialogs = ctx.out.get("dialog") + if not isinstance(dialogs, list): + return + for i in ctx.kept(): + d = dialogs[i] + if "originator" in d: + val = d.pop("originator") + if _is_int(val): + ctx.originators[i] = val + else: + ctx.report.add("T6", UNRESOLVED, f"dialog[{i}] originator {val!r} is not a party index; dropped.", None, dialog=i) + + +def _step_t7_recording_sets(ctx: _Context) -> None: + """T7: each ``recording-set`` Dialog becomes a Session listing its recordings. + + The recording-set's own start, duration, parties, session_id and originator + move to the Session (A.1 is silent: AMB-4). ``recording_set`` is removed from + each recording. + """ + dialogs = ctx.out.get("dialog") + for k, kind in ctx.removed.items(): + if kind != "recording-set": + continue + rs = ctx.dialogs[k] + recs_raw = rs.get("recordings") + recs: List[int] = [] + if isinstance(recs_raw, list): + for r in recs_raw: + if _is_int(r) and 0 <= r < len(ctx.dialogs) and r not in ctx.removed and isinstance(ctx.dialogs[r], dict): + if r not in recs: + recs.append(r) + else: + ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] lists recordings entry {r!r}, which is not a kept Dialog; left out of the Session.", None, dialog=k) + else: + ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] has no recordings list; Session has no dialog.", None, dialog=k) + sess: Dict[str, Any] = {} + d_start, d_dur = ctx.span(recs) if recs else (None, None) + if _parse_dt(rs.get("start")): + sess["start"] = rs["start"] + elif d_start is not None: + sess["start"] = d_start + if isinstance(rs.get("duration"), (int, float)) and not isinstance(rs.get("duration"), bool): + sess["duration"] = rs["duration"] + elif d_dur is not None: + sess["duration"] = d_dur + rs_parties = _plain_parties(rs.get("parties")) + parties = rs_parties or _union([ctx.receivers.get(r, []) for r in recs]) + if parties: + sess["parties"] = parties + orig = rs.get("originator") + if _is_int(orig) and (not parties or orig != parties[0]): + sess["originator"] = orig + sid = rs.get("session_id") + if isinstance(sid, dict): + sess["session_id"] = sid + elif isinstance(sid, list) and len(sid) == 1 and isinstance(sid[0], dict): + sess["session_id"] = sid[0] + elif sid is not None: + ctx.report.add( + "T7", UNRESOLVED, + f"recording-set dialog[{k}] session_id is not a single SessionId Object; Session.session_id not set.", + "AMB-4", dialog=k, session_id=sid, + ) + if recs: + sess["dialog"] = recs + order = ("start", "duration", "parties", "originator", "session_id", "sessions", "dialog") + sess = {key: sess[key] for key in order if key in sess} + sidx = ctx.new_session(sess) + ctx.rs_session[k] = sidx + for r in recs: + ctx.dialog_sessions.setdefault(r, []).append(sidx) + fields_moved = [f for f in ("start", "duration", "parties", "session_id", "originator") if f in rs] + ctx.report.add( + "T7", INFERRED, + f"recording-set dialog[{k}] -> Session {sidx}; its {fields_moved} moved to the Session " + "(A.1 silent about them); Session start/duration/parties fall back to values derived from the recordings when absent.", + "AMB-4", dialog=k, session=sidx, + ) + if ctx.catch_all is not None: + ctx.report.add( + "T7", UNRESOLVED, + f"Session {sidx} (recording-set dialog[{k}]) overlaps Session {ctx.catch_all}, which also lists its " + "recordings; A.1 does not say whether to relate them, so no Session_Reference was added.", + "AMB-1", session=sidx, catch_all=ctx.catch_all, + ) + for r in recs: + if isinstance(dialogs, list) and isinstance(dialogs[r], dict): + dialogs[r].pop("recording_set", None) + # Remove any stray recording_set / recordings on kept dialogs. + if isinstance(dialogs, list): + for i in ctx.kept(): + dialogs[i].pop("recording_set", None) + dialogs[i].pop("recordings", None) + + +def _step_t8_text_parties(ctx: _Context) -> None: + """T8: a ``text`` Dialog's ``parties`` reduce to the sender; all parties go to the Session.""" + dialogs = ctx.out.get("dialog") + if not isinstance(dialogs, list): + return + for i in ctx.kept(): + if ctx.dialogs[i].get("type") != "text": + continue + p = _plain_parties(ctx.dialogs[i].get("parties")) + if not p: + ctx.report.add("T8", UNRESOLVED, f"text dialog[{i}] has no parties; sender and receivers unknown.", None, dialog=i) + continue + orig = ctx.dialogs[i].get("originator") + sender = orig if _is_int(orig) else p[0] + dialogs[i]["parties"] = [sender] + ctx.receivers[i] = p if sender in p else [sender] + p + + +def _step_t9_incomplete_parties(ctx: _Context) -> None: + """T9: an ``incomplete`` Dialog's ``parties`` reduce to the originator (or first party).""" + dialogs = ctx.out.get("dialog") + if not isinstance(dialogs, list): + return + for i in ctx.kept(): + if ctx.dialogs[i].get("type") != "incomplete": + continue + p = _plain_parties(ctx.dialogs[i].get("parties")) + if not p: + continue + orig = ctx.dialogs[i].get("originator") + who = orig if _is_int(orig) else p[0] + dialogs[i]["parties"] = [who] + ctx.receivers[i] = p if who in p else [who] + p + + +def _step_t9b_recording_parties(ctx: _Context) -> None: + """T9b: other Dialogs keep ``parties`` (contributors); the Session gets the union (AMB-6).""" + idxs = [] + for i in ctx.kept(): + if ctx.dialogs[i].get("type") in ("text", "incomplete"): + continue + p = _plain_parties(ctx.dialogs[i].get("parties")) + if p: + ctx.receivers[i] = p + idxs.append(i) + if idxs: + ctx.report.add( + "T9b", INFERRED, + f"Dialog(s) {idxs} (recording or other type): parties left as the contributors; " + "the Session parties are the union of the contributors across its Dialogs (A.1 gives no rule).", + "AMB-6", dialogs=idxs, + ) + texts = [i for i in ctx.kept() if ctx.dialogs[i].get("type") == "text"] + if texts: + sets = {tuple(sorted(ctx.receivers.get(i, []))) for i in texts} + if len(sets) > 1: + ctx.report.add( + "T8", UNRESOLVED, + f"text Dialogs {texts} have different receiver sets; they were put in one Session whose parties " + "are the union. 4.5.4 prescribes a parent Session with a child Session per receiver set; that " + "split was not made.", "AMB-5", dialogs=texts, + ) + if any(len(s) > 2 for s in sets): + ctx.report.add( + "T8", UNRESOLVED, + "0.4.0 parties do not distinguish To, Cc and Bcc, so Bcc recipients cannot be identified or " + "excluded.", "AMB-5", dialogs=texts, + ) + + +def _step_t10_blank_removed(ctx: _Context) -> None: + """T10: each removed Dialog is replaced in place by ``{}`` so no index moves.""" + dialogs = ctx.out.get("dialog") + if not isinstance(dialogs, list): + return + for k, kind in ctx.removed.items(): + ctx.report.removed_dialogs[k] = copy.deepcopy(ctx.dialogs[k]) + dialogs[k] = {} + ctx.report.add("T10", INFO, f"dialog[{k}] ({kind}) replaced by an empty Dialog Object; index {k} unchanged.", None, dialog=k) + if len(dialogs) != len(ctx.dialogs): # pragma: no cover - internal guard + raise MigrationError("T10: dialog array length changed; indices would break") + + +def _merge_index(existing: Any, new: List[int]) -> Any: + cur = [] if existing is None else (existing if isinstance(existing, list) else [existing]) + merged = list(cur) + for n in new: + if n not in merged: + merged.append(n) + return merged[0] if len(merged) == 1 else merged + + +def _step_t10b_retarget(ctx: _Context) -> None: + """AMB-2: re-point analysis and attachment references to removed Dialogs. + + Recording-set: Analysis.dialog is expanded to the recordings and ``sessions`` + gets the recording-set's Session; an Attachment (single ``dialog`` index) + gets ``session`` instead. Transfer: the reference moves to the Session of the + transfer's original call. Nothing is left pointing at a ``{}`` Dialog. + """ + removed = ctx.removed + if not removed: + return + + def targets(e: int) -> Tuple[List[int], Optional[int]]: + """(replacement dialog indices, session index) for a removed Dialog.""" + if removed[e] == "recording-set": + sidx = ctx.rs_session.get(e) + recs = ctx.sessions[sidx].get("dialog", []) if sidx is not None else [] + return list(recs), sidx + return [], ctx.transfer_session.get(e) + + for n, an in enumerate(ctx.out.get("analysis") or []): + if not isinstance(an, dict) or "dialog" not in an: + continue + old = an["dialog"] + items = old if isinstance(old, list) else [old] + if not any(_is_int(x) and x in removed for x in items): + continue + new_dialogs: List[int] = [] + sess_add: List[int] = [] + for x in items: + if _is_int(x) and x in removed: + reps, sidx = targets(x) + new_dialogs.extend(r for r in reps if r not in new_dialogs) + if sidx is not None: + sess_add.append(sidx) + elif x not in new_dialogs: + new_dialogs.append(x) + if new_dialogs: + an["dialog"] = new_dialogs[0] if (len(new_dialogs) == 1 and not isinstance(old, list)) else new_dialogs + else: + del an["dialog"] + if sess_add: + an["sessions"] = _merge_index(an.get("sessions"), sess_add) + ctx.report.add( + "T10b", INFERRED, + f"analysis[{n}].dialog {old!r} pointed at a removed Dialog; now dialog={an.get('dialog')!r}, " + f"sessions={an.get('sessions')!r}.", "AMB-2", analysis=n, + ) + for n, att in enumerate(ctx.out.get("attachments") or []): + if not isinstance(att, dict) or not (_is_int(att.get("dialog")) and att["dialog"] in removed): + continue + e = att["dialog"] + _, sidx = targets(e) + del att["dialog"] + if sidx is not None: + att["session"] = _merge_index(att.get("session"), [sidx]) + ctx.report.add( + "T10b", INFERRED, + f"attachments[{n}].dialog={e} pointed at a removed Dialog; replaced by session={att['session']!r}.", + "AMB-2", attachment=n, + ) + else: + ctx.report.add( + "T10b", UNRESOLVED, + f"attachments[{n}].dialog={e} pointed at a removed Dialog with no Session to re-point to; " + "the attachment now has neither dialog nor session.", "AMB-2", attachment=n, + ) + + +def _step_t13_unwrap_signed(ctx: _Context) -> None: + """T13: a signed vCon is migrated as its unsigned payload; it must be signed again. + + ``alg: "none"`` is no longer permitted, so such a vCon is flagged explicitly. + The migration never signs. + """ + out = ctx.out + if "ciphertext" in out and ("recipients" in out or "protected" in out): + raise MigrationError("T13: the input is an encrypted (JWE) vCon; decrypt it before migrating") + if "payload" in out and "signatures" in out: + try: + raw = out["payload"] + payload = json.loads(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))) + except Exception as e: + raise MigrationError(f"T13: could not decode the signed vCon payload: {e}") from e + if not isinstance(payload, dict): + raise MigrationError("T13: the signed vCon payload is not a JSON object") + algs = [] + for sig in out.get("signatures") or []: + try: + hdr = sig.get("protected") + if hdr: + algs.append(json.loads(base64.urlsafe_b64decode(hdr + "=" * (-len(hdr) % 4))).get("alg")) + if isinstance(sig.get("header"), dict) and "alg" in sig["header"]: + algs.append(sig["header"]["alg"]) + except Exception: + continue + ctx.out = payload + ctx.report.resign_required = True + ctx.report.add( + "T13", UNRESOLVED, + "The input was signed. It was migrated as the unsigned payload; the signature was dropped. " + "Re-signing is required, and signing changes updated_at (4.1.6).", None, + ) + if any(isinstance(a, str) and a.lower() == "none" for a in algs): + ctx.report.add( + "T13", UNRESOLVED, + "A signature used alg 'none', which 0.5.0 forbids; sign again with a permitted algorithm.", None, + ) + ctx.src = copy.deepcopy(ctx.out) + ctx.report.source_version = ctx.out.get("vcon") + + +def _step_t14_extensions(ctx: _Context) -> None: + """T14: ``extensions`` must list every extension in use (MUST, was SHOULD).""" + names, unnamed = extensions_in_use(ctx.out) + listed = ctx.out.get("extensions") + listed = list(listed) if isinstance(listed, list) else [] + added = [] + for name in sorted(names): + if name not in listed: + listed.append(name) + added.append(name) + for name in ctx.out.get("critical") or []: + if isinstance(name, str) and name not in listed: + listed.append(name) + added.append(name) + if added: + ctx.out["extensions"] = listed + ctx.report.add("T14", INFERRED, f"Added extension name(s) {added} to extensions.", None, added=added) + if unnamed and not listed: + ctx.report.add( + "T14", UNRESOLVED, + "Values outside the core vocabulary are in use but their defining extension cannot be identified: " + + "; ".join(unnamed) + ". extensions was not changed.", None, uses=unnamed, + ) + + +def _step_t15_duplicate_headers(ctx: _Context) -> None: + """T15: duplicate header parameters in signed or encrypted forms are tolerated on read.""" + if ctx.report.resign_required: + ctx.report.add( + "T15", INFO, + "Header parameters repeated across JWS headers are not checked or rejected on read; " + "writers must not emit duplicates in 0.5.0.", + ) + + +# T11 and T12 are renames at the top level; implemented with an order-preserving helper. +def _rename_top(ctx: _Context, old: str, new: str, step: str) -> None: + if old in ctx.out: + ctx.out = _rename_key(ctx.out, old, new) + ctx.report.add(step, INFO, f"Renamed '{old}' to '{new}'.") + + +def _step_t11(ctx: _Context) -> None: + """T11: ``redacted`` -> ``redacted_from`` (same fields).""" + _rename_top(ctx, "redacted", "redacted_from", "T11") + + +def _step_t12(ctx: _Context) -> None: + """T12: ``amended`` -> ``amended_from`` (same fields).""" + _rename_top(ctx, "amended", "amended_from", "T12") + + +@dataclass(frozen=True) +class MigrationStep: + id: str + title: str + source: str # where the draft says it + func: Callable[[_Context], None] + + +#: One entry per step of the ordered transform table (Appendix A.1), in execution order. +MIGRATION_STEPS: List[MigrationStep] = [ + MigrationStep("T13", "Signed input: migrate the payload, require re-signing", "A.1 bullet 11; 6.2.2", _step_t13_unwrap_signed), + MigrationStep("T15", "Duplicate header parameters tolerated on read", "A.1 bullet 13", _step_t15_duplicate_headers), + MigrationStep("T1", "vcon 0.4.0 -> 0.5.0", "A.1 bullet 1", _step_t1_version), + MigrationStep("T8", "text Dialog parties -> sender; all parties to Session", "A.1 bullet 6", _step_t8_text_parties), + MigrationStep("T9", "incomplete Dialog parties -> originator/first", "A.1 bullet 6", _step_t9_incomplete_parties), + MigrationStep("T9b", "other Dialog parties kept; union to Session", "4.5.4 (A.1 silent)", _step_t9b_recording_parties), + MigrationStep("T6", "Dialog originator -> Session originator", "A.1 bullet 5", _step_t6_originator), + MigrationStep("T2", "Add a Session referencing all Dialogs", "A.1 bullet 2", _step_t2_sessions), + MigrationStep("T7", "recording-set Dialog -> Session", "A.1 bullet 9", _step_t7_recording_sets), + MigrationStep("T3", "party_history -> Events", "A.1 bullet 3", _step_t3_party_history), + MigrationStep("T4", "transfer Dialog -> transfer Events (with T5 Session references)", "A.1 bullet 4", _step_t4_transfers), + MigrationStep("T10", "Removed Dialogs -> {} in place", "A.1 bullet 10; 4.5.1", _step_t10_blank_removed), + MigrationStep("T10b", "Re-point analysis/attachment references to removed Dialogs", "AMB-2", _step_t10b_retarget), + MigrationStep("T11", "redacted -> redacted_from", "A.1 bullet 7", _step_t11), + MigrationStep("T12", "amended -> amended_from", "A.1 bullet 8", _step_t12), + MigrationStep("T14", "extensions lists every extension in use", "A.1 bullet 12; 4.1.3", _step_t14_extensions), +] + + +def migrate_0_4_0_to_0_5_0(vcon: Any, *, strict: bool = False) -> MigrationResult: + """Migrate a 0.4.0 vCon dict (or JSON string) to 0.5.0. + + Args: + vcon: The 0.4.0 vCon as a dict or JSON string. A signed vCon (JWS general + form) is migrated as its unsigned payload. The input is not modified. + strict: When True, raise :class:`MigrationError` instead of using a + fallback for a MUST field that cannot be sourced from the input. + + Returns: + ``MigrationResult(vcon, report)``: the 0.5.0 dict and the + :class:`MigrationReport` listing every inferred value, fallback and + unresolved item. + + Raises: + MigrationError: the input is not a 0.4.0 vCon, is encrypted, or (strict) + a required field has no source. + """ + if isinstance(vcon, (str, bytes)): + try: + vcon = json.loads(vcon) + except json.JSONDecodeError as e: + raise MigrationError(f"input is not valid JSON: {e}") from e + if not isinstance(vcon, dict): + raise MigrationError("input must be a vCon dict or JSON string") + + data = copy.deepcopy(vcon) + report = MigrationReport(strict=strict) + ctx = _Context(data, strict, report) + + version = data.get("vcon") + if version is not None and version != SOURCE_VERSION and not ("payload" in data and "signatures" in data): + raise MigrationError( + f"cannot migrate: input vcon is {version!r}, expected {SOURCE_VERSION!r}" + ) + for step in MIGRATION_STEPS: + report.steps_run.append(step.id) + step.func(ctx) + if step.id == "T13": + v = ctx.out.get("vcon") + if v is not None and v != SOURCE_VERSION: + raise MigrationError(f"cannot migrate: input vcon is {v!r}, expected {SOURCE_VERSION!r}") + if v is None: + report.add("T13", INFO, "Input has no 'vcon' parameter; treated as 0.4.0.") + + out = ctx.out + if ctx.sessions: + out["sessions"] = ctx.sessions + if ctx.events: + out["events"] = ctx.events + + # Lawful basis attachments keep their 0.4.0 scope (dialog). 0.5.0 scopes them with + # session plus party; adding a Session reference would be inventing a scope. + for n, att in enumerate(out.get("attachments") or []): + if isinstance(att, dict) and att.get("purpose") == "lawful_basis" and "session" not in att: + report.add( + "post", INFO, + f"attachments[{n}] is a lawful_basis attachment scoped by dialog only; it was left as is. " + "0.5.0 scopes a lawful basis to Sessions with 'session' (plus 'party'); add it if it covers the Session.", + None, attachment=n, + ) + + # Post-check: the result must satisfy the core-05 rules; anything left is reported. + from .dialog import Dialog + + errors, _ = validate_vcon_dict(out, Dialog.MIME_TYPES) + for err in errors: + report.add("post", UNRESOLVED, f"Result does not validate: {err}") + logger.info("Migrated vCon %s to 0.5.0: %s", out.get("uuid"), report.summary()) + return MigrationResult(out, report) diff --git a/src/vcon/party.py b/src/vcon/party.py index 8541e9c..dd192fd 100644 --- a/src/vcon/party.py +++ b/src/vcon/party.py @@ -118,73 +118,3 @@ def to_dict(self): else: party_dict[key] = value return party_dict - - -class PartyHistory: - """ - A class representing party history events in a vCon dialog. - - Party history tracks when parties join, leave, or change state during - a conversation. This is useful for understanding the flow of multi-party - conversations where participants may not all join and leave at the same time. - - Supported event types (vCon 0.4.0 specification): - - join: When the party joins the dialog - - drop: When the party drops out of the dialog - - hold: When the party is put on hold - - unhold: When the party is taken off hold - - mute: When the party is muted - - unmute: When the party is taken off mute - - Attributes: - party (int): Index of the party in the parties array - event (str): Type of event (must be one of VALID_EVENTS) - time (datetime): Time when the event occurred (serialized as ISO 8601) - - The time field is automatically serialized to ISO 8601 format when - converted to dictionary representation. - """ - # Valid event types for party history (from specification) - VALID_EVENTS = [ - "join", # when the party joins the dialog - "drop", # when the party drops out of the dialog - "hold", # when the party is put on hold - "unhold", # when the party is taken off hold - "mute", # when the party is muted - "unmute" # when the party is taken off mute - ] - - def __init__(self, party: int, event: str, time: datetime): - """ - Initialize a new PartyHistory object. - - :param party: Index of the party - :type party: int - :param event: Event type (e.g. "join", "drop", "hold", "unhold", - "mute", "unmute") - :type event: str - :param time: Time of the event - :type time: datetime - """ - # Validate event type - if event not in PartyHistory.VALID_EVENTS: - raise ValueError( - f"Invalid event '{event}'. " - f"Must be one of: {PartyHistory.VALID_EVENTS}" - ) - - self.party = party - self.event = event - self.time = time - - def to_dict(self): - # Handle time field which can be datetime or string - if hasattr(self.time, 'isoformat'): - time_value = self.time.isoformat() - else: - time_value = self.time - return { - "party": self.party, - "event": self.event, - "time": time_value - } diff --git a/src/vcon/session.py b/src/vcon/session.py new file mode 100644 index 0000000..a11437f --- /dev/null +++ b/src/vcon/session.py @@ -0,0 +1,178 @@ +"""Session Object and Session_Reference Object (core-05 sections 4.2 and 4.2.8). + +A Session groups the Dialog and Event Objects of one conversation (or part of +one) and records its receivers. A Session Object with no parameters is allowed. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Dict, List, Optional, Tuple, Union + +from dateutil import parser + +#: Session_Reference ``type`` tokens defined by core-05 (4.2.8.2). Values +#: defined by a vCon extension are also allowed. +SESSION_REFERENCE_TYPES = ("child", "peer", "precursor", "breakout") + +SESSION_PARAMETERS = ( + "start", + "duration", + "parties", + "originator", + "session_id", + "sessions", + "dialog", +) + + +def _is_index(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +class SessionReference: + """Session_Reference Object: how another Session relates to this one.""" + + def __init__(self, session: int, type: str, description: Optional[str] = None) -> None: + if not _is_index(session): + raise ValueError("Session_Reference 'session' must be a non-negative integer") + if not isinstance(type, str) or not type: + raise ValueError("Session_Reference 'type' is required") + self.session = session + self.type = type + self.description = description + + def to_dict(self) -> Dict[str, Any]: + out: Dict[str, Any] = {"session": self.session, "type": self.type} + if self.description is not None: + out["description"] = self.description + return out + + +class Session: + """A Session Object. + + Args: + start: Session start (``datetime`` or ISO 8601 string). SHOULD be present. + duration: Session duration in seconds. Absent means the session has no end. + parties: Indices of the receivers. The first one is the implied originator. + originator: Index of the originator, only when it is not the first party. + session_id: A SessionId Object (``{"local": ..., "remote": ...}``). + sessions: Relationships to other Sessions (``SessionReference`` or dicts). + dialog: Indices of the Dialog Objects that are part of the session. + """ + + def __init__( + self, + start: Optional[Union[datetime, str]] = None, + duration: Optional[Union[int, float]] = None, + parties: Optional[List[int]] = None, + originator: Optional[int] = None, + session_id: Optional[Dict[str, str]] = None, + sessions: Optional[List[Union[SessionReference, Dict[str, Any]]]] = None, + dialog: Optional[List[int]] = None, + ) -> None: + if isinstance(start, datetime): + start = start.isoformat() + elif isinstance(start, str): + start = parser.parse(start).isoformat() + self.start = start + self.duration = duration + self.parties = list(parties) if parties is not None else None + self.originator = originator + self.session_id = session_id + self.sessions = list(sessions) if sessions is not None else None + self.dialog = list(dialog) if dialog is not None else None + + def to_dict(self) -> Dict[str, Any]: + """Serialize, omitting parameters that are ``None``. An empty Session is ``{}``.""" + out: Dict[str, Any] = {} + for name in SESSION_PARAMETERS: + value = getattr(self, name) + if value is None: + continue + if name == "sessions": + value = [v.to_dict() if isinstance(v, SessionReference) else v for v in value] + out[name] = value + return out + + +def validate_session( + session: Any, + *, + party_count: Optional[int] = None, + dialog_count: Optional[int] = None, + session_count: Optional[int] = None, + label: str = "Session", +) -> Tuple[List[str], List[str]]: + """Validate one Session Object dict. Returns ``(errors, warnings)``.""" + errors: List[str] = [] + warnings: List[str] = [] + if not isinstance(session, dict): + return [f"{label} must be a dictionary."], warnings + if not session: + return errors, warnings # an empty placeholder Session is permitted + + if "start" in session: + try: + if not isinstance(session["start"], str): + raise ValueError("not a string") + parser.parse(session["start"]) + except Exception: + errors.append(f"{label} has an invalid 'start' format. Must be an ISO 8601 datetime string.") + else: + warnings.append(f"{label} should have a start parameter.") + + if "duration" in session: + d = session["duration"] + if isinstance(d, bool) or not isinstance(d, (int, float)) or d < 0: + errors.append(f"{label} field 'duration' must be a non-negative number.") + + if "parties" in session: + p = session["parties"] + if not isinstance(p, list): + errors.append(f"{label} field 'parties' must be a list.") + else: + for idx in p: + if not _is_index(idx) or (party_count is not None and idx >= party_count): + errors.append(f"{label} references invalid party index: {idx}") + else: + warnings.append(f"{label} should have a parties parameter.") + + if "originator" in session: + o = session["originator"] + if not _is_index(o) or (party_count is not None and o >= party_count): + errors.append(f"{label} references invalid party index: {o}") + + if "session_id" in session and not isinstance(session["session_id"], dict): + errors.append(f"{label} field 'session_id' must be a SessionId Object.") + + if "dialog" in session: + dl = session["dialog"] + if not isinstance(dl, list): + errors.append(f"{label} field 'dialog' must be a list.") + else: + for idx in dl: + if not _is_index(idx) or (dialog_count is not None and idx >= dialog_count): + errors.append(f"{label} references invalid dialog index: {idx}") + + if "sessions" in session: + refs = session["sessions"] + if not isinstance(refs, list): + errors.append(f"{label} field 'sessions' must be a list.") + else: + for n, ref in enumerate(refs): + if not isinstance(ref, dict): + errors.append(f"{label} sessions[{n}] must be a dictionary.") + continue + for req in ("session", "type"): + if req not in ref: + errors.append(f"{label} sessions[{n}] is missing required field: {req}") + if "session" in ref: + if not _is_index(ref["session"]) or ( + session_count is not None and ref["session"] >= session_count + ): + errors.append(f"{label} references invalid session index: {ref['session']}") + if "type" in ref and not isinstance(ref["type"], str): + errors.append(f"{label} sessions[{n}] field 'type' must be a string.") + return errors, warnings diff --git a/src/vcon/validation.py b/src/vcon/validation.py new file mode 100644 index 0000000..5c75161 --- /dev/null +++ b/src/vcon/validation.py @@ -0,0 +1,493 @@ +"""Structural validation of an unsigned vCon dict against core-05. + +``validate_vcon_dict`` is the engine behind ``Vcon.is_valid()``. It works on +plain dicts so the migration code can reuse it. +""" + +from __future__ import annotations + +import re +from typing import Any, Dict, List, Set, Tuple + +from dateutil import parser + +from .event import CORE_EVENT_TYPES, validate_event +from .session import SESSION_REFERENCE_TYPES, validate_session + +SYNTAX_VERSION = "0.5.0" + +CORE_DIALOG_TYPES = ("recording", "text", "incomplete") +#: Dialog types the library itself builds although core-05 does not define them. +LIBRARY_DIALOG_TYPES = ("audio", "video") +CORE_ENCODINGS = ("base64url", "json", "none") +CORE_DISPOSITIONS = ( + "no-answer", + "congestion", + "failed", + "busy", + "hung-up", + "voicemail-no-message", +) + +#: Extension names this library knows how to recognise, keyed by how they show up. +KNOWN_ATTACHMENT_PURPOSE_EXTENSIONS = { + "lawful_basis": "lawful_basis", + "wtf_transcription": "wtf_transcription", +} +KNOWN_ANALYSIS_TYPE_EXTENSIONS = { + "wtf_transcription": "wtf_transcription", +} + +#: Removed in 0.5.0; their presence means the document is still 0.4.0 shaped. +LEGACY_TOP_LEVEL = {"redacted": "redacted_from", "amended": "amended_from"} +LEGACY_DIALOG_PARAMS = ( + "party_history", + "originator", + "transferee", + "transferor", + "transfer_target", + "original", + "consultation", + "target_dialog", + "recordings", + "recording_set", +) +LEGACY_DIALOG_TYPES = ("transfer", "recording-set") + +_REDACTED_REF_RE = re.compile(r"__REDACTED_REF_(\d{1,5})(?!\d)") + + +def mediatype_ok(mediatype: Any, known: List[str]) -> bool: + """True if ``mediatype`` is acceptable for a Dialog. + + Media type parameters (``; boundary=...``) are ignored. Any ``multipart/``, + ``message/`` or ``text/`` subtype is accepted, since the draft's examples use + ``multipart/alternative`` and the list in the draft is open-ended. + """ + if not isinstance(mediatype, str): + return False + base = mediatype.split(";", 1)[0].strip().lower() + if base in known: + return True + return base.startswith(("multipart/", "message/", "text/")) + + +def _is_index(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +def _as_list(value: Any) -> List[Any]: + if value is None: + return [] + return value if isinstance(value, list) else [value] + + +def _flatten_parties(value: Any) -> List[Any]: + out: List[Any] = [] + for v in _as_list(value): + if isinstance(v, list): + out.extend(v) + else: + out.append(v) + return out + + +def extensions_in_use(vcon: Dict[str, Any]) -> Tuple[Set[str], List[str]]: + """Find the vCon extensions the document uses. + + Returns ``(names, unnamed)``. ``names`` holds extension names this library + recognises (``lawful_basis``, ``wtf_transcription``). ``unnamed`` describes + each use of a value outside the core vocabulary (an Event type, Dialog type, + encoding, disposition or Session_Reference type) whose defining extension + cannot be identified from the document alone. + """ + names: Set[str] = set() + unnamed: List[str] = [] + + for i, att in enumerate(_as_list(vcon.get("attachments"))): + if isinstance(att, dict): + purpose = att.get("purpose") + if purpose in KNOWN_ATTACHMENT_PURPOSE_EXTENSIONS: + names.add(KNOWN_ATTACHMENT_PURPOSE_EXTENSIONS[purpose]) + enc = att.get("encoding") + if enc is not None and enc not in CORE_ENCODINGS: + unnamed.append(f"attachments[{i}] encoding '{enc}'") + for i, an in enumerate(_as_list(vcon.get("analysis"))): + if isinstance(an, dict): + if an.get("type") in KNOWN_ANALYSIS_TYPE_EXTENSIONS: + names.add(KNOWN_ANALYSIS_TYPE_EXTENSIONS[an["type"]]) + enc = an.get("encoding") + if enc is not None and enc not in CORE_ENCODINGS: + unnamed.append(f"analysis[{i}] encoding '{enc}'") + for i, d in enumerate(_as_list(vcon.get("dialog"))): + if isinstance(d, dict) and d: + enc = d.get("encoding") + if enc is not None and enc not in CORE_ENCODINGS: + unnamed.append(f"dialog[{i}] encoding '{enc}'") + disp = d.get("disposition") + if d.get("type") == "incomplete" and disp is not None and disp not in CORE_DISPOSITIONS: + unnamed.append(f"dialog[{i}] disposition '{disp}'") + for i, e in enumerate(_as_list(vcon.get("events"))): + if isinstance(e, dict): + t = e.get("type") + if t is not None and t not in CORE_EVENT_TYPES: + unnamed.append(f"events[{i}] type '{t}'") + for i, s in enumerate(_as_list(vcon.get("sessions"))): + if isinstance(s, dict): + for j, ref in enumerate(_as_list(s.get("sessions"))): + if isinstance(ref, dict): + t = ref.get("type") + if t is not None and t not in SESSION_REFERENCE_TYPES: + unnamed.append(f"sessions[{i}].sessions[{j}] type '{t}'") + return names, unnamed + + +def _scan_redacted_refs(obj: Any, found: Set[int]) -> None: + if isinstance(obj, str): + for m in _REDACTED_REF_RE.finditer(obj): + found.add(int(m.group(1))) + elif isinstance(obj, list): + for v in obj: + _scan_redacted_refs(v, found) + elif isinstance(obj, dict): + for k, v in obj.items(): + _scan_redacted_refs(v, found) + + +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)``.""" + errors: List[str] = [] + warnings: List[str] = [] + + # --- required fields and version ------------------------------------- + for field in ("uuid", "created_at"): + if field not in vcon: + errors.append(f"Missing required field: {field}") + for ts in ("created_at", "updated_at"): + if ts in vcon: + try: + parser.parse(vcon[ts]) + except Exception as e: + errors.append( + f"Invalid {ts} format. Must be an ISO 8601 datetime string: {str(e)}" + ) + if "vcon" in vcon and vcon["vcon"] != SYNTAX_VERSION: + errors.append( + f"Unsupported vcon syntax version '{vcon['vcon']}': this library writes " + f"'{SYNTAX_VERSION}'. Migrate a 0.4.0 vCon with migrate_0_4_0_to_0_5_0()." + ) + for old, new in LEGACY_TOP_LEVEL.items(): + if old in vcon: + errors.append(f"Legacy 0.4.0 parameter '{old}' was renamed '{new}' in 0.5.0.") + + # --- parties ---------------------------------------------------------- + parties = vcon.get("parties", []) + if "parties" in vcon: + if not isinstance(parties, list): + errors.append("Field 'parties' must be a list.") + parties = [] + else: + for i, party in enumerate(parties): + if not isinstance(party, dict): + errors.append(f"Party at index {i} must be a dictionary.") + party_count = len(parties) + + dialogs = vcon.get("dialog", []) + if not isinstance(dialogs, list): + errors.append("Field 'dialog' must be a list.") + dialogs = [] + dialog_count = len(dialogs) + sessions = vcon.get("sessions", []) + if not isinstance(sessions, list): + errors.append("Field 'sessions' must be a list.") + sessions = [] + session_count = len(sessions) + events = vcon.get("events", []) + if not isinstance(events, list): + errors.append("Field 'events' must be a list.") + events = [] + attachments = vcon.get("attachments", []) + if "attachments" in vcon and not isinstance(attachments, list): + errors.append("Field 'attachments' must be a list.") + attachments = [] + analyses = vcon.get("analysis", []) + if "analysis" in vcon and not isinstance(analyses, list): + errors.append("Field 'analysis' must be a list.") + analyses = [] + redacted = isinstance(vcon.get("redacted_from"), dict) + + # --- redacted_from / amended_from ------------------------------------ + if "redacted_from" in vcon and "amended_from" in vcon: + errors.append("redacted_from and amended_from are mutually exclusive.") + rf = vcon.get("redacted_from") + if "redacted_from" in vcon: + if not isinstance(rf, dict): + errors.append("Field 'redacted_from' must be an object.") + else: + if "type" not in rf: + errors.append("redacted_from is missing required field: type") + if "url" in rf and "content_hash" not in rf: + errors.append("redacted_from with url must include content_hash.") + af = vcon.get("amended_from") + if "amended_from" in vcon: + if not isinstance(af, dict): + errors.append("Field 'amended_from' must be an object.") + else: + if "uuid" not in af and "url" not in af: + errors.append("amended_from must include uuid, or an external reference (url).") + if "url" in af and "content_hash" not in af: + errors.append("amended_from with url must include content_hash.") + + # --- extensions / critical ------------------------------------------- + ext_listed = vcon.get("extensions", []) + if "extensions" in vcon and ( + not isinstance(ext_listed, list) or not all(isinstance(x, str) for x in ext_listed) + ): + errors.append("Field 'extensions' must be a list of strings.") + ext_listed = [] + crit = vcon.get("critical", []) + if "critical" in vcon and ( + not isinstance(crit, list) or not all(isinstance(x, str) for x in crit) + ): + errors.append("Field 'critical' must be a list of strings.") + crit = [] + for name in crit: + if name not in ext_listed: + errors.append( + f"Extension '{name}' is listed in critical but not in extensions." + ) + used, unnamed = extensions_in_use(vcon) + for name in sorted(used): + if name not in ext_listed: + errors.append( + f"Extension '{name}' is in use but is not listed in the extensions parameter." + ) + if unnamed and not ext_listed: + errors.append( + "Values outside the core vocabulary are in use but the extensions parameter " + "lists no extension: " + "; ".join(unnamed) + "." + ) + + # --- dialog ----------------------------------------------------------- + for i, dialog in enumerate(dialogs): + if not isinstance(dialog, dict): + errors.append(f"Dialog at index {i} must be a dictionary.") + continue + if not dialog: + continue # empty placeholder Dialog Object (4.5.1) + dialog_type = dialog.get("type") + if "type" not in dialog: + errors.append(f"Dialog at index {i} is missing required field: type") + elif dialog_type in LEGACY_DIALOG_TYPES: + errors.append( + f"Dialog at index {i} has type '{dialog_type}', which was removed in 0.5.0 " + "(use Events and Sessions; migrate with migrate_0_4_0_to_0_5_0())." + ) + elif ( + dialog_type not in CORE_DIALOG_TYPES + and dialog_type not in LIBRARY_DIALOG_TYPES + and not ext_listed + ): + # A Dialog type outside the core vocabulary must come from a vCon + # extension, which has to be listed in extensions (4.1.3). + errors.append(f"Dialog at index {i} has an invalid type: {dialog_type}") + for legacy in LEGACY_DIALOG_PARAMS: + if legacy in dialog: + errors.append( + f"Dialog at index {i} has parameter '{legacy}', which was removed in 0.5.0." + ) + if dialog_type == "incomplete": + if "disposition" not in dialog: + errors.append(f"Dialog at index {i} of type 'incomplete' must have a disposition.") + for forbidden in ( + "mediatype", "filename", "body", "encoding", "url", "content_hash", + "message_id", "redacted_segments", + ): + if forbidden in dialog: + errors.append( + f"Dialog at index {i} of type 'incomplete' must not have field: {forbidden}" + ) + + if "parties" in dialog: + dp = dialog["parties"] + if not isinstance(dp, (list, int)) or isinstance(dp, bool): + errors.append(f"Dialog at index {i} field 'parties' must be a list.") + else: + for party_idx in _flatten_parties(dp): + if party_idx is None: + continue # null placeholder for a channel with no contributor + if not _is_index(party_idx) or party_idx >= party_count: + errors.append(f"Dialog at index {i} references invalid party index: {party_idx}") + if "start" in dialog: + try: + parser.parse(dialog["start"]) + except Exception: + errors.append( + f"Dialog at index {i} has an invalid 'start' format. Must be an ISO 8601 datetime string." + ) + if dialog_type != "incomplete": + has_content = "body" in dialog + if "mediatype" in dialog: + if not mediatype_ok(dialog["mediatype"], dialog_mime_types): + errors.append( + f"Dialog at index {i} has an invalid or missing mediatype: {dialog.get('mediatype')}" + ) + elif has_content: + errors.append( + f"Dialog at index {i} has an invalid or missing mediatype: missing" + ) + if "redacted_segments" in dialog: + segs = dialog["redacted_segments"] + if not isinstance(segs, list): + errors.append(f"Dialog at index {i} field 'redacted_segments' must be a list.") + else: + for n, seg in enumerate(segs): + if not isinstance(seg, dict) or "start" not in seg or "end" not in seg: + errors.append( + f"Dialog at index {i} redacted_segments[{n}] requires start and end." + ) + + # --- sessions --------------------------------------------------------- + if (dialog_count or events) and not sessions: + errors.append( + "At least one Session Object MUST exist if the events array or the dialog array contains Objects." + ) + for i, s in enumerate(sessions): + e, w = validate_session( + s, + party_count=party_count, + dialog_count=dialog_count, + session_count=session_count, + label=f"Session at index {i}", + ) + errors.extend(e) + warnings.extend(w) + referenced_dialogs: Set[int] = set() + for s in sessions: + if isinstance(s, dict) and isinstance(s.get("dialog"), list): + referenced_dialogs.update(x for x in s["dialog"] if _is_index(x)) + for i, d in enumerate(dialogs): + if isinstance(d, dict) and d and i not in referenced_dialogs: + warnings.append(f"Dialog at index {i} is not referenced by any Session Object.") + + # --- events ----------------------------------------------------------- + for i, ev in enumerate(events): + e, w = validate_event( + ev, + party_count=party_count, + dialog_count=dialog_count, + session_count=session_count, + label=f"Event at index {i}", + ) + errors.extend(e) + warnings.extend(w) + if isinstance(ev, dict) and ev.get("type") == "channel-contributors" and _is_index(ev.get("dialog")): + di = ev["dialog"] + if di < dialog_count and isinstance(dialogs[di], dict) and dialogs[di].get("type") != "recording": + errors.append( + f"Event at index {i} of type 'channel-contributors' must reference a 'recording' Dialog." + ) + + # --- attachments ------------------------------------------------------ + for i, attachment in enumerate(attachments): + if not isinstance(attachment, dict): + errors.append(f"Attachment at index {i} must be a dictionary.") + continue + if "purpose" not in attachment: + errors.append(f"Attachment at index {i} is missing required field: purpose") + has_inline = "body" in attachment and "encoding" in attachment + has_external = "url" in attachment and "content_hash" in attachment + if not (has_inline or has_external or redacted): + errors.append(f"Attachment at index {i} must include body+encoding or url+content_hash.") + if "encoding" in attachment and attachment["encoding"] not in CORE_ENCODINGS and not ext_listed: + errors.append(f"Attachment at index {i} has invalid encoding: {attachment['encoding']}") + if "body" in attachment and attachment["body"] != "" and "mediatype" not in attachment: + errors.append( + f"Attachment at index {i} is missing required field: mediatype (needed for inline content)" + ) + if "start" not in attachment: + errors.append(f"Attachment at index {i} is missing required field: start") + if "party" not in attachment: + errors.append(f"Attachment at index {i} is missing required field: party") + elif not _is_index(attachment["party"]) or attachment["party"] >= party_count: + errors.append(f"Attachment at index {i} references invalid party index: {attachment['party']}") + if "dialog" not in attachment and "session" not in attachment: + errors.append( + f"Attachment at index {i} must have at least one of dialog or session." + ) + if "dialog" in attachment: + dv = attachment["dialog"] + if not _is_index(dv) or dv >= dialog_count: + errors.append(f"Attachment at index {i} references invalid dialog index: {dv}") + if "session" in attachment: + sv = attachment["session"] + vals = sv if isinstance(sv, list) else [sv] + if not vals and isinstance(sv, list): + errors.append(f"Attachment at index {i} field 'session' must not be empty.") + for v in vals: + if not _is_index(v) or v >= session_count: + errors.append(f"Attachment at index {i} references invalid session index: {v}") + + # --- analysis --------------------------------------------------------- + for i, analysis in enumerate(analyses): + if not isinstance(analysis, dict): + errors.append(f"Analysis at index {i} must be a dictionary.") + continue + for field in ("type", "vendor"): + if field not in analysis: + errors.append(f"Analysis at index {i} is missing required field: {field}") + if "body" in analysis and analysis["body"] != "" and "encoding" not in analysis: + errors.append(f"Analysis at index {i} is missing required field: encoding") + if "encoding" in analysis and analysis["encoding"] not in CORE_ENCODINGS and not ext_listed: + errors.append(f"Analysis at index {i} has invalid encoding: {analysis['encoding']}") + for key, count, noun in ( + ("dialog", dialog_count, "dialog"), + ("sessions", session_count, "session"), + ("attachment", len(attachments), "attachment"), + ("analysis", len(analyses), "analysis"), + ): + if key not in analysis: + continue + val = analysis[key] + vals = val if isinstance(val, list) else [val] + if not isinstance(val, (int, list)) or isinstance(val, bool): + errors.append(f"Analysis at index {i} has an invalid '{key}' reference type.") + continue + for v in vals: + if not _is_index(v) or v >= count: + errors.append(f"Analysis at index {i} references invalid {noun} index: {v}") + elif key == "analysis" and v == i: + errors.append(f"Analysis at index {i} must not reference itself in analysis.") + if not any(k in analysis for k in ("dialog", "sessions", "attachment", "analysis")): + warnings.append( + f"Analysis at index {i} should have at least one of dialog, sessions, attachment or analysis." + ) + + # --- redacted_strings ------------------------------------------------- + rs = vcon.get("redacted_strings") + refs_declared: Set[int] = set() + if "redacted_strings" in vcon: + if not isinstance(rs, list): + errors.append("Field 'redacted_strings' must be a list.") + else: + if len(rs) > 99999: + errors.append("A vCon MUST NOT have more than 99999 redacted substrings.") + for n, item in enumerate(rs): + if not isinstance(item, dict) or not isinstance(item.get("ref"), int) or isinstance(item.get("ref"), bool): + errors.append(f"redacted_strings[{n}] requires an integer ref.") + continue + if not 1 <= item["ref"] <= 99999: + errors.append(f"redacted_strings[{n}] ref must be between 1 and 99999.") + if item["ref"] in refs_declared: + errors.append(f"redacted_strings[{n}] duplicates ref {item['ref']}.") + refs_declared.add(item["ref"]) + found: Set[int] = set() + _scan_redacted_refs({k: v for k, v in vcon.items() if k != "redacted_strings"}, found) + for ref in sorted(found - refs_declared): + errors.append( + f"__REDACTED_REF_{ref} appears in the vCon but has no entry in redacted_strings." + ) + + return errors, warnings diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 709d761..2492cde 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -20,6 +20,14 @@ from .party import Party from .dialog import Dialog, b64url_encode from .body import decode_body +from .session import Session +from .event import Event +from .migration import ( + MigrationError, + MigrationReport, + migrate_0_4_0_to_0_5_0 as _migrate_0_4_0_to_0_5_0, +) +from .validation import validate_vcon_dict # Set up logger logger = logging.getLogger(__name__) @@ -40,37 +48,48 @@ # Define allowed properties for each object type _ALLOWED_VCON_PROPERTIES = { - "uuid", "vcon", "created_at", "updated_at", "redacted", + "uuid", "vcon", "created_at", "updated_at", "redacted_from", "group", "parties", "dialog", "attachments", "analysis", - "signatures", "payload", "meta", "subject", "amended", - "extensions", "critical" + "signatures", "payload", "meta", "subject", "amended_from", + "extensions", "critical", "sessions", "events", "redacted_strings" +} + +_ALLOWED_SESSION_PROPERTIES = { + "start", "duration", "parties", "originator", "session_id", + "sessions", "dialog" +} + +_ALLOWED_EVENT_PROPERTIES = { + "type", "time", "sessions", "party", "dialog", "channel", + "contributors", "button", "transferee", "transfer_target", + "consultation", "target_session" } _ALLOWED_PARTY_PROPERTIES = { "type", "name", "contact", "meta", "external_id", "party_id", "tel", "stir", "mailto", "validation", "gmlpos", "civicaddress", - "uuid", "role", "contact_list", "sip", "did", "jCard", "timezone" + "uuid", "role", "contact_list", "sip", "did", "jCard", "timezone", + "org", "dept" } _ALLOWED_DIALOG_PROPERTIES = { "type", "start", "parties", "duration", "mediatype", "filename", "body", "encoding", "url", "content_hash", "disposition", - "party_history", "transferee", "transferor", "transfer_target", - "original", "consultation", "target_dialog", "campaign", - "interaction", "skill", "meta", "metadata", "transfer", - "signaling", "originator", "resolution", "frame_rate", + "campaign", "interaction", "skill", "meta", "metadata", + "signaling", "resolution", "frame_rate", "codec", "bitrate", "thumbnail", "streaming", "video", - "session_id", "application", "message_id" + "session_id", "application", "message_id", "redacted_segments" } _ALLOWED_ATTACHMENT_PROPERTIES = { - "purpose", "body", "encoding", "start", "party", "dialog", + "purpose", "body", "encoding", "start", "party", "dialog", "session", "mediatype", "filename", "url", "content_hash" } _ALLOWED_ANALYSIS_PROPERTIES = { - "type", "dialog", "vendor", "product", "body", "encoding", - "schema", "mediatype", "filename", "url", "content_hash" + "type", "dialog", "sessions", "attachment", "analysis", "vendor", + "product", "body", "encoding", "schema", "mediatype", "filename", + "url", "content_hash", "meta" } # Configure logging @@ -78,6 +97,19 @@ _LAST_V8_TIMESTAMP = None +#: JWS algorithms accepted for signing and verifying. "none" is excluded: +#: core-05 section 6.2.2, "The alg parameter MUST NOT have the value none". +PERMITTED_JWS_ALGORITHMS = ( + "RS256", "RS384", "RS512", + "PS256", "PS384", "PS512", + "ES256", "ES384", "ES512", + "EdDSA", +) + + +class AlgorithmNotPermittedError(ValueError): + """A JWS used ``alg`` "none" (forbidden by core-05) or an unsupported algorithm.""" + class Attachment: """ @@ -106,9 +138,16 @@ def __init__( start: Optional[str] = None, party: Optional[int] = None, dialog: Optional[int] = None, + session: Optional[Union[int, List[int]]] = None, ) -> None: """ Initialize an Attachment object. + + Under core-05 (section 4.6) an attachment needs ``party`` and at least + one of ``dialog`` or ``session``. ``party`` defaults to 0. Neither + ``dialog`` nor ``session`` is defaulted here, because the right index + depends on the vCon; ``Vcon.add_attachment()`` fills in the vCon's + Sessions when neither is given. Args: purpose: The purpose of the attachment @@ -123,10 +162,9 @@ def __init__( raise ValueError(f"Invalid encoding: {encoding}. Must be one of {self.VALID_ENCODINGS}") # Fill in defaults required by the WG JSON schema (every attachment - # requires start/party/dialog; inline content requires mediatype). - # See CHANGELOG 0.10.0 for the contract note: party/dialog previously - # defaulted to being omitted (None) when not supplied; they now - # default to 0, matching the existing add_tag() convention. + # requires start and party; inline content requires mediatype). + # party defaults to 0 (the add_tag() convention). dialog is no longer + # defaulted: core-05 allows session in its place. if mediatype is None and encoding == "json": mediatype = "application/json" @@ -139,7 +177,8 @@ def __init__( self.content_hash = content_hash self.start = start self.party = party if party is not None else 0 - self.dialog = dialog if dialog is not None else 0 + self.dialog = dialog + self.session = session logger.debug(f"Created new attachment of purpose {purpose} with {encoding} encoding") def to_dict(self) -> Dict[str, Any]: @@ -160,6 +199,7 @@ def to_dict(self) -> Dict[str, Any]: "start": self.start, "party": self.party, "dialog": self.dialog, + "session": self.session, } return {k: v for k, v in attachment_dict.items() if v is not None} @@ -225,16 +265,16 @@ class Vcon: - Digital signatures and encryption - Extensions and critical for extensibility - Civic address information for location data - - Party history for tracking join/drop/hold/mute events + - Sessions (``sessions``) grouping dialog and events, and Events + (``events``) for joins, drops, holds, key presses and transfers - New in vCon 0.4.0: - - Extensions field for listing used extensions - - Critical field for incompatible extensions - - Enhanced party fields (sip, did, jCard, timezone) - - Dialog session_id and content_hash fields - - Party history with event tracking - - Updated media type validation - - New disposition values for incomplete dialogs + New in vCon 0.5.0 (draft-ietf-vcon-vcon-core-05): + - ``sessions`` and ``events`` arrays; ``Session`` and ``Event`` classes + - ``redacted_from`` and ``amended_from`` replace ``redacted`` and ``amended`` + - Attachments need ``party`` and ``dialog`` or ``session`` + - ``extensions`` MUST list every extension in use; ``alg: "none"`` is rejected + - Dialog ``parties`` are contributors only; empty ``{}`` Dialog placeholders + - 0.4.0 input is migrated on load (see ``migrate_0_4_0_to_0_5_0``) Attributes: vcon_dict (Dict): The underlying dictionary containing all vCon data @@ -245,10 +285,17 @@ def __init__( self, vcon_dict: Dict[str, Any] = None, property_handling: str = PROPERTY_HANDLING_DEFAULT, + migrate_legacy: bool = True, + strict_migration: bool = False, ) -> None: """ Initialize a Vcon object from a dictionary. + A dict that declares ``"vcon": "0.4.0"`` (or a signed vCon whose payload + does) is migrated to 0.5.0 here, using ``migrate_0_4_0_to_0_5_0``. The + report is kept in ``self.migration_report``. A dict with any other (or no) + ``vcon`` value is taken as is. + Args: vcon_dict: A dictionary representing a vCon. Defaults to an empty dict. property_handling: How to handle non-standard properties. @@ -256,6 +303,11 @@ def __init__( - "default": Keep non-standard properties (default) - "strict": Remove non-standard properties - "meta": Move non-standard properties to meta object + migrate_legacy: Migrate 0.4.0 input to 0.5.0 (default True). When + False the 0.4.0 dict is kept untouched and ``is_valid()`` will + report it as not 0.5.0. + strict_migration: Passed to the migration as ``strict``; raises + ``MigrationError`` when a required field has no source. Example: >>> vcon = Vcon({"uuid": "123", "custom_field": "value"}) @@ -270,6 +322,18 @@ def __init__( # Initialize with empty dict if none provided if vcon_dict is None: vcon_dict = {} + + #: MigrationReport when the input was migrated from 0.4.0, else None. + self.migration_report: Optional[MigrationReport] = None + if migrate_legacy and self._is_legacy_0_4_0(vcon_dict): + migrated, self.migration_report = _migrate_0_4_0_to_0_5_0( + vcon_dict, strict=strict_migration + ) + logger.warning( + "Migrated vCon %s from 0.4.0 to 0.5.0 on load (%s)", + migrated.get("uuid"), self.migration_report.summary(), + ) + vcon_dict = migrated # Version field is now optional - no version management required @@ -308,6 +372,18 @@ def __init__( for dialog in processed_vcon["dialog"] ] + if "sessions" in processed_vcon: + processed_vcon["sessions"] = [ + self._process_properties(sess, _ALLOWED_SESSION_PROPERTIES) + for sess in processed_vcon["sessions"] + ] + + if "events" in processed_vcon: + processed_vcon["events"] = [ + self._process_properties(event, _ALLOWED_EVENT_PROPERTIES) + for event in processed_vcon["events"] + ] + if "attachments" in processed_vcon: processed_vcon["attachments"] = [ self._process_properties(attachment, _ALLOWED_ATTACHMENT_PROPERTIES) @@ -323,6 +399,41 @@ def __init__( self.vcon_dict = json.loads(json.dumps(processed_vcon)) logger.info(f"Vcon object initialized with UUID: {processed_vcon.get('uuid', 'not set')}") + @staticmethod + def _is_legacy_0_4_0(vcon_dict: Any) -> bool: + """True if the dict declares syntax 0.4.0, directly or in a signed payload.""" + if not isinstance(vcon_dict, dict): + return False + if vcon_dict.get("vcon") == "0.4.0": + return True + if "vcon" not in vcon_dict and isinstance(vcon_dict.get("payload"), str) and "signatures" in vcon_dict: + try: + raw = vcon_dict["payload"] + payload = json.loads(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))) + return isinstance(payload, dict) and payload.get("vcon") == "0.4.0" + except Exception: + return False + return False + + @classmethod + def migrate_0_4_0_to_0_5_0( + cls, + source: Union[str, Dict[str, Any]], + strict: bool = False, + property_handling: str = PROPERTY_HANDLING_DEFAULT, + ) -> "Vcon": + """ + Explicitly migrate a 0.4.0 vCon (dict or JSON string) and return a Vcon. + + The migration report is available as ``vcon.migration_report``. Unlike + the implicit migration on load, this also accepts input with no + ``vcon`` parameter. See :func:`vcon.migration.migrate_0_4_0_to_0_5_0`. + """ + migrated, report = _migrate_0_4_0_to_0_5_0(source, strict=strict) + obj = cls(migrated, property_handling=property_handling, migrate_legacy=False) + obj.migration_report = report + return obj + def set_created_at(self, created_at: Union[str, datetime]) -> None: """ Set the created_at field in the vCon. @@ -399,6 +510,8 @@ def build_from_json( cls, json_string: str, property_handling: str = PROPERTY_HANDLING_DEFAULT, + migrate_legacy: bool = True, + strict_migration: bool = False, ) -> "Vcon": """ Initialize a Vcon object from a JSON string. @@ -427,6 +540,8 @@ def build_from_json( return cls( vcon_dict, property_handling=property_handling, + migrate_legacy=migrate_legacy, + strict_migration=strict_migration, ) except json.JSONDecodeError as e: logger.error(f"Failed to parse JSON string: {str(e)}") @@ -463,7 +578,7 @@ def build_new( logger.debug(f"Generated UUID8: {uuid}") vcon_dict = { - "vcon": "0.4.0", + "vcon": "0.5.0", "uuid": uuid, "parties": [], "dialog": [], @@ -545,6 +660,32 @@ def get_tag(self, tag_name: str) -> Optional[str]: logger.debug(f"Found value for tag {tag_name}: {tag_value}") return tag_value + def _resolve_attachment_scope( + self, + dialog: Optional[int] = None, + session: Optional[Union[int, List[int]]] = None, + ) -> Dict[str, Any]: + """ + Work out the ``dialog`` / ``session`` scope for a new attachment. + + Core-05 section 4.6 needs at least one of the two. When the caller gives + neither, the attachment is scoped to every Session in the vCon; if the + vCon has no Session yet, an empty placeholder Session is added (an empty + Session Object is permitted) and referenced. + """ + scope: Dict[str, Any] = {} + if dialog is not None: + scope["dialog"] = dialog + if session is not None: + scope["session"] = session + if not scope: + sessions = self.vcon_dict.setdefault("sessions", []) + if not sessions: + sessions.append({}) + logger.info("Added placeholder Session to scope an attachment") + scope["session"] = list(range(len(sessions))) + return scope + def add_tag(self, tag_name: str, tag_value: str) -> None: """ Add a tag to the vCon. @@ -572,8 +713,8 @@ def add_tag(self, tag_name: str, tag_value: str) -> None: "mediatype": "application/json", "start": self.vcon_dict.get("created_at"), "party": 0, - "dialog": 0, } + tags_attachment.update(self._resolve_attachment_scope()) self.vcon_dict["attachments"].append(tags_attachment) else: # Normalize a legacy (pre-0.10.0 / -02 convention) JSON-string @@ -696,17 +837,28 @@ def add_lawful_basis_attachment( purpose_grants: list, party_index: Optional[int] = None, dialog_index: Optional[int] = None, + session_index: Optional[Union[int, List[int]]] = None, **kwargs ) -> None: """ Add a lawful basis attachment to the vCon. + The attachment has ``purpose`` ``"lawful_basis"`` and, under core-05, + is scoped to Sessions with ``session`` plus ``party``. ``party`` is the + party recording the basis (default 0). ``session`` is ``session_index`` + if given; otherwise the Sessions that list ``dialog_index`` (when given + and found); otherwise every Session in the vCon (an empty placeholder + Session is added if there is none). ``dialog`` is added only when + ``dialog_index`` is given. The ``lawful_basis`` extension name is added + to ``extensions``. + Args: lawful_basis: The lawful basis type (consent, contract, etc.) expiration: ISO 8601 timestamp when the lawful basis expires purpose_grants: List of purpose grant dictionaries - party_index: Index of the party this applies to (optional) + party_index: Index of the party that records the basis (default 0) dialog_index: Index of the dialog this applies to (optional) + session_index: Session index or list of indices this applies to (optional) **kwargs: Additional lawful basis parameters Example: @@ -732,11 +884,16 @@ def add_lawful_basis_attachment( **kwargs ) - # Add party and dialog references if provided, defaulting to 0 - # (matching add_tag()'s existing convention) since the WG JSON - # schema requires both on every attachment. + # party is required (default 0, add_tag()'s convention); core-05 + # also needs dialog or session, and the basis is scoped to Sessions. attachment["party"] = party_index if party_index is not None else 0 - attachment["dialog"] = dialog_index if dialog_index is not None else 0 + attachment.update( + self._resolve_attachment_scope( + dialog=dialog_index, + session=session_index if session_index is not None + else self._sessions_for_dialog(dialog_index), + ) + ) # Fill in mediatype/start, also required by the schema, unless # already set via **kwargs. @@ -761,17 +918,22 @@ def add_wtf_transcription_attachment( metadata: Dict[str, Any], party_index: Optional[int] = None, dialog_index: Optional[int] = None, + session_index: Optional[Union[int, List[int]]] = None, **kwargs ) -> None: """ Add a WTF transcription attachment to the vCon. + Scoped like ``add_lawful_basis_attachment``: ``dialog_index`` and/or + ``session_index``, else every Session in the vCon. + Args: transcript: Transcript information dictionary segments: List of segment dictionaries metadata: Metadata dictionary party_index: Index of the party this applies to (optional) dialog_index: Index of the dialog this applies to (optional) + session_index: Session index or list of indices (optional) **kwargs: Additional WTF parameters Example: @@ -796,11 +958,14 @@ def add_wtf_transcription_attachment( **kwargs ) - # Add party and dialog references if provided, defaulting to 0 - # (matching add_tag()'s existing convention) since the WG JSON - # schema requires both on every attachment. attachment["party"] = party_index if party_index is not None else 0 - attachment["dialog"] = dialog_index if dialog_index is not None else 0 + attachment.update( + self._resolve_attachment_scope( + dialog=dialog_index, + session=session_index if session_index is not None + else self._sessions_for_dialog(dialog_index), + ) + ) # Fill in mediatype/start, also required by the schema, unless # already set via **kwargs. @@ -863,7 +1028,7 @@ def add_wtf_transcription_analysis( ) wtf_body = wtf_attachment["body"] - dialog_ref = [dialog_index] if dialog_index is not None else [] + dialog_ref = [dialog_index] if dialog_index is not None else None self.add_analysis( type="transcription", @@ -883,6 +1048,16 @@ def add_wtf_transcription_analysis( except ImportError: raise RuntimeError("WTF extension not available") + def _sessions_for_dialog(self, dialog_index: Optional[int]) -> Optional[List[int]]: + """Indices of the Sessions that list ``dialog_index``, or None if there are none.""" + if dialog_index is None: + return None + found = [ + n for n, s in enumerate(self.vcon_dict.get("sessions", [])) + if isinstance(s, dict) and dialog_index in (s.get("dialog") or []) + ] + return found or None + def find_lawful_basis_attachments(self, party_index: Optional[int] = None) -> List[Dict[str, Any]]: """ Find lawful basis attachments in the vCon. @@ -1065,6 +1240,7 @@ def add_attachment( start: Optional[str] = None, party: Optional[int] = None, dialog: Optional[int] = None, + session: Optional[Union[int, List[int]]] = None, ) -> Attachment: """ Add an attachment to the vCon. @@ -1072,6 +1248,11 @@ def add_attachment( This method creates a new attachment with the specified type, body, and encoding and adds it to the vCon's attachments list. + Core-05 needs ``party`` plus ``dialog`` or ``session``. ``party`` defaults + to 0. If neither ``dialog`` nor ``session`` is given, the attachment is + scoped to every Session in the vCon (an empty placeholder Session is added + if there is none). + Args: purpose: The purpose of the attachment body: The content of the attachment @@ -1081,8 +1262,9 @@ def add_attachment( url: Optional URL for external attachments content_hash: Optional content hash for external attachments start: Optional timestamp for the attachment - party: Optional party index + party: Optional party index (default 0) dialog: Optional dialog index + session: Optional Session index or list of indices Returns: The created Attachment object @@ -1102,6 +1284,9 @@ def add_attachment( if start is None: start = self.vcon_dict.get("created_at") + if dialog is None and session is None: + session = self._resolve_attachment_scope()["session"] + attachment = Attachment( purpose=purpose, body=body, @@ -1113,6 +1298,7 @@ def add_attachment( start=start, party=party, dialog=dialog, + session=session, ) attachment_dict = attachment.to_dict() @@ -1189,9 +1375,12 @@ def add_analysis( self, *, type: str, - dialog: Union[List[int], int], vendor: str, body: Union[Dict[str, Any], List[Any], str], + dialog: Optional[Union[List[int], int]] = None, + sessions: Optional[Union[List[int], int]] = None, + attachment: Optional[Union[List[int], int]] = None, + analysis: Optional[Union[List[int], int]] = None, encoding: str = "none", mediatype: Optional[str] = None, filename: Optional[str] = None, @@ -1211,7 +1400,10 @@ def add_analysis( Args: type: The type of analysis - dialog: Index or list of indices of the associated dialog entries + dialog: Index or list of indices of the associated dialog entries (optional) + sessions: Index or list of indices of the Sessions analysed (optional) + attachment: Index or list of indices of the attachments analysed (optional) + analysis: Index or list of indices of other Analysis Objects used (optional) vendor: The name of the vendor who performed the analysis body: The analysis data encoding: The encoding format of the body (default: "none") @@ -1260,13 +1452,21 @@ def add_analysis( raise Exception("Invalid base64url body: ", e) # Build the analysis object - analysis = { - "type": type, - "dialog": dialog, + analysis_obj: Dict[str, Any] = {"type": type} + if dialog is not None: + analysis_obj["dialog"] = dialog + if sessions is not None: + analysis_obj["sessions"] = sessions + if attachment is not None: + analysis_obj["attachment"] = attachment + if analysis is not None: + analysis_obj["analysis"] = analysis + analysis_obj.update({ "vendor": vendor, "body": body, "encoding": encoding, - } + }) + analysis = analysis_obj if mediatype is not None: analysis["mediatype"] = mediatype @@ -1378,7 +1578,7 @@ def find_dialog(self, by: str, val: str) -> Optional[Dialog]: """ logger.debug(f"Searching for dialog with {by}={val}") dialog = next( - (dialog for dialog in self.vcon_dict["dialog"] if _get(dialog, by) == val), + (dialog for dialog in self.vcon_dict["dialog"] if dialog and _get(dialog, by) == val), None, ) if dialog: @@ -1398,125 +1598,145 @@ def find_dialogs_by_type(self, type: str) -> List[Dict[str, Any]]: A list of matching dialog dictionaries Example: >>> vcon = Vcon.build_new() - >>> vcon.add_transfer_dialog(start="2023-01-20T14:00:00Z", transfer_data={...}) - >>> transfer_dialogs = vcon.find_dialogs_by_type("transfer") + >>> incomplete = vcon.find_dialogs_by_type("incomplete") """ return [dialog for dialog in self.vcon_dict["dialog"] if dialog.get("type") == type] - def add_dialog(self, dialog: Dialog) -> None: + def add_dialog(self, dialog: Dialog, session: Optional[int] = None) -> int: """ Add a dialog entry to the vCon. This method adds a Dialog object to the vCon's dialog list. A dialog entry represents a segment of the conversation with its associated metadata. + Use ``Dialog.placeholder()`` to add an empty Dialog Object (``{}``) that + holds an array position. Args: dialog: The Dialog object to add + session: Optional index of an existing Session; the new Dialog's + index is appended to that Session's ``dialog`` list. Core-05 + requires at least one Session when the vCon has Dialogs, so add + Sessions with ``add_session()``. + + Returns: + The index of the new Dialog in the ``dialog`` array. Example: >>> vcon = Vcon.build_new() >>> dialog = Dialog(type="text", start="2023-01-01T00:00:00Z", parties=[0]) - >>> vcon.add_dialog(dialog) + >>> index = vcon.add_dialog(dialog) """ logger.debug(f"Adding dialog: {dialog.to_dict()}") # Process dialog dict according to property handling mode dialog_dict = dialog.to_dict() processed_dialog = self._process_properties(dialog_dict, _ALLOWED_DIALOG_PROPERTIES) + + if session is not None: + sessions = self.vcon_dict.get("sessions", []) + if not isinstance(session, int) or not 0 <= session < len(sessions): + raise ValueError(f"Invalid session index: {session}") self.vcon_dict["dialog"].append(processed_dialog) - logger.info(f"Added dialog of type {dialog.type}") + index = len(self.vcon_dict["dialog"]) - 1 + if session is not None: + self.vcon_dict["sessions"][session].setdefault("dialog", []).append(index) + logger.info(f"Added dialog of type {getattr(dialog, 'type', 'placeholder')}") + return index - def add_transfer_dialog( - self, - start: Union[str, datetime], - transfer_data: Dict[str, Any], - parties: List[int], - metadata: Optional[Dict[str, Any]] = None - ) -> None: + def add_session(self, session: Union[Session, Dict[str, Any], None] = None) -> int: """ - Add a transfer dialog entry to the vCon. - This method creates a dialog entry of type "transfer" with the provided - transfer data and adds it to the vCon's dialog list. - Args: - start: When the transfer occurred (ISO 8601 string or datetime) - transfer_data: Transfer-specific information - parties: List of party indices involved - metadata: Additional metadata (optional) + Add a Session Object and return its index in the ``sessions`` array. + + With no argument an empty placeholder Session (``{}``) is added, which + core-05 permits. + Example: >>> vcon = Vcon.build_new() - >>> vcon.add_transfer_dialog( - ... start="2023-01-20T14:05:00Z", - ... transfer_data={ - ... "reason": "Call forwarded", - ... "from": "+1234567890", - ... "to": "+1987654321", - ... "protocol": "SIP", - ... "details": { - ... "sipMessage": "SIP/2.0 302 Moved Temporarily" - ... } - ... }, - ... parties=[0, 1] - ... ) + >>> s = vcon.add_session(Session(start="2023-01-01T00:00:00Z", parties=[0, 1])) """ - dialog = Dialog( - type="transfer", - start=start, - parties=parties, - transfer=transfer_data, - metadata=metadata - ) - - self.add_dialog(dialog) - + if session is None: + session_dict: Dict[str, Any] = {} + elif isinstance(session, Session): + session_dict = session.to_dict() + else: + session_dict = dict(session) + processed = self._process_properties(session_dict, _ALLOWED_SESSION_PROPERTIES) + self.vcon_dict.setdefault("sessions", []).append(processed) + logger.info("Added session") + return len(self.vcon_dict["sessions"]) - 1 + + def add_event(self, event: Union[Event, Dict[str, Any]]) -> int: + """ + Add an Event Object and return its index in the ``events`` array. + + An ``Event`` is checked against the per-type parameter table when it is + built; a plain dict is checked by ``is_valid()``. + + Example: + >>> vcon = Vcon.build_new() + >>> vcon.add_event(Event(type="join", time="2023-01-01T00:00:00Z", sessions=0, party=0)) + """ + event_dict = event.to_dict() if isinstance(event, Event) else dict(event) + processed = self._process_properties(event_dict, _ALLOWED_EVENT_PROPERTIES) + self.vcon_dict.setdefault("events", []).append(processed) + logger.info(f"Added event of type {processed.get('type')}") + return len(self.vcon_dict["events"]) - 1 + def add_incomplete_dialog( self, start: Union[str, datetime], disposition: str, details: Optional[Dict[str, Any]] = None, parties: List[int] = None, - metadata: Optional[Dict[str, Any]] = None - ) -> None: + metadata: Optional[Dict[str, Any]] = None, + session: Optional[int] = None, + ) -> int: """ Add an incomplete dialog entry to the vCon. + This method creates a dialog entry of type "incomplete" for conversations - that failed to be set up, with the provided disposition and details. + that failed to be set up. Under core-05 an incomplete Dialog has no + content (no body, mediatype, filename, encoding, url or content_hash), and + its ``parties`` is the party that attempted the call, the originator. + ``details`` is kept under ``metadata["details"]``. + Args: start: When the attempt occurred (ISO 8601 string or datetime) - disposition: Reason for the incomplete conversation + disposition: Reason for the incomplete conversation (for example "no-answer") details: Additional details about the failure (optional) - parties: List of party indices involved (optional) + parties: The party (or parties) that attempted the conversation (optional) metadata: Additional metadata (optional) - + session: Optional Session index to add the Dialog to + + Returns: + The index of the new Dialog. + Example: >>> vcon = Vcon.build_new() >>> vcon.add_incomplete_dialog( ... start="2023-01-20T14:00:00Z", - ... disposition="NO_ANSWER", + ... disposition="no-answer", ... details={"ringDuration": 45000}, - ... parties=[0, 1] + ... parties=[0] ... ) """ if parties is None: parties = [] - - dialog_data = { - "disposition": disposition - } - + + meta = dict(metadata) if metadata else {} if details: - dialog_data.update(details) - + meta["details"] = details + dialog = Dialog( type="incomplete", start=start, parties=parties, - body=dialog_data, disposition=disposition, - metadata=metadata + metadata=meta or None, ) - - self.add_dialog(dialog) + + return self.add_dialog(dialog, session=session) def to_json(self) -> str: """ @@ -1552,7 +1772,7 @@ def to_dict(self) -> Dict[str, Any]: Example: >>> vcon = Vcon.build_new() >>> vcon_dict = vcon.to_dict() - >>> print(vcon_dict["vcon"]) # Prints "0.4.0" + >>> print(vcon_dict["vcon"]) # Prints "0.5.0" """ logger.debug("Converting vCon to dictionary") return json.loads(self.to_json()) @@ -1684,12 +1904,26 @@ def updated_at(self): return self.vcon_dict.get("updated_at") @property - def redacted(self): - return self.vcon_dict.get("redacted") + def sessions(self) -> List[Dict[str, Any]]: + """The ``sessions`` array (Session Objects).""" + return self.vcon_dict.get("sessions", []) + + @property + def events(self) -> List[Dict[str, Any]]: + """The ``events`` array (Event Objects).""" + return self.vcon_dict.get("events", []) @property - def amended(self): - return self.vcon_dict.get("amended") + def redacted_from(self): + return self.vcon_dict.get("redacted_from") + + @property + def amended_from(self): + return self.vcon_dict.get("amended_from") + + @property + def redacted_strings(self) -> List[Dict[str, Any]]: + return self.vcon_dict.get("redacted_strings", []) @property def group(self): @@ -1734,7 +1968,7 @@ def uuid8_time(custom_c_62_bits: int) -> str: return uuid_str - def sign(self, private_key: Union[rsa.RSAPrivateKey, bytes]) -> None: + def sign(self, private_key: Union[rsa.RSAPrivateKey, bytes], alg: str = "RS256") -> None: """ Sign the vCon using JWS (JSON Web Signature). @@ -1744,8 +1978,12 @@ def sign(self, private_key: Union[rsa.RSAPrivateKey, bytes]) -> None: Args: private_key: The RSA private key or its PEM representation + alg: JWS algorithm (default "RS256", the value core-05 says SHOULD be + used). "none" is rejected (6.2.2). Raises: + AlgorithmNotPermittedError: If ``alg`` is "none" (any case) or is not + a permitted algorithm. Exception: If there is an error during the signing process Example: @@ -1755,10 +1993,11 @@ def sign(self, private_key: Union[rsa.RSAPrivateKey, bytes]) -> None: >>> vcon.sign(private_key) """ logger.debug("Signing vCon with JWS") + self._check_jws_alg(alg) try: payload = self.to_json() - jws = JsonWebSignature() - protected = {"alg": "RS256", "typ": "JWS"} + jws = JsonWebSignature(algorithms=list(PERMITTED_JWS_ALGORITHMS)) + protected = {"alg": alg, "typ": "JWS"} # Convert private key to PEM format if it's not already if isinstance(private_key, rsa.RSAPrivateKey): @@ -1781,6 +2020,17 @@ def sign(self, private_key: Union[rsa.RSAPrivateKey, bytes]) -> None: logger.error(f"Failed to sign vCon: {str(e)}") raise + @staticmethod + def _check_jws_alg(alg: Any) -> None: + if not isinstance(alg, str) or alg.strip().lower() == "none": + raise AlgorithmNotPermittedError( + 'JWS alg "none" is not permitted (core-05 section 6.2.2)' + ) + if alg not in PERMITTED_JWS_ALGORITHMS: + raise AlgorithmNotPermittedError( + f"JWS alg {alg!r} is not supported; use one of {PERMITTED_JWS_ALGORITHMS}" + ) + def verify(self, public_key: Union[rsa.RSAPublicKey, bytes]) -> bool: """ Verify the JWS signature of the vCon. @@ -1796,6 +2046,9 @@ def verify(self, public_key: Union[rsa.RSAPublicKey, bytes]) -> bool: Raises: ValueError: If the vCon is not signed + AlgorithmNotPermittedError: If the signature declares ``alg`` "none" + (in the protected header or the signature's header), which + core-05 forbids. Verification is refused rather than skipped. Example: >>> private_key, public_key = Vcon.generate_key_pair() @@ -1810,8 +2063,30 @@ def verify(self, public_key: Union[rsa.RSAPublicKey, bytes]) -> bool: logger.error("Cannot verify: vCon is not signed") raise ValueError("vCon is not signed") + # Refuse alg "none" before anything else, from either header location. + sig0 = self.vcon_dict["signatures"][0] + declared = [] try: - jws = JsonWebSignature() + hdr = sig0.get("protected") + if hdr: + declared.append(json.loads(base64.urlsafe_b64decode(hdr + "=" * (-len(hdr) % 4))).get("alg")) + except Exception: + logger.error("Cannot verify: protected header is not valid base64url JSON") + return False + if isinstance(sig0.get("header"), dict) and "alg" in sig0["header"]: + declared.append(sig0["header"]["alg"]) + for declared_alg in declared: + if isinstance(declared_alg, str) and declared_alg.strip().lower() == "none": + logger.error('Refusing to verify: JWS alg "none" is not permitted') + raise AlgorithmNotPermittedError( + 'JWS alg "none" is not permitted (core-05 section 6.2.2)' + ) + if not declared: + logger.error("Cannot verify: no alg in the JWS protected header or header") + return False + + try: + jws = JsonWebSignature(algorithms=list(PERMITTED_JWS_ALGORITHMS)) signed_data = f"{self.vcon_dict['signatures'][0]['protected']}.{self.vcon_dict['payload']}.{self.vcon_dict['signatures'][0]['signature']}" # Convert public key to PEM format if it's not already @@ -1858,156 +2133,38 @@ def generate_key_pair(cls) -> Tuple[rsa.RSAPrivateKey, rsa.RSAPublicKey]: def is_valid(self) -> Tuple[bool, List[str]]: """ - Validate the vCon syntax according to the standard. - Checks required fields, ensures data types are correct, and verifies - relationships between different parts of the vCon (for example, dialog party - references and attachment fields). + Validate the vCon against the core-05 rules. + + Checks required fields and types, that ``vcon`` (if present) is "0.5.0", + that Sessions, Events, Dialogs, attachments and analysis reference + existing objects, the per-event-type parameter table, that at least one + Session exists when there are Dialogs or Events, that attachments have + ``party`` and ``dialog`` or ``session``, that ``redacted_from`` and + ``amended_from`` are exclusive, that ``extensions`` lists every extension + in use (and every ``critical`` entry), and that every + ``__REDACTED_REF_#`` has a ``redacted_strings`` entry. + + SHOULD-level findings are not errors; see :meth:`get_validation_warnings`. Returns: Tuple[bool, List[str]]: A tuple where the first element is True if the vCon is valid and False otherwise, and the second element is a list of error messages. """ logger.debug("Validating vCon") - errors = [] - # Validate required fields. - required_fields = ["uuid", "created_at"] - for field in required_fields: - if field not in self.vcon_dict: - error = f"Missing required field: {field}" - logger.error(error) - errors.append(error) - # Validate created_at format. - if "created_at" in self.vcon_dict: - try: - parser.parse(self.vcon_dict["created_at"]) - except Exception as e: - error = f"Invalid created_at format. Must be an ISO 8601 datetime string: {str(e)}" - logger.error(error) - errors.append(error) - # Validate parties. - if "parties" in self.vcon_dict: - if not isinstance(self.vcon_dict["parties"], list): - error = "Field 'parties' must be a list." - logger.error(error) - errors.append(error) - else: - for i, party in enumerate(self.vcon_dict["parties"]): - if not isinstance(party, dict): - error = f"Party at index {i} must be a dictionary." - logger.error(error) - errors.append(error) - # Validate dialogs. - dialogs = self.vcon_dict.get("dialog", []) - for i, dialog in enumerate(dialogs): - if not isinstance(dialog, dict): - errors.append(f"Dialog at index {i} must be a dictionary.") - continue - - # Validate dialog type if present - if "type" in dialog: - dialog_type = dialog["type"] - if dialog_type not in Dialog.VALID_TYPES: - errors.append(f"Dialog at index {i} has an invalid type: {dialog_type}") - - # Validate specific requirements for each type - if dialog_type == "incomplete": - # For incomplete dialogs, ensure there's a disposition - if "disposition" not in dialog: - errors.append(f"Dialog at index {i} of type 'incomplete' must have a disposition.") - - elif dialog_type == "transfer": - # For transfer dialogs, ensure there's either transfer info or transferor/transferee - has_transfer_field = "transfer" in dialog - has_transferor = "transferor" in dialog - has_transferee = "transferee" in dialog - - if not (has_transfer_field or (has_transferor and has_transferee)): - errors.append(f"Dialog at index {i} of type 'transfer' must have either a transfer field or both transferor and transferee fields.") - - # Validate party references in dialog. - if "parties" in dialog: - if not isinstance(dialog["parties"], list): - errors.append(f"Dialog at index {i} field 'parties' must be a list.") - else: - party_count = len(self.vcon_dict.get("parties", [])) - for party_idx in dialog["parties"]: - if not isinstance(party_idx, int) or party_idx < 0 or party_idx >= party_count: - errors.append(f"Dialog at index {i} references invalid party index: {party_idx}") - # Validate start time format if present. - if "start" in dialog: - try: - parser.parse(dialog["start"]) - except Exception: - errors.append(f"Dialog at index {i} has an invalid 'start' format. Must be an ISO 8601 datetime string.") - - # Validate mediatype for non-transfer/incomplete types - dialog_type = dialog.get("type", "") - if dialog_type not in ["transfer", "incomplete"]: - if ("mediatype" not in dialog or - not isinstance(dialog["mediatype"], str) or - dialog["mediatype"] not in Dialog.MIME_TYPES): - errors.append(f"Dialog at index {i} has an invalid or missing mediatype: {dialog.get('mediatype', 'missing')}") - - # Validate attachments. - if "attachments" in self.vcon_dict: - if not isinstance(self.vcon_dict["attachments"], list): - errors.append("Field 'attachments' must be a list.") - else: - for i, attachment in enumerate(self.vcon_dict["attachments"]): - if not isinstance(attachment, dict): - errors.append(f"Attachment at index {i} must be a dictionary.") - else: - # Check for required attachment fields. - if "purpose" not in attachment: - errors.append(f"Attachment at index {i} is missing required field: purpose") - has_inline = "body" in attachment and "encoding" in attachment - has_external = "url" in attachment and "content_hash" in attachment - if not (has_inline or has_external): - errors.append( - f"Attachment at index {i} must include body+encoding or url+content_hash." - ) - # Validate encoding. - if ("encoding" in attachment and - attachment["encoding"] not in ["json", "none", "base64url"]): - errors.append(f"Attachment at index {i} has invalid encoding: {attachment['encoding']}") - - # Validate analysis. - if "analysis" in self.vcon_dict: - if not isinstance(self.vcon_dict["analysis"], list): - errors.append("Field 'analysis' must be a list.") - else: - for i, analysis in enumerate(self.vcon_dict["analysis"]): - if not isinstance(analysis, dict): - errors.append(f"Analysis at index {i} must be a dictionary.") - else: - # Required analysis fields. - required_analysis_fields = ["type", "dialog", "vendor", "body", "encoding"] - for field in required_analysis_fields: - if field not in analysis: - errors.append(f"Analysis at index {i} is missing required field: {field}") - # Validate encoding. - if ("encoding" in analysis and - analysis["encoding"] not in ["json", "none", "base64url"]): - errors.append(f"Analysis at index {i} has invalid encoding: {analysis['encoding']}") - # Validate dialog references within analysis. - dialog_count = len(dialogs) - if "dialog" in analysis: - if isinstance(analysis["dialog"], list): - for dialog_idx in analysis["dialog"]: - if not isinstance(dialog_idx, int) or dialog_idx < 0 or dialog_idx >= dialog_count: - errors.append(f"Analysis at index {i} references invalid dialog index: {dialog_idx}") - elif isinstance(analysis["dialog"], int): - if analysis["dialog"] < 0 or analysis["dialog"] >= dialog_count: - errors.append(f"Analysis at index {i} references invalid dialog index: {analysis['dialog']}") - else: - errors.append(f"Analysis at index {i} has an invalid 'dialog' reference type.") - + errors, _warnings = validate_vcon_dict(self.vcon_dict, Dialog.MIME_TYPES) + for error in errors: + logger.error(error) if len(errors) == 0: logger.info("vCon validation successful.") else: logger.warning(f"vCon validation failed with {len(errors)} error(s).") return len(errors) == 0, errors + def get_validation_warnings(self) -> List[str]: + """SHOULD-level findings (for example SHOULD NOT parameters on Events).""" + _errors, warnings = validate_vcon_dict(self.vcon_dict, Dialog.MIME_TYPES) + return warnings + @staticmethod def validate_file(file_path: str) -> tuple[bool, list[str]]: """ @@ -2052,6 +2209,8 @@ def load( cls, source: str, property_handling: str = PROPERTY_HANDLING_DEFAULT, + migrate_legacy: bool = True, + strict_migration: bool = False, ) -> "Vcon": """ Load a vCon from either a file path or URL. @@ -2073,11 +2232,15 @@ def load( return cls.load_from_url( source, property_handling=property_handling, + migrate_legacy=migrate_legacy, + strict_migration=strict_migration, ) else: return cls.load_from_file( source, property_handling=property_handling, + migrate_legacy=migrate_legacy, + strict_migration=strict_migration, ) @classmethod @@ -2085,6 +2248,8 @@ def load_from_file( cls, file_path: str, property_handling: str = PROPERTY_HANDLING_DEFAULT, + migrate_legacy: bool = True, + strict_migration: bool = False, ) -> "Vcon": """ Load a vCon from a file. @@ -2107,6 +2272,8 @@ def load_from_file( return cls.build_from_json( json_str, property_handling=property_handling, + migrate_legacy=migrate_legacy, + strict_migration=strict_migration, ) except FileNotFoundError: raise FileNotFoundError(f"vCon file not found: {file_path}") @@ -2118,6 +2285,8 @@ def load_from_url( cls, url: str, property_handling: str = PROPERTY_HANDLING_DEFAULT, + migrate_legacy: bool = True, + strict_migration: bool = False, ) -> "Vcon": """ Load a vCon from a URL. @@ -2139,6 +2308,8 @@ def load_from_url( return cls.build_from_json( response.text, property_handling=property_handling, + migrate_legacy=migrate_legacy, + strict_migration=strict_migration, ) def save_to_file(self, file_path: str) -> None: diff --git a/tests/schema/SOURCE.md b/tests/schema/SOURCE.md index 2bec2ba..1c2ab5d 100644 --- a/tests/schema/SOURCE.md +++ b/tests/schema/SOURCE.md @@ -1,16 +1,20 @@ # Source `vcon_json_schema.json` is vendored (not generated) from the vCon working -group's reference schema, kept here so `tests/test_schema_compliance.py` can -validate library output offline and reproducibly. +group's draft, kept here so `tests/test_schema_compliance.py` and +`tests/test_core05_examples.py` can validate library output offline and +reproducibly. -- Repository: https://github.com/vcon-dev/vcon-adapter-template -- Path: `tests/schema/vcon_json_schema.json` -- Commit: `43c587121431b27b561002730e0fd5971d6c47ca` -- Commit date: 2026-09-25 16:59:22 -0400 -- Fetched: 2026-09-26, via `raw.githubusercontent.com/vcon-dev/vcon-adapter-template/main/tests/schema/vcon_json_schema.json` +- Document: `draft-ietf-vcon-vcon-core-05`, Appendix C (JSON Schema, draft-07), + syntax `0.5.0`. It is the unfolded `vcon_json_schema.json` of the draft's + repository at tag `draft-ietf-vcon-vcon-core-05`; the draft prints the same + bytes folded at 65 columns. +- The previous copy (core-04, `const` "0.4.0") was replaced; it remains in + git history. -This matches the appendix schema in `draft-ietf-vcon-vcon-core-04` (the -schema's own `$id`/`description` say "unsigned form of vCon ... as defined -in RFCXXXX"). Re-vendor by re-running the fetch above and diffing against -this copy if the draft or the adapter-template's schema changes. +`examples/B1-...B9-*.json` are the Appendix B examples of the same draft, +unfolded from the repository's `.vcon` files. B6 is the signed (JWS) form and +B7 the encrypted (JWE) form; the schema describes the unsigned form only. + +This schema is permissive: parameters and type values the draft does not define +do not fail validation. Re-vendor from the draft tag if the draft changes. diff --git a/tests/schema/examples/B1-two-party-call-inline-recording.json b/tests/schema/examples/B1-two-party-call-inline-recording.json new file mode 100644 index 0000000..834871c --- /dev/null +++ b/tests/schema/examples/B1-two-party-call-inline-recording.json @@ -0,0 +1,71 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 4.72, + "parties": [ + 0, + 1 + ], + "mediatype": "audio/x-wav", + "filename": "ab_call.wav", + "encoding": "base64url", + "body": "UklGRioeAABXQVZFZm10IBQAAAAxAAEAQB8AAFkGAABBAAAAAgBAAWZhY3QEAAAAgJMAAGRhdGH2HQAAoxjXHYXCRekuye4gK4Tsiv4wZeNhtuvu3RMkgyPXme4NeahQLG0yeLayx5HCIiRWK7psbQrQTFm57NwQJvIbq1aNxk6VpMYAXSm5Bb1rgStIStvEzmCaOIabxs2gjReJ02Rk0BQtOxHkhUTIZd4VGKoq1KuoCGhrZTx1vRZICuZEcgkGjdH2jiCU1a0NMW6BE8lVHN-OYFPHcZspr0CSl1aeo2hOWUx3CbovpGqKsApWteunk8gMPMOdynRVFWR5o0l2BvaQDcWugGRHrQa9NcEbG1LWQq_AWLpsXKdMQefGrZu4ZE2ZSDIRGJLTKpIzDybqSyZishQmjuVGztMKNlcyt2vW546JsutgllyppQWroAtHbkyrrGAx3bIiX81g1sR-oVaBbtkobA08fpJYscQSlHHcGm7hDriuWTRm8A6GKQ1Fbcn10M30DcHctnEchwaAI7dxI2knYCQ5biNHB2Djxm3bFmyU5TA3ALZt3DaSeABIkiRJcm0AxpEkSZI7AEiSJEmSwUYZ1mQLYNu2bdumPWDbtm3b9gOAJEmSJFkFgCRJkiQZbHRhTccDtm3btm0qAEaOJEmSPABIkiRJkjAASJIk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cF0kyAqGNkw5KuoOyG3XXJbpCMxxZzuZ9A7IjBzXzRQHk4Xi66Ciak0sa9ZAk7uQJJmtIBrDQhIZDCCisukrYW2QWUj1CrhUGrmp9grYb-oYUuwMOGlkzJLUCMht7lzQHpubADSzYJ1ftv4KrIGVNW4YtUphGyv65IpeYkaXigzfwRxbJK4eULOsuofVTeKhI0V7rVx6syVN58RFipMWLcXb7HWa0ool1tVSbRerw1U13_R970Yst2rTUDSHiqJEkdDB3u8tLXXEZRi3iLuKOJJsq89gTZ4TTUs9wXJSZIUvXR-7sZUYe8uDt1KkJhPJMc6uUfVsadMGMupEzmqFtXHdstEeH4X3qL6u60iO3kZOOfwyo_KeppGj8RXzk2zV00dWW80n0QTMxLbTfSB8jmdFp02aKlNlK1l97XheSYTXkOLGwR4faduDnqHCOE2_ZLbx6rq35oJe0p26lepuXOWTt7Ie_DmLNi4IDSZom4YzSEtD47tmVUra4GERBpUJACE0Uua5njuKvpK2ddy599W22r4k_U2rbBguUz2dY6tWrvTZuZr9sdZE7-olvZu1lUrIGj9QIfauaCtaeXRZr4kfW5Hlxb0fr3U2lWqt6sOSaYEyZJEIdkWdSu89fZvqdnrVNRmum_xp2jTnh2ISAYJiKwN0oNFtnSyD5Eiyw3dPBAY5diql0b9ecXVDBo2Rs63nWNr6tfuyXTmu8nIabShdNojSNGobq52IxMKBgybmG60GIeX0pUNWh0AA9KxbRYyBJnluZH2Jc4hI2iigbuXGkTgINqqeKLVUDKTR2dQt6gpWMhzXTRd4B2BULCDiSHXDgy8AnTuMqiROgCsJsYs4tGAjt1WcVdE2SATnCLSKbNhtyAJQciPHaL0Eyo0bWcX0DiZu29hwFntXxIIy4KuVckrtDCD4tGYSHctAFDmNzVbPQCvDauJGqTgafrcINDGcNGnZR7Zt3PoALxSCUqY0wbyrSHmTIZc" + } + ], + "analysis": [], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 4.72, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01a16b86-9a63-8346-b9a2-279e0d16bc46", + "events": [ + { + "type": "join", + "time": "2022-06-21T17:53:26.000+00:00", + "sessions": 0, + "party": 0 + }, + { + "type": "join", + "time": "2022-06-21T17:53:26.000+00:00", + "sessions": 0, + "party": 1 + }, + { + "type": "drop", + "time": "2022-06-21T17:53:30.720+00:00", + "sessions": 0, + "party": 0 + }, + { + "type": "drop", + "time": "2022-06-21T17:53:30.720+00:00", + "sessions": 0, + "party": 1 + } + ] +} diff --git a/tests/schema/examples/B2-email-thread-multipart.json b/tests/schema/examples/B2-email-thread-multipart.json new file mode 100644 index 0000000..fc6710d --- /dev/null +++ b/tests/schema/examples/B2-email-thread-multipart.json @@ -0,0 +1,58 @@ +{ + "vcon": "0.5.0", + "parties": [ + { + "mailto": "b@example.com", + "name": "Bob" + }, + { + "mailto": "a@example.com", + "name": "Alice" + } + ], + "dialog": [ + { + "type": "text", + "start": "2022-09-23T21:44:25.000+00:00", + "duration": 0, + "parties": [ + 0 + ], + "mediatype": "multipart/mixed; boundary=\"----=_Part_388314_1108189513.1663969465698\"", + "encoding": "none", + "body": "------=_Part_388314_1108189513.1663969465698\r\nContent-Type: multipart/alternative;\r\n\tboundary=\"----=_Part_388313_805631480.1663969465697\"\r\n\r\n------=_Part_388313_805631480.1663969465697\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\nAlice:Please find the image attached.\r\n\r\nRegards,Bob\r\n\r\n------=_Part_388313_805631480.1663969465697\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n
Alice:
Please find the image attached.

Regards,
Bob

\r\n------=_Part_388313_805631480.1663969465697--\r\n\r\n------=_Part_388314_1108189513.1663969465698\r\nContent-Type: image/png\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"=?UTF-8?b?c2NyZWVuc2hvdC5wbmc=?=\"\r\nContent-ID: \r\n\r\niVBORw0KGgoAAAANSUhEUgAAACYAAAAeCAIAAADPdvs5AAAAA3NCSVQICAjb4U/gAAAAGXRFWHRT\r\nb2Z0d2FyZQBnbm9tZS1zY3JlZW5zaG907wO/PgAAALpJREFUSInl1t0NgzAMBOC7qPvP1gW6Qjdo\r\nj4f0J4qAJI6NROvniE8+mwCvtzv6imTnyf1K/UclHUFWjIvaIL3CHCABSPKKtJckWfY6zw+sj5dq\r\nISdVIzmj2klzTZG2Rme7NKgOwY6qPrMcUs+2PqchL14P+oyz+fHx77K5Sv8xyxAyZ0uBaxn/SpcU\r\n8NxcosAut1Y3NtjVX7UjZlmpgWTSFyvVQPKB16tSqW53bFnKtyyZvYT3rSsAWADWAlOjseYFfwAA\r\nAABJRU5ErkJggg==\r\n\r\n------=_Part_388314_1108189513.1663969465698--\r\n", + "message_id": "<1126698042.388315.1663969465698@mail.yahoo.com>" + }, + { + "type": "text", + "start": "2022-09-23T21:44:59.000+00:00", + "duration": 0, + "parties": [ + 1 + ], + "mediatype": "multipart/alternative; boundary=\"----=_Part_390234_811845464.1663969499935\"", + "encoding": "none", + "body": "------=_Part_390234_811845464.1663969499935\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n Hi Bob:Got it. Thanks.\r\n\r\n On Friday, September 23, 2022, 9:44:40 PM UTC, Bob wrote: \r\n \r\n Alice:Please find the image attached.\r\n\r\nRegards,Bob\r\n \r\n------=_Part_390234_811845464.1663969499935\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n
\r\n
Hi Bob:
Got it. Thanks.


\r\n \r\n
\r\n
\r\n \r\n
\r\n On Friday, September 23, 2022, 9:44:40 PM UTC, Bob <b@example.com> wrote:\r\n
\r\n

\r\n

\r\n
Alice:
Please find the image attached.

Regards,
Bob

\r\n
\r\n
\r\n------=_Part_390234_811845464.1663969499935--\r\n", + "message_id": "<2031327240.390235.1663969499936@mail.yahoo.com>" + } + ], + "analysis": [], + "attachments": [], + "created_at": "2026-10-24T01:29:10.590+00:00", + "subject": "Account problem", + "sessions": [ + { + "start": "2022-09-23T21:44:25.000+00:00", + "duration": 34, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0, + 1 + ] + } + ], + "uuid": "01a16b86-acc8-8c6d-b9a2-279e0d16bc46" +} diff --git a/tests/schema/examples/B3-email-thread-text.json b/tests/schema/examples/B3-email-thread-text.json new file mode 100644 index 0000000..d30ecab --- /dev/null +++ b/tests/schema/examples/B3-email-thread-text.json @@ -0,0 +1,71 @@ +{ + "vcon": "0.5.0", + "parties": [ + { + "mailto": "a@example.com", + "name": "Alice" + }, + { + "mailto": "b@example.com", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "text", + "start": "2022-09-23T23:24:59.000+00:00", + "duration": 0, + "parties": [ + 0 + ], + "mediatype": "text/plain", + "encoding": "none", + "body": "Hi Bob:\nI just wanted to follow up to see that your account is ok now.\n\nRegards,\nAlice\n\n", + "message_id": "<1402576211.401234.1663975499936@mail.yahoo.com>" + }, + { + "type": "text", + "start": "2022-09-23T23:34:32.000+00:00", + "duration": 0, + "parties": [ + 1 + ], + "mediatype": "text/plain; charset=UTF-8", + "encoding": "none", + "body": "Hi Alice:\nAll is fine. Thanks.\n\n On Friday, September 23, 2022, 23:24:59 PM UTC, Alice wrote: \n \n Hi Bob:\n I just wanted to follow up to see that your account is ok now.\n \n Regards,\n Alice\n", + "message_id": "<1879233410.402112.1663976072118@mail.yahoo.com>" + }, + { + "type": "text", + "start": "2022-09-23T23:38:12.000+00:00", + "duration": 0, + "parties": [ + 0 + ], + "mediatype": "text/plain", + "encoding": "none", + "body": "Awesome!\n\n On Friday, September 23, 2022, 23:34: PM UTC, Bob wrote: \n\n Hi Alice:\n All is fine. Thanks.\n \n On Friday, September 23, 2022, 23:24:59 PM UTC, Alice wrote: \n \n Hi Bob:\n I just wanted to follow up to see that your account is ok now.\n \n Regards,\n Alice\n", + "message_id": "<1535873320.402417.1663976292034@mail.yahoo.com>" + } + ], + "analysis": [], + "attachments": [], + "created_at": "2026-10-24T01:29:12.007+00:00", + "subject": "Account issue followup", + "sessions": [ + { + "start": "2022-09-23T23:24:59.000+00:00", + "duration": 793, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0, + 1, + 2 + ] + } + ], + "uuid": "01a16b86-b24d-8057-b9a2-279e0d16bc46" +} diff --git a/tests/schema/examples/B4-two-party-call-external-recording.json b/tests/schema/examples/B4-two-party-call-external-recording.json new file mode 100644 index 0000000..f87d55b --- /dev/null +++ b/tests/schema/examples/B4-two-party-call-external-recording.json @@ -0,0 +1,45 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "url": "https://github.com/ietf-wg-vcon/draft-ietf-vcon-vcon-core/raw/refs/heads/main/examples/ab_call_2ch.ogg", + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + } + ], + "analysis": [], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" +} diff --git a/tests/schema/examples/B5-two-party-call-with-analysis.json b/tests/schema/examples/B5-two-party-call-with-analysis.json new file mode 100644 index 0000000..f0ef040 --- /dev/null +++ b/tests/schema/examples/B5-two-party-call-with-analysis.json @@ -0,0 +1,1075 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "url": "https://github.com/ietf-wg-vcon/draft-ietf-vcon-vcon-core/raw/refs/heads/main/examples/ab_call_2ch.ogg", + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + } + ], + "analysis": [ + { + "type": "transcript", + "dialog": 0, + "body": { + "metadata": { + "transaction_key": "deprecated", + "request_id": "01a16b9c-30a8-7941-9b74-a9c73124938a", + "sha256": "460145629244a6c72d4f0b94707ec3ca4e92da1ae11fe1d04a3fc88143795c63", + "created": "2026-10-24T01:52:40.996Z", + "duration": 32.925938, + "channels": 2, + "models": [ + "2187e11a-3532-4498-b076-81fa530bdd49" + ], + "model_info": { + "2187e11a-3532-4498-b076-81fa530bdd49": { + "name": "general-nova-3", + "version": "2025-07-31.0", + "arch": "nova-3" + } + }, + "diarize_info": { + "model_uuid": "a9f85c2b-5afb-4b9d-b49b-492c43a01cfb", + "arch": "v1" + } + }, + "results": { + "channels": [ + { + "alternatives": [ + { + "transcript": "Hi. I'd like to add Foo to my service. My name is Alice and my number is 1234567890. No. Thank you. Goodbye.", + "confidence": 0.99609375, + "words": [ + { + "word": "hi", + "start": 5.52, + "end": 6.16, + "confidence": 0.8781738, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "Hi." + }, + { + "word": "i'd", + "start": 6.24, + "end": 6.56, + "confidence": 0.9951172, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "I'd" + }, + { + "word": "like", + "start": 6.56, + "end": 6.72, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "like" + }, + { + "word": "to", + "start": 6.72, + "end": 6.7999997, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "to" + }, + { + "word": "add", + "start": 6.7999997, + "end": 7.12, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "add" + }, + { + "word": "foo", + "start": 7.12, + "end": 7.52, + "confidence": 0.6496582, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "Foo" + }, + { + "word": "to", + "start": 7.52, + "end": 7.8399997, + "confidence": 0.9902344, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "to" + }, + { + "word": "my", + "start": 7.8399997, + "end": 8, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "my" + }, + { + "word": "service", + "start": 8, + "end": 8.4, + "confidence": 0.99560547, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "service." + }, + { + "word": "my", + "start": 13.695001, + "end": 13.935, + "confidence": 0.99609375, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "My" + }, + { + "word": "name", + "start": 13.935, + "end": 14.175, + "confidence": 0.9980469, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "name" + }, + { + "word": "is", + "start": 14.175, + "end": 14.255, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "is" + }, + { + "word": "alice", + "start": 14.255, + "end": 14.815001, + "confidence": 0.9902344, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "Alice" + }, + { + "word": "and", + "start": 14.815001, + "end": 15.215, + "confidence": 0.7080078, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "and" + }, + { + "word": "my", + "start": 15.215, + "end": 15.455, + "confidence": 0.99609375, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "my" + }, + { + "word": "number", + "start": 15.455, + "end": 15.695, + "confidence": 0.9970703, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "number" + }, + { + "word": "is", + "start": 15.695, + "end": 16.335, + "confidence": 0.9970703, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "is" + }, + { + "word": "1234567890", + "start": 16.335, + "end": 20.255001, + "confidence": 0.9845703, + "speaker": 0, + "speaker_confidence": 0.98775685, + "punctuated_word": "1234567890." + }, + { + "word": "no", + "start": 27.820936, + "end": 28.380938, + "confidence": 0.8015137, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "No." + }, + { + "word": "thank", + "start": 28.380938, + "end": 28.700937, + "confidence": 0.9941406, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "Thank" + }, + { + "word": "you", + "start": 28.700937, + "end": 29.180937, + "confidence": 0.98657227, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "you." + }, + { + "word": "goodbye", + "start": 29.180937, + "end": 29.500937, + "confidence": 0.85009766, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "Goodbye." + } + ], + "paragraphs": { + "transcript": "\nSpeaker 0: Hi. I'd like to add Foo to my service. My name is Alice and my number is 1234567890. No. Thank you.\n\nGoodbye.", + "paragraphs": [ + { + "sentences": [ + { + "text": "Hi.", + "start": 5.52, + "end": 6.16 + }, + { + "text": "I'd like to add Foo to my service.", + "start": 6.24, + "end": 8.4 + }, + { + "text": "My name is Alice and my number is 1234567890.", + "start": 13.695001, + "end": 20.255001 + }, + { + "text": "No.", + "start": 27.820936, + "end": 28.380938 + }, + { + "text": "Thank you.", + "start": 28.380938, + "end": 29.180937 + } + ], + "speaker": 0, + "num_words": 21, + "start": 5.52, + "end": 29.180937 + }, + { + "sentences": [ + { + "text": "Goodbye.", + "start": 29.180937, + "end": 29.500937 + } + ], + "speaker": 0, + "num_words": 1, + "start": 29.180937, + "end": 29.500937 + } + ] + } + } + ] + }, + { + "alternatives": [ + { + "transcript": "Hello. This is example.com. My name is Bob. How can I help you? Okay. Can you give me your name and phone number so I can look up your account? Thank you. Okay. I've added food to your service. Is there anything else I can help you with? Goodbye. Have a nice day.", + "confidence": 1, + "words": [ + { + "word": "hello", + "start": 1.12, + "end": 1.68, + "confidence": 0.9790039, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "Hello." + }, + { + "word": "this", + "start": 1.68, + "end": 2.08, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "This" + }, + { + "word": "is", + "start": 2.08, + "end": 2.24, + "confidence": 0.9951172, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "is" + }, + { + "word": "example.com", + "start": 2.24, + "end": 3.28, + "confidence": 0.939209, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "example.com." + }, + { + "word": "my", + "start": 3.28, + "end": 3.4399998, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "My" + }, + { + "word": "name", + "start": 3.4399998, + "end": 3.6, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "name" + }, + { + "word": "is", + "start": 3.6, + "end": 3.6799998, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "is" + }, + { + "word": "bob", + "start": 3.6799998, + "end": 4.16, + "confidence": 0.99853516, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "Bob." + }, + { + "word": "how", + "start": 4.16, + "end": 4.4, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "How" + }, + { + "word": "can", + "start": 4.4, + "end": 4.56, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "can" + }, + { + "word": "i", + "start": 4.56, + "end": 4.64, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "I" + }, + { + "word": "help", + "start": 4.64, + "end": 4.88, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "help" + }, + { + "word": "you", + "start": 4.88, + "end": 5.36, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "you?" + }, + { + "word": "okay", + "start": 9.04, + "end": 9.759999, + "confidence": 0.99853516, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "Okay." + }, + { + "word": "can", + "start": 10.08, + "end": 10.32, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "Can" + }, + { + "word": "you", + "start": 10.32, + "end": 10.4, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "you" + }, + { + "word": "give", + "start": 10.4, + "end": 10.559999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "give" + }, + { + "word": "me", + "start": 10.559999, + "end": 10.719999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "me" + }, + { + "word": "your", + "start": 10.719999, + "end": 10.88, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "your" + }, + { + "word": "name", + "start": 10.88, + "end": 11.12, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "name" + }, + { + "word": "and", + "start": 11.12, + "end": 11.28, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "and" + }, + { + "word": "phone", + "start": 11.28, + "end": 11.5199995, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "phone" + }, + { + "word": "number", + "start": 11.5199995, + "end": 11.679999, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "number" + }, + { + "word": "so", + "start": 11.679999, + "end": 11.92, + "confidence": 0.9350586, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "so" + }, + { + "word": "i", + "start": 11.92, + "end": 12.08, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "I" + }, + { + "word": "can", + "start": 12.08, + "end": 12.16, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "can" + }, + { + "word": "look", + "start": 12.16, + "end": 12.32, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "look" + }, + { + "word": "up", + "start": 12.32, + "end": 12.48, + "confidence": 0.9921875, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "up" + }, + { + "word": "your", + "start": 12.48, + "end": 12.639999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "your" + }, + { + "word": "account", + "start": 12.639999, + "end": 13.04, + "confidence": 0.9980469, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "account?" + }, + { + "word": "thank", + "start": 20.635, + "end": 20.955, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "Thank" + }, + { + "word": "you", + "start": 20.955, + "end": 21.435, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "you." + }, + { + "word": "okay", + "start": 22.795, + "end": 23.515, + "confidence": 0.9995117, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "Okay." + }, + { + "word": "i've", + "start": 23.994999, + "end": 24.395, + "confidence": 0.99853516, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "I've" + }, + { + "word": "added", + "start": 24.395, + "end": 24.715, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "added" + }, + { + "word": "food", + "start": 24.715, + "end": 24.955, + "confidence": 0.9580078, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "food" + }, + { + "word": "to", + "start": 24.955, + "end": 25.115, + "confidence": 0.96435547, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "to" + }, + { + "word": "your", + "start": 25.115, + "end": 25.275, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "your" + }, + { + "word": "service", + "start": 25.275, + "end": 25.595001, + "confidence": 0.99560547, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "service." + }, + { + "word": "is", + "start": 25.595001, + "end": 25.755001, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "Is" + }, + { + "word": "there", + "start": 25.755001, + "end": 25.915, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "there" + }, + { + "word": "anything", + "start": 25.915, + "end": 26.154999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "anything" + }, + { + "word": "else", + "start": 26.154999, + "end": 26.395, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "else" + }, + { + "word": "i", + "start": 26.395, + "end": 26.635, + "confidence": 0.97314453, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "I" + }, + { + "word": "can", + "start": 26.635, + "end": 26.795, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "can" + }, + { + "word": "help", + "start": 26.795, + "end": 26.955, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "help" + }, + { + "word": "you", + "start": 26.955, + "end": 27.035, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "you" + }, + { + "word": "with", + "start": 27.035, + "end": 27.275, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "with?" + }, + { + "word": "goodbye", + "start": 30.320875, + "end": 30.960875, + "confidence": 0.99121094, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "Goodbye." + }, + { + "word": "have", + "start": 30.960875, + "end": 31.200874, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "Have" + }, + { + "word": "a", + "start": 31.200874, + "end": 31.360876, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "a" + }, + { + "word": "nice", + "start": 31.360876, + "end": 31.520876, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "nice" + }, + { + "word": "day", + "start": 31.520876, + "end": 31.760876, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0, + "punctuated_word": "day." + } + ], + "paragraphs": { + "transcript": "\nSpeaker 0: Hello. This is example.com. My name is Bob. How can I help you? Okay.\n\nCan you give me your name and phone number so I can look up your account? Thank you. Okay. I've added food to your service. Is there anything else I can help you with?\n\nGoodbye. Have a nice day.", + "paragraphs": [ + { + "sentences": [ + { + "text": "Hello.", + "start": 1.12, + "end": 1.68 + }, + { + "text": "This is example.com.", + "start": 1.68, + "end": 3.28 + }, + { + "text": "My name is Bob.", + "start": 3.28, + "end": 4.16 + }, + { + "text": "How can I help you?", + "start": 4.16, + "end": 5.36 + }, + { + "text": "Okay.", + "start": 9.04, + "end": 9.759999 + } + ], + "speaker": 0, + "num_words": 14, + "start": 1.12, + "end": 9.759999 + }, + { + "sentences": [ + { + "text": "Can you give me your name and phone number so I can look up your account?", + "start": 10.08, + "end": 13.04 + }, + { + "text": "Thank you.", + "start": 20.635, + "end": 21.435 + }, + { + "text": "Okay.", + "start": 22.795, + "end": 23.515 + }, + { + "text": "I've added food to your service.", + "start": 23.994999, + "end": 25.595001 + }, + { + "text": "Is there anything else I can help you with?", + "start": 25.595001, + "end": 27.275 + } + ], + "speaker": 0, + "num_words": 34, + "start": 10.08, + "end": 27.275 + }, + { + "sentences": [ + { + "text": "Goodbye.", + "start": 30.320875, + "end": 30.960875 + }, + { + "text": "Have a nice day.", + "start": 30.960875, + "end": 31.760876 + } + ], + "speaker": 0, + "num_words": 5, + "start": 30.320875, + "end": 31.760876 + } + ] + } + } + ] + } + ], + "paragraphs": { + "transcript": "\nChannel 1: Speaker 0: Hello. This is example.com. My name is Bob. How can I help you?\n\nChannel 0: Hi. I'd like to add Foo to my service.\n\nChannel 1: Okay. Can you give me your name and phone number so I can look up your account?\n\nChannel 0: My name is Alice and my number is 1234567890.\n\nChannel 1: Thank you. Okay. I've added food to your service. Is there anything else I can help you with?\n\nChannel 0: No. Thank you. Goodbye.\n\nChannel 1: Goodbye. Have a nice day.", + "paragraphs": [ + { + "sentences": [ + { + "text": "Hello.", + "start": 1.12, + "end": 1.68 + }, + { + "text": "This is example.com.", + "start": 1.68, + "end": 3.28 + }, + { + "text": "My name is Bob.", + "start": 3.28, + "end": 4.16 + }, + { + "text": "How can I help you?", + "start": 4.16, + "end": 5.36 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 13, + "start": 1.12, + "end": 5.36 + }, + { + "sentences": [ + { + "text": "Hi.", + "start": 5.52, + "end": 6.16 + }, + { + "text": "I'd like to add Foo to my service.", + "start": 6.24, + "end": 8.4 + } + ], + "speaker": 0, + "channel": 0, + "num_words": 9, + "start": 5.52, + "end": 8.4 + }, + { + "sentences": [ + { + "text": "Okay.", + "start": 9.04, + "end": 9.759999 + }, + { + "text": "Can you give me your name and phone number so I can look up your account?", + "start": 10.08, + "end": 13.04 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 17, + "start": 9.04, + "end": 13.04 + }, + { + "sentences": [ + { + "text": "My name is Alice and my number is 1234567890.", + "start": 13.695001, + "end": 20.255001 + } + ], + "speaker": 0, + "channel": 0, + "num_words": 9, + "start": 13.695001, + "end": 20.255001 + }, + { + "sentences": [ + { + "text": "Thank you.", + "start": 20.635, + "end": 21.435 + }, + { + "text": "Okay.", + "start": 22.795, + "end": 23.515 + }, + { + "text": "I've added food to your service.", + "start": 23.994999, + "end": 25.595001 + }, + { + "text": "Is there anything else I can help you with?", + "start": 25.595001, + "end": 27.275 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 18, + "start": 20.635, + "end": 27.275 + }, + { + "sentences": [ + { + "text": "No.", + "start": 27.820936, + "end": 28.380938 + }, + { + "text": "Thank you.", + "start": 28.380938, + "end": 29.180937 + }, + { + "text": "Goodbye.", + "start": 29.180937, + "end": 29.500937 + } + ], + "speaker": 0, + "channel": 0, + "num_words": 4, + "start": 27.820936, + "end": 29.500937 + }, + { + "sentences": [ + { + "text": "Goodbye.", + "start": 30.320875, + "end": 30.960875 + }, + { + "text": "Have a nice day.", + "start": 30.960875, + "end": 31.760876 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 5, + "start": 30.320875, + "end": 31.760876 + } + ] + } + } + }, + "encoding": "json", + "vendor": "deepgram", + "schema": "deepgram_prerecorded", + "product": "transcription" + } + ], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" +} diff --git a/tests/schema/examples/B6-signed.json b/tests/schema/examples/B6-signed.json new file mode 100644 index 0000000..43c5df8 --- /dev/null +++ b/tests/schema/examples/B6-signed.json @@ -0,0 +1,17 @@ +{ + "payload": "eyJ2Y29uIjoiMC41LjAiLCJjcmVhdGVkX2F0IjoiMjAyMi0wNi0yMVQxMzo1MzowMC0wNDowMCIsInBhcnRpZXMiOlt7InRlbCI6IisxMjM0NTY3ODkwMSIsIm5hbWUiOiJBbGljZSJ9LHsidGVsIjoiKzE5ODc2NTQzMjEwIiwibmFtZSI6IkJvYiJ9XSwiZGlhbG9nIjpbeyJ0eXBlIjoicmVjb3JkaW5nIiwic3RhcnQiOiIyMDIyLTA2LTIxVDE3OjUzOjI2LjAwMCswMDowMCIsImR1cmF0aW9uIjozMi45MzIzOTYsInBhcnRpZXMiOlswLDFdLCJ1cmwiOiJodHRwczovL2dpdGh1Yi5jb20vaWV0Zi13Zy12Y29uL2RyYWZ0LWlldGYtdmNvbi12Y29uLWNvcmUvcmF3L3JlZnMvaGVhZHMvbWFpbi9leGFtcGxlcy9hYl9jYWxsXzJjaC5vZ2ciLCJtZWRpYXR5cGUiOiJhdWRpby9vZ2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XtvIj8pZwyE4FNuaiJwojkQxDfjqk67Qs5NUQsFcaIwMes8It74ASHm8DUKEhDT2ASgMtUDwKWrOBefrSPqjY7+EMh2yVZnQhMwpx4s7CH0za32Yq+KC8GotHdI6jisDEom7aHglg==" + ], + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" + }, + "signature": "HJA8mITP_gPp5FjIA2qw982rnUP44vDSeJRYGNXCxZhWm1c5dGRTlpbssDFBweCE_eOHpi8O2GhIulx9XBod3NgColJu2FDBC6mmk75ke37A2AmSBuIl6AhQpEkfs6FRunG9OQ3I-r6dok9WHYI7JmgqcZY-2GHvzCIMW3LgaJZ1Vdt7TK3vqMR_Nn8Cpo3jkodtwMAuXivUtHWz4oldkSczuVqUMKtawLIU0GvPMfShR1C7ayuWgXkg7f1yiU9cKNtQM-biEyvIfGe_3tSPl6G09IToJRo-17Ji1qmm1eTaMwudG4hWvFmlvWnQCq-QRFi30gfBYVEYyrAJj7p_Bg", + "protected": "eyJhbGciOiJSUzI1NiJ9" + } + ] +} diff --git a/tests/schema/examples/B7-encrypted.json b/tests/schema/examples/B7-encrypted.json new file mode 100644 index 0000000..179938e --- /dev/null +++ b/tests/schema/examples/B7-encrypted.json @@ -0,0 +1,15 @@ +{ + "protected": "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZDQkMtSFM1MTIifQ", + "iv": "2LXY42Qg-9NPezg9KrThkQ", + "ciphertext": "tntDlZelgX_ECWMNDZ_gV14bCDhEPlBJS84xDDN_7P2jpyi0EzWZWIQyhomCGVI-doUnVEbWRi3dfkF3t_uOOZIZ4F5-2ebiE94E6_JgJKHj0ow92cO_l5jGcnt_U8nNWJU2m1gm0E_TyAkbGvoGWeBcvfunof5YbnQFVC0WZ9Jns-JnY3mEKF18Z_ZKUyDrd9Q-b_MDDfrgfnVbCToGAupX7t26cgTFcEBudRXxeDbe-YJ2BaIN5GEPXT2Jeu4Aamq82hIdog8woW_QPpWGr6R44TjKLxz7n0ABny2m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m2Jp1R8fk0G08SZ78SGRexkOhnpDAPFX1kOpVMWzS1ZYmYVTkZxjtv3Sm7YABnhvDhxdxHZFR_n83EYVSjIfenJOPnJ7M_hyWh2eStg2n-V6dpqc_PC9cHB-bGYey_Lnx4kDOiGeqjvg5yo_qYK0PYn-pr59Su0q0qZkp_3g80vQ" + } + ], + "unprotected": { + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", + "cty": "application/vcon" + } +} diff --git a/tests/schema/examples/B8-redacted.json b/tests/schema/examples/B8-redacted.json new file mode 100644 index 0000000..043b84d --- /dev/null +++ b/tests/schema/examples/B8-redacted.json @@ -0,0 +1,165 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "name": "Alice" + }, + { + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + } + ], + "analysis": [ + { + "type": "transcript-redacted", + "dialog": 0, + "body": [ + { + "parties": 0, + "start": "2022-06-21T17:53:31.520000+00:00", + "duration": 0.6400000000000006, + "text": "Hi." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:32.240000+00:00", + "duration": 2.16, + "text": "I'd like to add Foo to my service." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:39.695001+00:00", + "duration": 6.5600000000000005, + "text": "My name is Alice and my number is {{BAN}}." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:53.820936+00:00", + "duration": 0.5600020000000008, + "text": "No." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:54.380938+00:00", + "duration": 0.7999989999999997, + "text": "Thank you." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:55.180937+00:00", + "duration": 0.3200000000000003, + "text": "Goodbye." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:27.120000+00:00", + "duration": 0.5599999999999998, + "text": "Hello." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:27.680000+00:00", + "duration": 1.5999999999999999, + "text": "This is {{URL}}." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:29.280000+00:00", + "duration": 0.8800000000000003, + "text": "My name is Bob." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:30.160000+00:00", + "duration": 1.2000000000000002, + "text": "How can I help you?" + }, + { + "parties": 1, + "start": "2022-06-21T17:53:35.040000+00:00", + "duration": 0.7199990000000014, + "text": "{{US_STATE}}." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:36.080000+00:00", + "duration": 2.959999999999999, + "text": "Can you give me your name and phone number so I can look up your account?" + }, + { + "parties": 1, + "start": "2022-06-21T17:53:46.635000+00:00", + "duration": 0.7999999999999972, + "text": "Thank you." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:48.795000+00:00", + "duration": 0.7199999999999989, + "text": "{{US_STATE}}." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:49.994999+00:00", + "duration": 1.600002, + "text": "I've added food to your service." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:51.595001+00:00", + "duration": 1.6799989999999987, + "text": "Is there anything else I can help you with?" + }, + { + "parties": 1, + "start": "2022-06-21T17:53:56.320875+00:00", + "duration": 0.6400000000000006, + "text": "Goodbye." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:56.960875+00:00", + "duration": 0.8000009999999982, + "text": "Have a nice day." + } + ], + "encoding": "json", + "vendor": "CapitalOne", + "schema": "data_labeler_schema", + "product": "dataprofiler" + } + ], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01928e10-193e-8231-b9a2-279e0d16bc46", + "redacted_from": { + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", + "type": "PII Redaction" + } +} diff --git a/tests/schema/examples/B9-amended-signed.json b/tests/schema/examples/B9-amended-signed.json new file mode 100644 index 0000000..a48a977 --- /dev/null +++ b/tests/schema/examples/B9-amended-signed.json @@ -0,0 +1,59 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "url": "https://github.com/ietf-wg-vcon/draft-ietf-vcon-vcon-core/raw/refs/heads/main/examples/ab_call_2ch.ogg", + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + }, + { + "type": "text", + "start": "2022-06-21T17:53:26.000+00:00", + "parties": [ + 1 + ], + "mediatype": "text/plain", + "body": "Good day!", + "encoding": "none" + } + ], + "analysis": [], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0, + 1 + ] + } + ], + "uuid": "01a16b86-9ea3-8a32-a20f-d188127fad29", + "amended_from": { + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" + } +} diff --git a/tests/schema/vcon_json_schema.json b/tests/schema/vcon_json_schema.json index 9a323fb..e3b5c90 100644 --- a/tests/schema/vcon_json_schema.json +++ b/tests/schema/vcon_json_schema.json @@ -12,7 +12,7 @@ "vcon": { "type": "string", "description": "DEPRECATED: Syntactic version of the JSON format. This was used to indicate schema changes in the Internet-Draft versions", - "const": "0.4.0" + "const": "0.5.0" }, "uuid": { "type": "string", @@ -47,9 +47,9 @@ "type": "string", "description": "Subject or topic of the conversation" }, - "redacted": { + "redacted_from": { "type": "object", - "description": "Reference to the unredacted or less redacted vCon prior instance", + "description": "Reference to the unredacted or less redacted vCon prior instance (Redacted_from Object); mutually exclusive with amended_from", "required": [ "type" ], @@ -61,7 +61,7 @@ }, "type": { "type": "string", - "description": "Type of redaction performed" + "description": "Type of redaction performed; same set of values as the type parameter of the Redacted_string Object" }, "url": { "type": "string", @@ -89,9 +89,9 @@ ] } }, - "amended": { + "amended_from": { "type": "object", - "description": "Reference to the prior vCon instance version that this vCon amends", + "description": "Reference to the prior vCon instance version that this vCon amends (Amended_from Object); mutually exclusive with redacted_from", "properties": { "uuid": { "type": "string", @@ -137,6 +137,20 @@ "$comment": "uuid is optional only if an external reference is provided" } }, + "redacted_strings": { + "type": "array", + "description": "Array of Redacted_string Objects, one for each unique substring replaced by __REDACTED_REF_# in the vCon", + "items": { + "$ref": "#/definitions/RedactedString" + } + }, + "sessions": { + "type": "array", + "description": "Array of Session Objects, each grouping the Dialog and Event Objects of one session of the conversation", + "items": { + "$ref": "#/definitions/Session" + } + }, "parties": { "type": "array", "description": "Array of Party Objects representing all parties involved in the conversation", @@ -144,6 +158,13 @@ "$ref": "#/definitions/Party" } }, + "events": { + "type": "array", + "description": "Array of Event Objects; order is not significant, Event Objects are sequenced by their time parameter", + "items": { + "$ref": "#/definitions/Event" + } + }, "dialog": { "type": "array", "description": "Array of Dialog Objects containing the captured conversation content", @@ -167,6 +188,84 @@ } }, "definitions": { + "Session": { + "type": "object", + "description": "Represents one session of the conversation and references the Dialog Objects which are part of it; a Session Object with no parameters is permitted", + "properties": { + "start": { + "type": "string", + "format": "date-time", + "description": "Start time of the session in RFC3339 format; SHOULD be present" + }, + "duration": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "number", + "minimum": 0 + } + ], + "description": "Duration of the session in seconds" + }, + "parties": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "description": "Indices of the parties that are the receivers of the dialog in the session; SHOULD be present; the first party is the implied originator" + }, + "originator": { + "type": "integer", + "minimum": 0, + "description": "Index of the originating party; only provided if the first party in parties is not the originator" + }, + "session_id": { + "$ref": "#/definitions/SessionId" + }, + "sessions": { + "type": "array", + "items": { + "$ref": "#/definitions/SessionReference" + }, + "description": "Relationships to other Session Objects" + }, + "dialog": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "description": "Indices of the Dialog Objects which are part of the session" + } + } + }, + "SessionReference": { + "type": "object", + "description": "Session_Reference Object: the relationship of another Session Object to the Session Object which contains this reference", + "required": [ + "session", + "type" + ], + "properties": { + "session": { + "type": "integer", + "minimum": 0, + "description": "Index of the referenced Session Object in the sessions array" + }, + "type": { + "type": "string", + "description": "Type of relationship: child, peer, precursor, breakout, or a value defined in a vCon extension" + }, + "description": { + "type": "string", + "description": "Free form text description of the relationship" + } + } + }, "Party": { "type": "object", "description": "Represents a party involved in the conversation", @@ -297,44 +396,25 @@ } } }, - "Dialog": { + "Event": { "type": "object", - "description": "Represents a segment of captured conversation", + "description": "Represents an event which occurred in a session, such as a party joining, a key press or a transfer", "required": [ - "type" + "type", + "time" ], "properties": { "type": { "type": "string", - "enum": [ - "recording", - "text", - "transfer", - "incomplete", - "recording-set" - ], - "description": "Type of dialog" + "description": "Type of event: join, drop, hold, unhold, mute, unmute, keydown, keyup, consultation-start, blind-transfer, consultative-transfer, transfer-abandoned, channel-contributors, or a value defined in a vCon extension" }, - "start": { + "time": { "type": "string", "format": "date-time", - "description": "Start time of the dialog in RFC3339 format; SHOULD be present unless not known; optional for transfer type" - }, - "duration": { - "anyOf": [ - { - "type": "integer", - "minimum": 0 - }, - { - "type": "number", - "minimum": 0 - } - ], - "description": "Duration in seconds" + "description": "Time of the event in RFC3339 format" }, - "parties": { - "anyOf": [ + "sessions": { + "oneOf": [ { "type": "integer", "minimum": 0 @@ -345,187 +425,88 @@ "type": "integer", "minimum": 0 } - }, - { - "type": "array", - "items": { - "anyOf": [ - { - "type": "integer", - "minimum": 0 - }, - { - "type": "array", - "items": { - "type": "integer", - "minimum": 0 - } - }, - { - "type": "null" - } - ] - } } ], - "description": "Index/indices of parties in the parties array; SHOULD be present for recording, recording-set and text types; MUST NOT be present for transfer type" + "description": "Index or indices of the Session Objects in which the event occurred; the event applies only to the listed Session Objects; for transfer event types, a single index to the Session Object for the original call; MUST NOT be present for channel-contributors" }, - "originator": { + "party": { "type": "integer", "minimum": 0, - "description": "Index of the originating party if first party is not the originator" - }, - "recordings": { - "type": "array", - "items": { - "type": "integer", - "minimum": 0 - }, - "description": "recording-set reference to list of indices to recording Dialog Objects" + "description": "Index of the party to which the event applies; for transfer event types, the Transferor; MUST NOT be present for channel-contributors" }, - "recording_set": { + "dialog": { "type": "integer", "minimum": 0, - "description": "Index of the recording-set Dialog Object that this recording is a part of" - }, - "mediatype": { - "type": "string", - "description": "Media type of the dialog content; MUST be present for inline content; not required when Dialog Content is absent" + "description": "Index of the Dialog Object to which the event relates; required for channel-contributors, where it references a recording Dialog Object; SHOULD NOT be present for the other event types defined in RFCXXXX; an event type defined in a vCon extension may allow an array of indices" }, - "filename": { - "type": "string", - "description": "Original filename of the dialog content" - }, - "body": { - "description": "Inline content of the dialog (for inline files). Any type for encoding=json, otherwise it must be a string." - }, - "encoding": { - "type": "string", - "enum": [ - "base64url", - "json", - "none" - ], - "description": "Encoding type for inline content" - }, - "url": { - "type": "string", - "format": "uri", - "description": "HTTPS URL for externally referenced content" - }, - "content_hash": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ], - "description": "Hash(es) of external content" - }, - "disposition": { - "type": "string", - "enum": [ - "no-answer", - "congestion", - "failed", - "busy", - "hung-up", - "voicemail-no-message" - ], - "description": "Reason the call or conversation failed (required for incomplete type); \"failed\" SHOULD be used when the reason is not known" + "channel": { + "type": "integer", + "minimum": 0, + "description": "Index of the channel of the recording, where 0 is the first channel (channel-contributors only)" }, - "session_id": { + "contributors": { "anyOf": [ { - "$ref": "#/definitions/SessionId" + "type": "integer", + "minimum": 0 }, { "type": "array", "items": { - "$ref": "#/definitions/SessionId" + "type": "integer", + "minimum": 0 } }, { - "type": "array", - "items": { - "oneOf": [ - { - "$ref": "#/definitions/SessionId" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/SessionId" - } - } - ] - } + "type": "null" } ], - "description": "Session ID(s) for the dialog" + "description": "Index or indices of the parties contributing to the channel starting at the time of the event; null or absent means no party contributes (channel-contributors only)" }, - "party_history": { - "type": "array", - "items": { - "$ref": "#/definitions/PartyHistory" - }, - "description": "History of party join/drop/hold/mute events" + "button": { + "type": "string", + "description": "DTMF digit, character or string (required for keydown and keyup events)" }, "transferee": { "type": "integer", "minimum": 0, - "description": "Party index of the transferee (for transfer type)" - }, - "transferor": { - "type": "integer", - "minimum": 0, - "description": "Party index of the transferor (for transfer type)" + "description": "Party index of the Transferee (transfer event types)" }, "transfer_target": { "type": "integer", "minimum": 0, - "description": "Party index of the transfer target (for transfer type)" - }, - "original": { - "type": "integer", - "minimum": 0, - "description": "Dialog index of the original call (for transfer type); may reference a recording, recording-set or text type Dialog Object" + "description": "Party index of the Transfer Target (transfer event types; optional for transfer-abandoned)" }, "consultation": { "type": "integer", "minimum": 0, - "description": "Dialog index of the consultation call (for transfer type); may reference a recording, recording-set, text or incomplete type Dialog Object" + "description": "Session index of the consultative call (consultation-start and consultative-transfer; optional for transfer-abandoned)" }, - "target_dialog": { + "target_session": { "type": "integer", "minimum": 0, - "description": "Dialog index of the target call (for transfer type); may reference a recording, recording-set, text or incomplete type Dialog Object" - }, - "application": { - "type": "string", - "description": "Application, communication channel or context of the conversation" - }, - "message_id": { - "type": "string", - "description": "Unique message identifier from the messaging system" + "description": "Session index of the target call (blind-transfer and consultative-transfer)" } }, - "dependencies": { - "url": [ - "content_hash" - ] - }, "allOf": [ { "if": { "properties": { "type": { - "const": "incomplete" + "enum": [ + "join", + "drop", + "hold", + "unhold", + "mute", + "unmute", + "keydown", + "keyup", + "consultation-start", + "blind-transfer", + "consultative-transfer", + "transfer-abandoned" + ] } }, "required": [ @@ -534,15 +515,35 @@ }, "then": { "required": [ - "disposition" - ] + "sessions", + "party" + ], + "not": { + "anyOf": [ + { + "required": [ + "channel" + ] + }, + { + "required": [ + "contributors" + ] + } + ] + } } }, { "if": { "properties": { "type": { - "const": "recording-set" + "enum": [ + "consultation-start", + "blind-transfer", + "consultative-transfer", + "transfer-abandoned" + ] } }, "required": [ @@ -550,16 +551,26 @@ ] }, "then": { - "required": [ - "recordings" - ] + "properties": { + "sessions": { + "type": "integer", + "minimum": 0 + } + } } }, { "if": { "properties": { "type": { - "const": "transfer" + "enum": [ + "join", + "drop", + "hold", + "unhold", + "mute", + "unmute" + ] } }, "required": [ @@ -571,67 +582,27 @@ "anyOf": [ { "required": [ - "parties" - ] - }, - { - "required": [ - "originator" - ] - }, - { - "required": [ - "session_id" - ] - }, - { - "required": [ - "party_history" - ] - }, - { - "required": [ - "message_id" + "button" ] }, { "required": [ - "recordings" + "transferee" ] }, { "required": [ - "recording_set" + "transfer_target" ] }, { "required": [ - "mediatype" + "consultation" ] }, { "required": [ - "filename" - ] - }, - { - "required": [ - "body" - ] - }, - { - "required": [ - "encoding" - ] - }, - { - "required": [ - "url" - ] - }, - { - "required": [ - "content_hash" + "target_session" ] } ] @@ -642,7 +613,10 @@ "if": { "properties": { "type": { - "const": "recording-set" + "enum": [ + "keydown", + "keyup" + ] } }, "required": [ @@ -650,68 +624,21 @@ ] }, "then": { + "required": [ + "button" + ], "not": { "anyOf": [ - { - "required": [ - "message_id" - ] - }, - { - "required": [ - "recording_set" - ] - }, - { - "required": [ - "mediatype" - ] - }, - { - "required": [ - "filename" - ] - }, - { - "required": [ - "body" - ] - }, - { - "required": [ - "encoding" - ] - }, - { - "required": [ - "url" - ] - }, - { - "required": [ - "content_hash" - ] - }, { "required": [ "transferee" ] }, - { - "required": [ - "transferor" - ] - }, { "required": [ "transfer_target" ] }, - { - "required": [ - "original" - ] - }, { "required": [ "consultation" @@ -719,7 +646,7 @@ }, { "required": [ - "target_dialog" + "target_session" ] } ] @@ -730,7 +657,7 @@ "if": { "properties": { "type": { - "const": "incomplete" + "const": "consultation-start" } }, "required": [ @@ -738,81 +665,114 @@ ] }, "then": { + "required": [ + "transferee", + "transfer_target", + "consultation" + ], "not": { "anyOf": [ { "required": [ - "message_id" + "button" ] }, { "required": [ - "recordings" + "target_session" ] - }, - { - "required": [ - "recording_set" - ] - }, - { - "required": [ - "mediatype" - ] - }, - { - "required": [ - "filename" - ] - }, - { - "required": [ - "body" - ] - }, - { - "required": [ - "encoding" - ] - }, - { - "required": [ - "url" - ] - }, - { - "required": [ - "content_hash" - ] - }, - { - "required": [ - "transferee" - ] - }, + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "blind-transfer" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee", + "transfer_target", + "target_session" + ], + "not": { + "anyOf": [ { "required": [ - "transferor" + "button" ] }, { "required": [ - "transfer_target" + "consultation" ] - }, + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "consultative-transfer" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee", + "transfer_target", + "consultation", + "target_session" + ], + "not": { + "anyOf": [ { "required": [ - "original" + "button" ] - }, + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "transfer-abandoned" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee" + ], + "not": { + "anyOf": [ { "required": [ - "consultation" + "button" ] }, { "required": [ - "target_dialog" + "target_session" ] } ] @@ -823,7 +783,7 @@ "if": { "properties": { "type": { - "const": "recording" + "const": "channel-contributors" } }, "required": [ @@ -831,31 +791,35 @@ ] }, "then": { + "required": [ + "dialog", + "channel" + ], "not": { "anyOf": [ { "required": [ - "recordings" + "sessions" ] }, { "required": [ - "transferee" + "party" ] }, { "required": [ - "transferor" + "button" ] }, { "required": [ - "transfer_target" + "transferee" ] }, { "required": [ - "original" + "transfer_target" ] }, { @@ -865,18 +829,185 @@ }, { "required": [ - "target_dialog" + "target_session" ] } ] } - } + } + } + ], + "$comment": "The rules for each known type follow the Event Object Parameter Applicability by Type tables. SHOULD NOT statements, such as dialog in the event types other than channel-contributors, are not enforced. An Event Object with a type which is not listed is only checked for the parameters common to all types." + }, + "Dialog": { + "type": "object", + "description": "Represents a segment of captured conversation; an empty Dialog Object holds a position in the dialog array", + "anyOf": [ + { + "required": [ + "type" + ] + }, + { + "maxProperties": 0, + "$comment": "An empty Dialog Object has no type and no meaning" + } + ], + "properties": { + "type": { + "type": "string", + "description": "Type of dialog: recording, text, incomplete, or a value defined in a vCon extension" + }, + "start": { + "type": "string", + "format": "date-time", + "description": "Start time of the dialog in RFC3339 format; SHOULD be present unless not known" + }, + "duration": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "number", + "minimum": 0 + } + ], + "description": "Duration in seconds" + }, + "parties": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + }, + { + "type": "array", + "items": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + }, + { + "type": "null" + } + ] + } + } + ], + "description": "Index/indices of the parties that contributed to the dialog content; SHOULD be present for recording and text types" + }, + "mediatype": { + "type": "string", + "description": "Media type of the dialog content; MUST be present for inline content; not required when Dialog Content is absent" + }, + "filename": { + "type": "string", + "description": "Original filename of the dialog content" + }, + "body": { + "description": "Inline content of the dialog (for inline files). Any type for encoding json; a string for encoding base64url or none." + }, + "encoding": { + "type": "string", + "description": "Encoding type for inline content: base64url, json, none, or a value defined in a vCon extension" + }, + "url": { + "type": "string", + "format": "uri", + "description": "HTTPS URL for externally referenced content" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of external content" + }, + "disposition": { + "type": "string", + "description": "Reason the call or conversation failed (required for incomplete type, SHOULD NOT be present for other types): no-answer, congestion, failed, busy, hung-up, voicemail-no-message, or a value defined in a vCon extension; \"failed\" SHOULD be used when the reason is not known" + }, + "session_id": { + "anyOf": [ + { + "$ref": "#/definitions/SessionId" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/SessionId" + } + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "$ref": "#/definitions/SessionId" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/SessionId" + } + } + ] + } + } + ], + "description": "Session ID(s) for the dialog, correlated with the parties parameter" + }, + "application": { + "type": "string", + "description": "Application, communication channel or context of the conversation" + }, + "message_id": { + "type": "string", + "description": "Unique message identifier from the messaging system" }, + "redacted_segments": { + "type": "array", + "description": "Redacted_segments Objects for the audiovisual segments which were redacted; SHOULD NOT be present for text; MUST NOT be present for incomplete", + "items": { + "$ref": "#/definitions/RedactedSegments" + } + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "allOf": [ { "if": { "properties": { "type": { - "const": "text" + "const": "incomplete" } }, "required": [ @@ -884,46 +1015,49 @@ ] }, "then": { + "required": [ + "disposition" + ], "not": { "anyOf": [ { "required": [ - "recordings" + "mediatype" ] }, { "required": [ - "recording_set" + "filename" ] }, { "required": [ - "transferee" + "body" ] }, { "required": [ - "transferor" + "encoding" ] }, { "required": [ - "transfer_target" + "url" ] }, - { + { "required": [ - "original" + "content_hash" ] }, { "required": [ - "consultation" + "message_id" ] }, { "required": [ - "target_dialog" + "redacted_segments" ] } ] @@ -967,8 +1101,31 @@ "mediatype" ] } + }, + { + "if": { + "properties": { + "encoding": { + "enum": [ + "base64url", + "none" + ] + } + }, + "required": [ + "encoding" + ] + }, + "then": { + "properties": { + "body": { + "type": "string" + } + } + } } - ] + ], + "$comment": "The rules for each known type follow the Dialog Object Parameter Applicability by Type table. A Dialog Object with a type which is not listed is only checked for the rules common to all types." }, "SessionId": { "type": "object", @@ -984,70 +1141,12 @@ } } }, - "PartyHistory": { - "type": "object", - "description": "Records party events during the dialog", - "required": [ - "party", - "time", - "event" - ], - "properties": { - "party": { - "type": "integer", - "minimum": 0, - "description": "Index of the party" - }, - "time": { - "type": "string", - "format": "date-time", - "description": "Time of the event in RFC3339 format" - }, - "event": { - "type": "string", - "enum": [ - "join", - "drop", - "hold", - "unhold", - "mute", - "unmute", - "keydown", - "keyup" - ], - "description": "Type of event" - }, - "button": { - "type": "string", - "description": "DTMF digit, character or string (required for keydown/keyup events)" - } - }, - "if": { - "properties": { - "event": { - "enum": [ - "keydown", - "keyup" - ] - } - }, - "required": [ - "event" - ] - }, - "then": { - "required": [ - "button" - ] - } - }, "Attachment": { "type": "object", "description": "Represents an ancillary document related to the conversation", "required": [ "start", - "party", - "dialog" + "party" ], "properties": { "purpose": { @@ -1067,7 +1166,23 @@ "dialog": { "type": "integer", "minimum": 0, - "description": "Index of the dialog this attachment is part of" + "description": "Index of the dialog this attachment is part of (optional; at least one of dialog or session MUST be present)" + }, + "session": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of the Session Object(s) this attachment is related to" }, "mediatype": { "type": "string", @@ -1078,16 +1193,11 @@ "description": "Original filename of the attachment" }, "body": { - "description": "Inline content of the attachment (for inline files). Any type for encoding=json, otherwise it must be a string." + "description": "Inline content of the attachment (for inline files). Any type for encoding json; a string for encoding base64url or none." }, "encoding": { "type": "string", - "enum": [ - "base64url", - "json", - "none" - ], - "description": "Encoding type for inline content" + "description": "Encoding type for inline content: base64url, json, none, or a value defined in a vCon extension" }, "url": { "type": "string", @@ -1114,6 +1224,18 @@ "content_hash" ] }, + "anyOf": [ + { + "required": [ + "dialog" + ] + }, + { + "required": [ + "session" + ] + } + ], "allOf": [ { "if": { @@ -1152,6 +1274,28 @@ "mediatype" ] } + }, + { + "if": { + "properties": { + "encoding": { + "enum": [ + "base64url", + "none" + ] + } + }, + "required": [ + "encoding" + ] + }, + "then": { + "properties": { + "body": { + "type": "string" + } + } + } } ] }, @@ -1181,7 +1325,23 @@ } } ], - "description": "Index/indices of dialog objects this analysis is based on" + "description": "Index/indices of dialog objects this analysis is based on (optional)" + }, + "sessions": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of Session Objects this analysis is based on (optional)" }, "attachment": { "oneOf": [ @@ -1197,7 +1357,23 @@ } } ], - "description": "Index/indices of attachment objects this analysis is based on" + "description": "Index/indices of attachment objects this analysis is based on (optional)" + }, + "analysis": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of other Analysis Objects this analysis is based on (optional); MUST NOT reference itself" }, "mediatype": { "type": "string", @@ -1220,16 +1396,11 @@ "description": "Token or label for the data format/schema of the analysis" }, "body": { - "description": "Inline content of the analysis (for inline files). Any type for encoding=json, otherwise it must be a string." + "description": "Inline content of the analysis (for inline files). Any type for encoding json; a string for encoding base64url or none." }, "encoding": { "type": "string", - "enum": [ - "base64url", - "json", - "none" - ], - "description": "Encoding type for inline content" + "description": "Encoding type for inline content: base64url, json, none, or a value defined in a vCon extension" }, "url": { "type": "string", @@ -1275,17 +1446,132 @@ "encoding" ] } + }, + { + "if": { + "properties": { + "encoding": { + "enum": [ + "base64url", + "none" + ] + } + }, + "required": [ + "encoding" + ] + }, + "then": { + "properties": { + "body": { + "type": "string" + } + } + } } - ] + ], + "$comment": "At least one of the dialog, sessions, attachment or analysis parameters SHOULD be present. An Analysis Object MUST NOT reference itself in the analysis parameter; this is not enforced by this schema." + }, + "RedactedString": { + "type": "object", + "description": "Information about a substring of the vCon which was replaced by __REDACTED_REF_#", + "required": [ + "ref" + ], + "properties": { + "ref": { + "type": "integer", + "minimum": 1, + "maximum": 99999, + "description": "Reference number of the redacted substring" + }, + "type": { + "type": "string", + "description": "Type of information redacted: GOVT_ID_NUM, FIN_ID_NUM, MED_ID_NUM, BIOMETRIC, AUTH_DATA, CONTACT_INFO, LOC_INFO, EMPL_INFO, BELIEF_INFO, UNSPECIFIED or another value; absent means UNSPECIFIED" + }, + "orig": { + "type": "string", + "description": "Original, unredacted value of the substring" + } + }, + "$comment": "That each __REDACTED_REF_# substring has a Redacted_string Object with a matching ref is not enforced by this schema." + }, + "RedactedSegments": { + "type": "object", + "description": "An audiovisual segment of a recording which was redacted", + "required": [ + "start", + "end" + ], + "properties": { + "start": { + "type": "string", + "format": "date-time", + "description": "Start time of the redaction in RFC3339 format" + }, + "end": { + "type": "string", + "format": "date-time", + "description": "End time of the redaction in RFC3339 format" + }, + "parties": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "description": "Indices of the parties whose content was redacted" + } + }, + "$comment": "TODO: should use duration instead of end?" } }, "not": { "required": [ - "redacted", - "amended" + "redacted_from", + "amended_from" ], - "$comment": "The redacted and amended parameters are mutually exclusive" + "$comment": "The redacted_from and amended_from parameters are mutually exclusive" }, - "$comment": "At least one of the parties, dialog, analysis or attachments parameters SHOULD be present (RFCXXXX Section 4). SHOULD-level statements are not enforced by this schema." + "allOf": [ + { + "if": { + "anyOf": [ + { + "required": [ + "dialog" + ], + "properties": { + "dialog": { + "minItems": 1 + } + } + }, + { + "required": [ + "events" + ], + "properties": { + "events": { + "minItems": 1 + } + } + } + ] + }, + "then": { + "required": [ + "sessions" + ], + "properties": { + "sessions": { + "minItems": 1 + } + }, + "$comment": "At least one Session Object MUST exist if the events array or the dialog array contain Objects" + } + } + ], + "$comment": "This schema is permissive: parameters and type values which are not defined in RFCXXXX do not cause validation to fail. At least one of the parties, dialog, analysis or attachments parameters SHOULD be present. SHOULD-level statements are not enforced by this schema. Index values are not checked against the size of the array which they reference." } diff --git a/tests/test_core05_changes.py b/tests/test_core05_changes.py new file mode 100644 index 0000000..2336215 --- /dev/null +++ b/tests/test_core05_changes.py @@ -0,0 +1,388 @@ +"""Behaviour that changed in vCon 0.5.0 (draft-ietf-vcon-vcon-core-05).""" + +import base64 +import json + +import pytest + +from vcon import Vcon, Dialog, Session, Event, AlgorithmNotPermittedError +from vcon.party import Party +from vcon.vcon import Attachment + +T = "2026-01-01T00:00:00Z" + + +def _b64(obj): + return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode() + + +def _base(): + v = Vcon.build_new() + v.add_party(Party(name="Alice")) + v.add_party(Party(name="Bob")) + v.add_session(Session(start=T, parties=[0, 1])) + return v + + +class TestRedactedFromAmendedFrom: + def test_properties_replace_old_names(self): + v = Vcon({"uuid": "a", "created_at": T, "redacted_from": {"uuid": "b", "type": "PII"}}) + assert v.redacted_from == {"uuid": "b", "type": "PII"} + assert v.amended_from is None + assert not hasattr(v, "redacted") + assert not hasattr(v, "amended") + w = Vcon({"uuid": "a", "created_at": T, "amended_from": {"uuid": "b"}}) + assert w.amended_from == {"uuid": "b"} + + def test_mutually_exclusive(self): + v = _base() + v.vcon_dict["redacted_from"] = {"uuid": "b", "type": "PII"} + v.vcon_dict["amended_from"] = {"uuid": "c"} + valid, errors = v.is_valid() + assert not valid + assert any("mutually exclusive" in e for e in errors) + + def test_url_needs_content_hash(self): + v = _base() + v.vcon_dict["amended_from"] = {"url": "https://example.com/v.json"} + assert any("content_hash" in e for e in v.is_valid()[1]) + v.vcon_dict["amended_from"] = {"url": "https://example.com/v.json", "content_hash": "sha512-abc"} + assert v.is_valid()[0] + + def test_amended_from_needs_uuid_or_url(self): + v = _base() + v.vcon_dict["amended_from"] = {} + assert any("uuid, or an external reference" in e for e in v.is_valid()[1]) + + def test_redacted_from_needs_type(self): + v = _base() + v.vcon_dict["redacted_from"] = {"uuid": "b"} + assert any("missing required field: type" in e for e in v.is_valid()[1]) + + def test_legacy_names_are_flagged_when_migration_is_off(self): + v = Vcon( + {"uuid": "a", "created_at": T, "vcon": "0.4.0", "redacted": {"uuid": "b", "type": "x"}}, + migrate_legacy=False, + ) + valid, errors = v.is_valid() + assert not valid + assert any("'redacted' was renamed 'redacted_from'" in e for e in errors) + assert any("Unsupported vcon syntax version '0.4.0'" in e for e in errors) + + def test_strict_property_handling_keeps_new_names(self): + v = Vcon( + {"uuid": "a", "created_at": T, "redacted_from": {"uuid": "b", "type": "x"}, "junk": 1}, + property_handling="strict", + ) + assert "redacted_from" in v.vcon_dict and "junk" not in v.vcon_dict + + +class TestAttachments: + def test_party_is_required_and_dialog_or_session(self): + v = _base() + v.vcon_dict["attachments"].append( + {"purpose": "x", "body": "b", "encoding": "none", "start": T} + ) + errors = v.is_valid()[1] + assert any("missing required field: party" in e for e in errors) + assert any("at least one of dialog or session" in e for e in errors) + + def test_session_alone_satisfies_the_scope_rule(self): + v = _base() + v.add_attachment("x", body="b", party=0, session=0, mediatype="text/plain") + assert v.vcon_dict["attachments"][0]["session"] == 0 + assert "dialog" not in v.vcon_dict["attachments"][0] + assert v.is_valid() == (True, []) + + def test_session_list_and_dialog_together(self): + v = _base() + v.add_session(Session(start=T)) + v.add_dialog(Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none"), session=0) + v.add_attachment("x", body="b", party=1, dialog=0, session=[0, 1], mediatype="text/plain") + assert v.is_valid() == (True, []) + + def test_bad_references_are_errors(self): + v = _base() + v.add_attachment("x", body="b", party=7, session=3) + errors = v.is_valid()[1] + assert any("invalid party index: 7" in e for e in errors) + assert any("invalid session index: 3" in e for e in errors) + + def test_default_scope_is_every_session(self): + v = _base() + v.add_session(Session(start=T)) + v.add_attachment("x", body="b") + assert v.vcon_dict["attachments"][0]["session"] == [0, 1] + assert v.vcon_dict["attachments"][0]["party"] == 0 + + def test_attachment_class_has_session_and_no_dialog_default(self): + a = Attachment("p", body="b", session=[0]) + d = a.to_dict() + assert d["session"] == [0] and "dialog" not in d and d["party"] == 0 + + def test_redacted_attachment_may_lack_content(self): + v = _base() + v.vcon_dict["redacted_from"] = {"uuid": "b", "type": "PII"} + v.vcon_dict["attachments"].append({"purpose": "x", "start": T, "party": 0, "session": 0}) + assert v.is_valid() == (True, []) + + +class TestAnalysis: + def test_dialog_is_optional_and_new_references_are_checked(self): + v = _base() + v.add_analysis(type="summary", vendor="v", body="s", sessions=0) + assert "dialog" not in v.analysis[0] + assert v.is_valid() == (True, []) + v.add_analysis(type="summary", vendor="v", body="s", sessions=5, attachment=2, analysis=1) + errors = v.is_valid()[1] + assert any("invalid session index: 5" in e for e in errors) + assert any("invalid attachment index: 2" in e for e in errors) + assert any("must not reference itself" in e for e in errors) + + +class TestDialog: + def test_dialog_types_are_recording_text_incomplete(self): + for t in ("recording", "text", "incomplete"): + assert t in Dialog.VALID_TYPES + assert "transfer" not in Dialog.VALID_TYPES + + def test_empty_dialog_is_valid_and_keeps_indices(self): + v = _base() + v.add_dialog(Dialog.placeholder(), session=0) # even if a Session lists it + v.add_dialog(Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none"), session=0) + assert v.dialog[0] == {} + assert v.is_valid() == (True, []) + + def test_parties_may_contain_nulls_and_lists(self): + v = _base() + v.add_dialog( + Dialog(type="recording", start=T, parties=[[0, 1], None, 1], mediatype="audio/wav", url="https://e.com/a.wav", content_hash="sha512-x"), + session=0, + ) + assert v.is_valid() == (True, []) + + def test_incomplete_dialog_has_no_content(self): + v = _base() + v.add_incomplete_dialog(start=T, disposition="no-answer", parties=[0], session=0) + assert v.is_valid() == (True, []) + d = v.dialog[0] + assert d["type"] == "incomplete" and "body" not in d + v.vcon_dict["dialog"][0]["body"] = "x" + assert any("must not have field: body" in e for e in v.is_valid()[1]) + + def test_removed_types_and_parameters_fail_validation(self): + v = _base() + v.vcon_dict["dialog"].append({"type": "transfer", "start": T}) + v.vcon_dict["dialog"].append({"type": "text", "start": T, "parties": [0], "originator": 0, "party_history": [], + "body": "x", "mediatype": "text/plain", "encoding": "none"}) + errors = v.is_valid()[1] + assert any("type 'transfer'" in e and "removed in 0.5.0" in e for e in errors) + assert any("'originator', which was removed" in e for e in errors) + assert any("'party_history', which was removed" in e for e in errors) + + def test_no_transfer_dialog_helper(self): + assert not hasattr(Vcon, "add_transfer_dialog") + + def test_multipart_alternative_mediatype_with_parameters(self): + v = _base() + v.add_dialog( + Dialog(type="text", start=T, parties=[0], body="x", encoding="none", + mediatype='multipart/alternative; boundary="----=_Part_1"'), + session=0, + ) + assert v.is_valid() == (True, []) + + def test_redacted_segments(self): + v = _base() + v.add_dialog( + Dialog(type="recording", start=T, parties=[0], mediatype="audio/wav", url="https://e.com/a.wav", + content_hash="sha512-x", redacted_segments=[{"start": T, "end": "2026-01-01T00:00:05Z"}]), + session=0, + ) + assert v.is_valid() == (True, []) + v.vcon_dict["dialog"][0]["redacted_segments"] = [{"start": T}] + assert any("requires start and end" in e for e in v.is_valid()[1]) + + +class TestSigning: + def test_sign_rejects_alg_none(self): + v = _base() + priv, _ = Vcon.generate_key_pair() + for alg in ("none", "None", "NONE", " none "): + with pytest.raises(AlgorithmNotPermittedError): + v.sign(priv, alg=alg) + assert "signatures" not in v.vcon_dict + + def test_sign_rejects_unknown_alg(self): + v = _base() + priv, _ = Vcon.generate_key_pair() + with pytest.raises(AlgorithmNotPermittedError): + v.sign(priv, alg="HS256x") + + def test_sign_and_verify_rs256_default(self): + v = _base() + priv, pub = Vcon.generate_key_pair() + v.sign(priv) + header = json.loads(base64.urlsafe_b64decode(v.vcon_dict["signatures"][0]["protected"] + "==")) + assert header["alg"] == "RS256" + assert v.verify(pub) is True + + def test_verify_refuses_alg_none_in_protected_header(self): + v = _base() + _, pub = Vcon.generate_key_pair() + v.vcon_dict["payload"] = _b64({"uuid": "x"}) + v.vcon_dict["signatures"] = [{"protected": _b64({"alg": "none"}), "signature": ""}] + with pytest.raises(AlgorithmNotPermittedError): + v.verify(pub) + + def test_verify_refuses_alg_none_in_header_object(self): + v = _base() + _, pub = Vcon.generate_key_pair() + v.vcon_dict["payload"] = _b64({"uuid": "x"}) + v.vcon_dict["signatures"] = [ + {"protected": _b64({"typ": "JWS"}), "header": {"alg": "NONE"}, "signature": ""} + ] + with pytest.raises(AlgorithmNotPermittedError): + v.verify(pub) + + def test_verify_fails_closed_without_alg(self): + v = _base() + _, pub = Vcon.generate_key_pair() + v.vcon_dict["payload"] = _b64({"uuid": "x"}) + v.vcon_dict["signatures"] = [{"protected": _b64({"typ": "JWS"}), "signature": "AA"}] + assert v.verify(pub) is False + + def test_verify_wrong_key_is_false(self): + v = _base() + priv, _ = Vcon.generate_key_pair() + _, other = Vcon.generate_key_pair() + v.sign(priv) + assert v.verify(other) is False + + +class TestExtensionsEnforcement: + def test_lawful_basis_in_use_must_be_listed(self): + v = _base() + v.vcon_dict["attachments"].append( + {"purpose": "lawful_basis", "start": T, "party": 0, "session": [0], "body": {}, "encoding": "json", "mediatype": "application/json"} + ) + valid, errors = v.is_valid() + assert not valid + assert any("Extension 'lawful_basis' is in use but is not listed" in e for e in errors) + v.add_extension("lawful_basis") + assert v.is_valid() == (True, []) + + def test_wtf_in_use_must_be_listed(self): + v = _base() + v.add_analysis(type="wtf_transcription", vendor="v", body={}, encoding="json", sessions=0) + assert any("'wtf_transcription' is in use" in e for e in v.is_valid()[1]) + + def test_critical_must_be_in_extensions(self): + v = _base() + v.add_critical("x_ext") + errors = v.is_valid()[1] + assert any("'x_ext' is listed in critical but not in extensions" in e for e in errors) + v.add_extension("x_ext") + assert v.is_valid() == (True, []) + + def test_non_core_values_need_some_extension(self): + v = _base() + v.vcon_dict["sessions"][0]["sessions"] = [{"session": 0, "type": "x-weird"}] + assert any("outside the core vocabulary" in e for e in v.is_valid()[1]) + v.add_extension("weird") + assert v.is_valid()[0] + + def test_nonstandard_encoding_needs_extension(self): + v = _base() + v.add_attachment("x", body="b", encoding="none", session=0) + v.vcon_dict["attachments"][0]["encoding"] = "gzip" + assert not v.is_valid()[0] + + def test_helpers_add_the_extension_name(self): + v = _base() + v.add_lawful_basis_attachment( + lawful_basis="consent", expiration="2030-01-01T00:00:00Z", + purpose_grants=[{"purpose": "recording", "granted": True, "granted_at": T}], + ) + assert "lawful_basis" in v.get_extensions() + assert v.is_valid() == (True, []) + + +class TestLawfulBasisScope: + GRANTS = [{"purpose": "recording", "granted": True, "granted_at": T}] + + def test_attachment_carries_session_and_party(self): + v = _base() + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS, party_index=1) + att = v.find_lawful_basis_attachments()[0] + assert att["purpose"] == "lawful_basis" + assert att["session"] == [0] + assert att["party"] == 1 + assert "dialog" not in att + + def test_default_scope_is_all_sessions(self): + v = _base() + v.add_session(Session(start=T)) + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS) + assert v.find_lawful_basis_attachments()[0]["session"] == [0, 1] + + def test_dialog_index_adds_dialog_and_uses_sessions_listing_it(self): + v = _base() + v.add_session(Session(start=T)) + v.add_dialog(Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none"), session=1) + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS, dialog_index=0) + att = v.find_lawful_basis_attachments()[0] + assert att["dialog"] == 0 and att["session"] == [1] + + def test_explicit_session_index(self): + v = _base() + v.add_session(Session(start=T)) + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS, session_index=1) + assert v.find_lawful_basis_attachments()[0]["session"] == 1 + + def test_placeholder_session_is_added_when_there_is_none(self): + v = Vcon.build_new() + v.add_party(Party(name="A")) + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS) + assert v.sessions == [{}] + assert v.find_lawful_basis_attachments()[0]["session"] == [0] + assert v.is_valid() == (True, []) + + def test_wtf_attachment_is_scoped_too(self): + v = _base() + v.add_wtf_transcription_attachment( + transcript={"text": "hi", "language": "en", "duration": 1.0, "confidence": 0.9}, + segments=[{"id": 0, "start": 0.0, "end": 1.0, "text": "hi", "confidence": 0.9}], + metadata={"created_at": T, "processed_at": T, "provider": "p", "model": "m"}, + ) + assert v.find_wtf_attachments()[0]["session"] == [0] + + +class TestRedactedStrings: + def test_every_reference_needs_an_entry(self): + v = _base() + v.add_dialog(Dialog(type="text", start=T, parties=[0], body="my number is __REDACTED_REF_1 ok", mediatype="text/plain", encoding="none"), session=0) + errors = v.is_valid()[1] + assert any("__REDACTED_REF_1 appears in the vCon but has no entry" in e for e in errors) + v.vcon_dict["redacted_strings"] = [{"ref": 1, "type": "GOVT_ID_NUM"}] + assert v.is_valid() == (True, []) + + def test_ref_range_and_duplicates(self): + v = _base() + v.vcon_dict["redacted_strings"] = [{"ref": 0}, {"ref": 2}, {"ref": 2}] + errors = v.is_valid()[1] + assert any("between 1 and 99999" in e for e in errors) + assert any("duplicates ref 2" in e for e in errors) + + +class TestVersionHandling: + def test_build_new_emits_0_5_0(self): + assert Vcon.build_new().vcon == "0.5.0" + + def test_version_absent_is_accepted(self): + v = Vcon({"uuid": "a", "created_at": T}) + assert v.is_valid()[0] + + def test_other_versions_are_not_valid(self): + v = Vcon({"uuid": "a", "created_at": T, "vcon": "0.3.0"}) + assert not v.is_valid()[0] diff --git a/tests/test_core05_examples.py b/tests/test_core05_examples.py new file mode 100644 index 0000000..02162c4 --- /dev/null +++ b/tests/test_core05_examples.py @@ -0,0 +1,128 @@ +"""Appendix B examples of core-05 load and validate; library output validates against Appendix C.""" + +import base64 +import copy +import json +from pathlib import Path + +import pytest + +jsonschema = pytest.importorskip("jsonschema") + +from vcon import Vcon, Dialog, Session, Event +from vcon.party import Party + +SCHEMA_DIR = Path(__file__).parent / "schema" +SCHEMA = json.loads((SCHEMA_DIR / "vcon_json_schema.json").read_text()) +EXAMPLES = sorted((SCHEMA_DIR / "examples").glob("B*.json")) +UNSIGNED = [p for p in EXAMPLES if p.name[:2] in {"B1", "B2", "B3", "B4", "B5", "B8", "B9"}] + + +def _validator(): + return jsonschema.Draft7Validator(SCHEMA, format_checker=jsonschema.FormatChecker()) + + +def test_all_nine_appendix_b_examples_are_present(): + assert [p.name[:2] for p in EXAMPLES] == ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9"] + + +@pytest.mark.parametrize("path", UNSIGNED, ids=lambda p: p.name[:2]) +def test_unsigned_example_validates_against_appendix_c(path): + data = json.loads(path.read_text()) + _validator().validate(data) + + +@pytest.mark.parametrize("path", UNSIGNED, ids=lambda p: p.name[:2]) +def test_unsigned_example_loads_and_passes_is_valid(path): + data = json.loads(path.read_text()) + vcon = Vcon.load(str(path)) + assert vcon.migration_report is None # already 0.5.0 + assert vcon.vcon == "0.5.0" + valid, errors = vcon.is_valid() + assert valid, errors + # Loading does not change the example's content. + assert vcon.to_dict()["sessions"] == data["sessions"] + assert vcon.to_dict().get("events") == data.get("events") + assert vcon.to_dict()["dialog"] == data["dialog"] + + +def test_signed_example_b6_payload_loads_and_validates(): + envelope = json.loads((SCHEMA_DIR / "examples" / "B6-signed.json").read_text()) + protected = json.loads(base64.urlsafe_b64decode(envelope["signatures"][0]["protected"] + "==")) + assert protected == {"alg": "RS256"} + raw = envelope["payload"] + payload = json.loads(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4))) + _validator().validate(payload) + vcon = Vcon(payload) + assert vcon.is_valid()[0] + + +def test_encrypted_example_b7_is_a_jwe_not_a_vcon(): + envelope = json.loads((SCHEMA_DIR / "examples" / "B7-encrypted.json").read_text()) + assert {"protected", "iv", "ciphertext", "tag", "recipients", "unprotected"} <= set(envelope) + assert json.loads(base64.urlsafe_b64decode(envelope["protected"] + "=="))["alg"] == "RSA-OAEP" + + +def test_b1_events_use_bare_integer_sessions(): + vcon = Vcon.load(str(SCHEMA_DIR / "examples" / "B1-two-party-call-inline-recording.json")) + assert [e["type"] for e in vcon.events] == ["join", "join", "drop", "drop"] + assert all(e["sessions"] == 0 and "dialog" not in e for e in vcon.events) + + +def test_b8_and_b9_use_the_renamed_parameters(): + b8 = Vcon.load(str(SCHEMA_DIR / "examples" / "B8-redacted.json")) + b9 = Vcon.load(str(SCHEMA_DIR / "examples" / "B9-amended-signed.json")) + assert b8.redacted_from["uuid"] and b9.amended_from["uuid"] + + +def test_library_built_vcon_with_every_object_kind_validates(): + vcon = Vcon.build_new() + vcon.add_party(Party(name="Alice", tel="+12025550101")) + vcon.add_party(Party(name="Bob", tel="+12025550102")) + vcon.add_party(Party(name="Carol", tel="+12025550103")) + vcon.add_session(Session(start="2026-01-01T00:00:00Z", duration=60, parties=[0, 1])) + s1 = vcon.add_session(Session(start="2026-01-01T00:00:10Z", duration=30, parties=[1, 2])) + s2 = vcon.add_session(Session(start="2026-01-01T00:00:45Z", parties=[0, 2])) + vcon.vcon_dict["sessions"][0]["sessions"] = [{"session": 1, "type": "child", "description": "consult"}] + vcon.add_dialog( + Dialog(type="recording", start="2026-01-01T00:00:00Z", duration=60, parties=[[0], [1]], + mediatype="audio/wav", url="https://example.com/a.wav", content_hash="sha512-abc"), + session=0, + ) + vcon.add_dialog(Dialog(type="text", start="2026-01-01T00:00:10Z", parties=[1], body="hello", mediatype="text/plain", encoding="none"), session=1) + vcon.add_incomplete_dialog(start="2026-01-01T00:00:45Z", disposition="busy", parties=[0], session=2) + vcon.add_dialog(Dialog.placeholder()) + T = "2026-01-01T00:00:00Z" + for e in ( + Event(type="join", time=T, sessions=0, party=0), + Event(type="keydown", time=T, sessions=[0, 1], party=1, button="#"), + Event(type="consultation-start", time=T, sessions=0, party=1, transferee=0, transfer_target=2, consultation=1), + Event(type="consultative-transfer", time=T, sessions=0, party=1, transferee=0, transfer_target=2, consultation=1, target_session=2), + Event(type="blind-transfer", time=T, sessions=0, party=1, transferee=0, transfer_target=2, target_session=2), + Event(type="transfer-abandoned", time=T, sessions=0, party=1, transferee=0), + Event(type="channel-contributors", time=T, dialog=0, channel=1, contributors=[1, 2]), + Event(type="channel-contributors", time=T, dialog=0, channel=0, contributors=None), + ): + vcon.add_event(e) + vcon.add_tag("k", "v") + vcon.add_lawful_basis_attachment( + lawful_basis="consent", expiration="2030-01-01T00:00:00Z", + purpose_grants=[{"purpose": "recording", "granted": True, "granted_at": T}], + ) + vcon.add_analysis(type="summary", vendor="v", body="s", dialog=0, sessions=[0], attachment=0) + vcon.add_wtf_transcription_analysis( + transcript={"text": "hi", "language": "en", "duration": 1.0, "confidence": 0.9}, + segments=[{"id": 0, "start": 0.0, "end": 1.0, "text": "hi", "confidence": 0.9}], + metadata={"created_at": T, "processed_at": T, "provider": "p", "model": "m"}, + dialog_index=0, + ) + out = vcon.to_dict() + _validator().validate(out) + assert vcon.is_valid() == (True, []) + assert out["vcon"] == "0.5.0" + assert out["dialog"][3] == {} + assert s1 == 1 and s2 == 2 + + +def test_empty_build_new_validates_against_appendix_c(): + _validator().validate(Vcon.build_new().to_dict()) diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 5897e46..72a5bbc 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -15,29 +15,19 @@ class TestDialog: def test_initialization_with_all_parameters(self): from datetime import datetime from src.vcon.dialog import Dialog - from src.vcon.party import PartyHistory # Given - party_history = [PartyHistory(1, "join", datetime.now())] dialog = Dialog( type="text", start=datetime.now(), duration=120.0, parties=[1, 2], - originator=1, mediatype="text/plain", filename="example.txt", body="Hello, World!", encoding="utf-8", url="http://example.com", disposition="inline", - party_history=party_history, - transferee=2, - transferor=1, - transfer_target=3, - original=1, - consultation=2, - target_dialog=3, campaign="campaign1", interaction="interaction1", skill="skill1", @@ -47,7 +37,6 @@ def test_initialization_with_all_parameters(self): assert dialog.type == "text" assert dialog.duration == 120.0 assert dialog.parties == [1, 2] - assert dialog.party_history == party_history # Initialization with missing optional parameters def test_initialization_with_missing_optional_parameters(self): @@ -60,20 +49,12 @@ def test_initialization_with_missing_optional_parameters(self): start=datetime.now(), duration=None, parties=[1, 2], - originator=None, mediatype=None, filename=None, body=None, encoding=None, url=None, disposition=None, - party_history=None, - transferee=None, - transferor=None, - transfer_target=None, - original=None, - consultation=None, - target_dialog=None, campaign=None, interaction=None, skill=None, @@ -82,7 +63,6 @@ def test_initialization_with_missing_optional_parameters(self): # When & Then assert dialog.type == "audio" assert not hasattr(dialog, "duration") - assert not hasattr(dialog, "originator") assert not hasattr(dialog, "mediatype") def test_initialization_with_default_optional_parameters(self): @@ -91,23 +71,20 @@ def test_initialization_with_default_optional_parameters(self): from src.vcon.dialog import Dialog dialog = Dialog( - type="video", start=datetime.now(), duration=0.0, parties=[1], originator=1 + type="video", start=datetime.now(), duration=0.0, parties=[1] ) # When & Then assert dialog.duration == 0.0 assert dialog.parties == [1] - assert dialog.originator == 1 dialog = Dialog( type="video", start=datetime.now(), duration=0.0, parties=[1], - originator=None, ) - assert not hasattr(dialog, "originator") assert not hasattr(dialog, "body") dialog = Dialog( @@ -115,7 +92,6 @@ def test_initialization_with_default_optional_parameters(self): start=datetime.now(), duration=0.0, parties=[1], - originator=1, mediatype="video/mp4", ) @@ -127,29 +103,18 @@ def test_conversion_to_dict(self): # Given from datetime import datetime from src.vcon.dialog import Dialog - from src.vcon.party import PartyHistory - party_time = datetime.now().isoformat() - party_history = [PartyHistory(1, "join", party_time)] dialog = Dialog( type="text", start=datetime.now(), duration=120.0, parties=[1, 2], - originator=1, mediatype="text/plain", filename="example.txt", body="Hello, World!", encoding="utf-8", url="http://example.com", disposition="inline", - party_history=party_history, - transferee=2, - transferor=1, - transfer_target=3, - original=1, - consultation=2, - target_dialog=3, campaign="campaign1", interaction="interaction1", skill="skill1", @@ -162,12 +127,7 @@ def test_conversion_to_dict(self): assert dialog_dict["type"] == "text" assert dialog_dict["duration"] == 120.0 assert dialog_dict["parties"] == [1, 2] - assert dialog_dict["party_history"] == [ - {"party": 1, "event": "join", "time": party_time} - ] - assert dialog_dict["party_history"] == [ - {"party": 1, "event": "join", "time": party_time} - ] + assert "party_history" not in dialog_dict # Test the meta variable in the dialog def test_meta_variable_in_dialog(self): diff --git a/tests/test_dialog_extra.py b/tests/test_dialog_extra.py index 4d1b0db..4bb7f94 100644 --- a/tests/test_dialog_extra.py +++ b/tests/test_dialog_extra.py @@ -6,7 +6,6 @@ import pytest from src.vcon.dialog import Dialog -from src.vcon.party import PartyHistory class DummyResponse: @@ -56,20 +55,30 @@ def test_video_mediatype_autodetect(): assert dialog.mediatype == "video/mp4" -def test_to_dict_party_history_serialization(): - history = [ - PartyHistory(party=0, event="join", time=datetime(2026, 2, 3, 12, 0, tzinfo=timezone.utc)), - PartyHistory(party=1, event="drop", time="2026-02-03T12:05:00Z"), - ] - dialog = Dialog( - type="text", - start=datetime.now(timezone.utc), - parties=[0, 1], - party_history=history, - ) - data = dialog.to_dict() - assert data["party_history"][0]["event"] == "join" - assert data["party_history"][1]["time"] == "2026-02-03T12:05:00Z" +def test_removed_dialog_parameters_are_rejected(): + """party_history, originator and the transfer parameters left Dialog in 0.5.0.""" + for name, value in ( + ("party_history", []), + ("originator", 0), + ("transferor", 0), + ("target_dialog", 1), + ("recording_set", 0), + ): + with pytest.raises(ValueError, match="removed in vCon 0.5.0"): + Dialog(type="text", start=datetime.now(timezone.utc), parties=[0], **{name: value}) + + +def test_transfer_dialog_type_is_gone(): + with pytest.raises(ValueError, match="Invalid dialog type"): + Dialog(type="transfer", start=datetime.now(timezone.utc), parties=[0]) + with pytest.raises(ValueError, match="Invalid dialog type"): + Dialog(type="recording-set", start=datetime.now(timezone.utc), parties=[0]) + + +def test_placeholder_dialog_serializes_as_empty_object(): + placeholder = Dialog.placeholder() + assert placeholder.is_placeholder() + assert placeholder.to_dict() == {} def test_add_external_data_and_inline_data(monkeypatch): diff --git a/tests/test_migration_0_4_0.py b/tests/test_migration_0_4_0.py new file mode 100644 index 0000000..2a5e1e4 --- /dev/null +++ b/tests/test_migration_0_4_0.py @@ -0,0 +1,764 @@ +"""Migration of a 0.4.0 vCon to 0.5.0 (Appendix A.1, steps T1 to T15).""" + +import base64 +import copy +import json +from pathlib import Path + +import pytest + +from vcon import ( + Vcon, + migrate_0_4_0_to_0_5_0, + MigrationError, + MigrationReport, +) +from vcon.migration import MIGRATION_STEPS, FALLBACK, INFERRED, UNRESOLVED + +try: + import jsonschema +except ImportError: # pragma: no cover + jsonschema = None + +SCHEMA = json.loads((Path(__file__).parent / "schema" / "vcon_json_schema.json").read_text()) + +T0 = "2022-06-21T17:53:26.000+00:00" +T1 = "2022-06-21T17:54:00.000+00:00" +T2 = "2022-06-21T17:55:00.000+00:00" + + +def v04(**kw): + """A 0.4.0 vCon with three parties and the given extra top-level members.""" + d = { + "vcon": "0.4.0", + "uuid": "01a16b86-9a63-8346-b9a2-279e0d16bc46", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [{"name": "Alice"}, {"name": "Bob"}, {"name": "Carol"}], + "dialog": [], + "analysis": [], + "attachments": [], + } + d.update(kw) + return d + + +def rec(**kw): + d = {"type": "recording", "start": T0, "duration": 10, "parties": [0, 1], + "mediatype": "audio/x-wav", "url": "https://e.com/a.wav", "content_hash": "sha512-x"} + d.update(kw) + return d + + +def text(**kw): + d = {"type": "text", "start": T1, "parties": [0, 1], "body": "hi", "encoding": "none", "mediatype": "text/plain"} + d.update(kw) + return d + + +def check_schema(vcon): + if jsonschema: + jsonschema.Draft7Validator(SCHEMA).validate(vcon) + + +def migrate(d, **kw): + out, report = migrate_0_4_0_to_0_5_0(d, **kw) + check_schema(out) + return out, report + + +class TestTableDriven: + def test_one_entry_per_transform_step(self): + ids = [s.id for s in MIGRATION_STEPS] + assert sorted(ids) == sorted( + ["T1", "T2", "T3", "T4", "T6", "T7", "T8", "T9", "T9b", "T10", "T11", "T12", "T13", "T14", "T15", "T10b"] + ) + assert len(ids) == len(set(ids)) + assert all(s.source and s.title and callable(s.func) for s in MIGRATION_STEPS) + + def test_steps_run_in_the_documented_order(self): + _, report = migrate(v04()) + assert report.steps_run == [s.id for s in MIGRATION_STEPS] + order = report.steps_run + # reads of the original dialog array precede the in-place blanking + for step in ("T8", "T9", "T9b", "T6", "T2", "T7", "T3", "T4"): + assert order.index(step) < order.index("T10") + + def test_input_is_not_modified(self): + d = v04(dialog=[rec(originator=1, party_history=[{"party": 0, "time": T0, "event": "join"}])]) + before = copy.deepcopy(d) + migrate_0_4_0_to_0_5_0(d) + assert d == before + + def test_accepts_json_string(self): + out, _ = migrate_0_4_0_to_0_5_0(json.dumps(v04(dialog=[rec()]))) + assert out["vcon"] == "0.5.0" + + def test_rejects_other_versions_and_garbage(self): + with pytest.raises(MigrationError, match="expected '0.4.0'"): + migrate_0_4_0_to_0_5_0({"vcon": "0.5.0", "uuid": "a", "created_at": "2022-01-01T00:00:00Z"}) + with pytest.raises(MigrationError): + migrate_0_4_0_to_0_5_0("not json") + with pytest.raises(MigrationError): + migrate_0_4_0_to_0_5_0([1]) + + +class TestT1Version: + def test_vcon_parameter(self): + out, report = migrate(v04()) + assert out["vcon"] == "0.5.0" + + def test_missing_version_is_set_and_reported(self): + d = v04() + del d["vcon"] + out, report = migrate_0_4_0_to_0_5_0(d) + assert out["vcon"] == "0.5.0" + assert any(e.code == "AMB-12" for e in report.inferred) + + +class TestT2Session: + def test_one_session_references_all_dialogs(self): + out, _ = migrate(v04(dialog=[rec(), text()])) + assert len(out["sessions"]) == 1 + assert out["sessions"][0]["dialog"] == [0, 1] + + def test_simple_call_matches_the_appendix_b_shape(self): + out, _ = migrate(v04(dialog=[rec(parties=[0, 1])])) + assert out["sessions"] == [{"start": T0, "duration": 10, "parties": [0, 1], "dialog": [0]}] + + def test_no_dialog_means_no_session(self): + out, _ = migrate(v04()) + assert "sessions" not in out and "events" not in out + + def test_removed_positions_are_skipped_in_the_dialog_list(self): + out, _ = migrate(v04(dialog=[rec(), {"type": "recording-set", "recordings": [0], "start": T0}, text()])) + assert out["sessions"][0]["dialog"] == [0, 2] + + def test_session_start_and_duration_are_derived_and_reported(self): + d = v04(dialog=[rec(), text(duration=5)]) + out, report = migrate(d) + assert out["sessions"][0]["start"] == T0 + assert out["sessions"][0]["duration"] == 39 # T0 .. (T1 + 5s) = 34s + 5s + assert any("start/duration derived" in e.message for e in report.inferred) + + def test_text_only_session_has_no_duration(self): + out, _ = migrate(v04(dialog=[text()])) + assert "duration" not in out["sessions"][0] + + +class TestT3PartyHistory: + HISTORY = [ + {"party": 0, "time": T0, "event": "join"}, + {"party": 1, "time": T0, "event": "join"}, + {"party": 1, "time": T1, "event": "hold"}, + {"party": 0, "time": T1, "event": "drop"}, + ] + + def test_entries_become_events_with_event_renamed_type(self): + out, _ = migrate(v04(dialog=[rec(party_history=self.HISTORY)])) + assert out["events"] == [ + {"type": "join", "time": T0, "sessions": 0, "party": 0}, + {"type": "join", "time": T0, "sessions": 0, "party": 1}, + {"type": "hold", "time": T1, "sessions": 0, "party": 1}, + {"type": "drop", "time": T1, "sessions": 0, "party": 0}, + ] + assert "party_history" not in out["dialog"][0] + + def test_events_do_not_reference_the_dialog(self): + out, _ = migrate(v04(dialog=[rec(party_history=self.HISTORY)])) + assert all("dialog" not in e for e in out["events"]) + + def test_button_survives_on_key_events(self): + out, _ = migrate(v04(dialog=[rec(party_history=[{"party": 0, "time": T0, "event": "keydown", "button": "5"}])])) + assert out["events"][0] == {"type": "keydown", "time": T0, "sessions": 0, "party": 0, "button": "5"} + + def test_dialog_in_two_sessions_lists_both(self): + d = v04(dialog=[rec(party_history=self.HISTORY[:1]), {"type": "recording-set", "recordings": [0], "start": T0}]) + out, report = migrate(d) + assert out["events"][0]["sessions"] == [0, 1] + assert any(e.code == "AMB-3" for e in report.inferred) + + def test_missing_party_uses_empty_party_object_or_raises_in_strict(self): + d = v04(dialog=[rec(party_history=[{"time": T0, "event": "join"}])]) + out, report = migrate_0_4_0_to_0_5_0(d) + assert out["parties"][out["events"][0]["party"]] == {} + assert report.fallbacks + with pytest.raises(MigrationError, match="no party"): + migrate_0_4_0_to_0_5_0(d, strict=True) + + def test_missing_time_falls_back_to_dialog_start(self): + d = v04(dialog=[rec(party_history=[{"party": 0, "event": "join"}])]) + out, report = migrate_0_4_0_to_0_5_0(d) + assert out["events"][0]["time"] == T0 + assert report.fallbacks + with pytest.raises(MigrationError): + migrate_0_4_0_to_0_5_0(d, strict=True) + + +class TestT4TransferToEvents: + def base(self, transfer): + return v04(dialog=[ + rec(), # 0 original call + rec(start=T1, parties=[1, 2]), # 1 consultation call + rec(start=T2, parties=[0, 2]), # 2 target call + transfer, # 3 transfer dialog + ]) + + def test_blind_transfer(self): + d = self.base({"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 0, "target_dialog": 2}) + out, report = migrate(d) + assert [e["type"] for e in out["events"]] == ["blind-transfer"] + e = out["events"][0] + assert e["party"] == 1 and e["transferee"] == 0 and e["transfer_target"] == 2 + assert e["time"] == T2 + assert "consultation" not in e + # original / target are Sessions that list the right Dialogs + assert out["sessions"][e["sessions"]]["dialog"] == [0] + assert out["sessions"][e["target_session"]]["dialog"] == [2] + assert out["dialog"][3] == {} + assert 3 not in [i for s in out["sessions"] for i in s.get("dialog", [])] + + def test_consultative_transfer_emits_two_events_sharing_the_consultation_session(self): + d = self.base({"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 0, "consultation": 1, "target_dialog": 2}) + out, _ = migrate(d) + assert [e["type"] for e in out["events"]] == ["consultation-start", "consultative-transfer"] + cs, ct = out["events"] + assert cs["consultation"] == ct["consultation"] + assert out["sessions"][cs["consultation"]]["dialog"] == [1] + assert out["sessions"][ct["target_session"]]["dialog"] == [2] + assert cs["sessions"] == ct["sessions"] + assert "target_session" not in cs + assert ct["party"] == cs["party"] == 1 # transferor becomes party + + def test_transfer_to_recording_set_reuses_its_session(self): + d = v04(dialog=[ + rec(), rec(start=T2), + {"type": "recording-set", "start": T0, "recordings": [0], "parties": [0, 1]}, + {"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 2, "target_dialog": 1}, + ]) + out, _ = migrate(d) + e = out["events"][0] + assert out["sessions"][e["sessions"]]["dialog"] == [0] + assert e["sessions"] == 1 # the recording-set's Session + + def test_time_from_other_source_is_reported(self): + d = self.base({"type": "transfer", "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 0, "target_dialog": 2}) + out, report = migrate(d) + assert out["events"][0]["time"] == T2 + entries = [e for e in report.inferred if e.code == "AMB-7" and "Event time taken from" in e.message] + assert entries and "target dialog[2]" in entries[0].message + + def test_consultation_time_comes_from_consultation_call(self): + d = self.base({"type": "transfer", "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 0, "consultation": 1, "target_dialog": 2}) + out, report = migrate(d) + assert out["events"][0]["time"] == T1 # consultation-start: start of consultation call + assert out["events"][1]["time"] == T2 # transfer: start of target call + assert len([e for e in report.inferred if "Event time taken from" in e.message]) == 2 + + def test_no_time_source_falls_back_to_created_at_or_raises(self): + d = v04(dialog=[rec(), {"type": "transfer", "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 0}]) + out, report = migrate_0_4_0_to_0_5_0(d) + assert out["events"][0]["time"] == d["created_at"] + assert any("created_at" in e.message for e in report.fallbacks) + with pytest.raises(MigrationError, match="no start and no other time source"): + migrate_0_4_0_to_0_5_0(d, strict=True) + + def test_no_time_and_no_created_at_always_raises(self): + d = v04(dialog=[rec(), {"type": "transfer", "transferee": 0, "transferor": 1, "transfer_target": 2, "original": 0}]) + del d["created_at"] + with pytest.raises(MigrationError, match="no time can be sourced"): + migrate_0_4_0_to_0_5_0(d) + + def test_abandoned_transfer(self): + d = self.base({"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, "original": 0}) + out, report = migrate(d) + e = out["events"][0] + assert e["type"] == "transfer-abandoned" + assert "transfer_target" not in e and "target_session" not in e + assert any(x.code == "AMB-7" for x in report.inferred) + + def test_target_not_captured_gets_placeholder_session(self): + d = self.base({"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 0}) + out, report = migrate(d) + e = out["events"][0] + assert e["type"] == "blind-transfer" + assert out["sessions"][e["target_session"]] == {} + assert any("placeholder Session" in x.message for x in report.inferred) + + def test_missing_transferor_uses_empty_party_or_raises_in_strict(self): + t = {"type": "transfer", "start": T2, "transferee": 0, "transfer_target": 2, "original": 0, "target_dialog": 2} + out, report = migrate_0_4_0_to_0_5_0(self.base(t)) + assert out["parties"][out["events"][0]["party"]] == {} + assert report.fallbacks + with pytest.raises(MigrationError, match="no transferor"): + migrate_0_4_0_to_0_5_0(self.base(t), strict=True) + + def test_missing_original_gets_placeholder_session_or_raises(self): + t = {"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, "transfer_target": 2, "target_dialog": 2} + out, report = migrate_0_4_0_to_0_5_0(self.base(t)) + assert out["sessions"][out["events"][0]["sessions"]] == {} + assert report.fallbacks + with pytest.raises(MigrationError): + migrate_0_4_0_to_0_5_0(self.base(t), strict=True) + + def test_unmapped_transfer_content_is_kept_in_the_report(self): + t = {"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 0, "target_dialog": 2, "transfer": {"reason": "forwarded"}} + out, report = migrate_0_4_0_to_0_5_0(self.base(t)) + assert report.removed_dialogs[3]["transfer"] == {"reason": "forwarded"} + assert any("no Event equivalent" in e.message for e in report.unresolved) + + def test_events_pass_the_parameter_table(self): + t = {"type": "transfer", "start": T2, "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 0, "consultation": 1, "target_dialog": 2} + out, report = migrate(self.base(t)) + assert not report.unresolved + assert Vcon(out).is_valid() == (True, []) + + +class TestT6Originator: + def test_originator_moves_to_the_session_when_not_first_party(self): + out, _ = migrate(v04(dialog=[rec(parties=[0, 1], originator=1)])) + assert out["sessions"][0]["originator"] == 1 + assert "originator" not in out["dialog"][0] + + def test_originator_dropped_when_it_is_the_first_party(self): + out, _ = migrate(v04(dialog=[rec(parties=[0, 1], originator=0)])) + assert "originator" not in out["sessions"][0] + assert "originator" not in out["dialog"][0] + + def test_conflicting_originators_are_reported(self): + d = v04(dialog=[rec(parties=[0, 1, 2], originator=1), text(parties=[0, 1, 2], originator=2)]) + out, report = migrate(d) + assert out["sessions"][0]["originator"] == 1 + assert any("different originators" in e.message for e in report.unresolved) + + +class TestT7RecordingSet: + def d(self): + return v04(dialog=[ + rec(recording_set=2, start=T0, duration=4, parties=[0, 1]), + rec(recording_set=2, start=T0, duration=6, parties=[1, 0]), + {"type": "recording-set", "start": T0, "duration": 7, "parties": [0, 1], "originator": 1, + "session_id": {"local": "l", "remote": "r"}, "recordings": [0, 1]}, + ]) + + def test_recording_set_becomes_a_session(self): + out, report = migrate(self.d()) + s = out["sessions"][1] + assert s["dialog"] == [0, 1] + assert s["start"] == T0 and s["duration"] == 7 and s["parties"] == [0, 1] + assert s["originator"] == 1 + assert s["session_id"] == {"local": "l", "remote": "r"} + assert any(e.code == "AMB-4" for e in report.inferred) + assert any(e.code == "AMB-1" for e in report.unresolved) + + def test_recording_set_parameter_is_removed_from_recordings(self): + out, _ = migrate(self.d()) + assert all("recording_set" not in x for x in out["dialog"][:2]) + + def test_recording_set_dialog_is_blanked_and_unlisted(self): + out, report = migrate(self.d()) + assert out["dialog"][2] == {} + assert report.removed_dialogs[2]["type"] == "recording-set" + assert all(2 not in s.get("dialog", []) for s in out["sessions"]) + + +class TestT8T9Parties: + def test_text_dialog_parties_reduce_to_sender_receivers_go_to_session(self): + out, _ = migrate(v04(dialog=[text(parties=[0, 1, 2])])) + assert out["dialog"][0]["parties"] == [0] + assert out["sessions"][0]["parties"] == [0, 1, 2] + + def test_sender_is_the_originator_when_set(self): + out, _ = migrate(v04(dialog=[text(parties=[0, 1, 2], originator=2)])) + assert out["dialog"][0]["parties"] == [2] + assert out["sessions"][0]["parties"] == [0, 1, 2] + assert out["sessions"][0]["originator"] == 2 + + def test_thread_with_different_receivers_is_reported_not_split(self): + d = v04(dialog=[text(parties=[0, 1]), text(parties=[1, 0, 2])]) + out, report = migrate(d) + assert len(out["sessions"]) == 1 + assert [x["parties"] for x in out["dialog"]] == [[0], [1]] + assert out["sessions"][0]["parties"] == [0, 1, 2] + assert sum(1 for e in report.unresolved if e.code == "AMB-5") >= 1 + + def test_incomplete_dialog_parties_reduce_to_originator_or_first(self): + inc = {"type": "incomplete", "start": T0, "parties": [2, 0], "disposition": "no-answer"} + out, _ = migrate(v04(dialog=[inc])) + assert out["dialog"][0]["parties"] == [2] + assert out["sessions"][0]["parties"] == [2, 0] + inc2 = dict(inc, originator=0) + out2, _ = migrate(v04(dialog=[inc2])) + assert out2["dialog"][0]["parties"] == [0] + assert out2["sessions"][0]["originator"] == 0 + + def test_recording_parties_are_kept_and_unioned_into_the_session(self): + out, report = migrate(v04(dialog=[rec(parties=[0, 1]), rec(parties=[1, 2])])) + assert [x["parties"] for x in out["dialog"]] == [[0, 1], [1, 2]] + assert out["sessions"][0]["parties"] == [0, 1, 2] + assert any(e.code == "AMB-6" for e in report.inferred) + + def test_text_without_parties_is_reported(self): + t = text() + del t["parties"] + _, report = migrate_0_4_0_to_0_5_0(v04(dialog=[t])) + assert any("has no parties" in e.message for e in report.unresolved) + + +class TestT10EmptyDialogsAndAMB2: + def test_removed_dialogs_become_empty_objects_in_place(self): + d = v04(dialog=[ + rec(), + {"type": "transfer", "start": T1, "transferee": 0, "transferor": 1, "transfer_target": 2, "original": 0, "target_dialog": 3}, + text(), + rec(start=T2), + ]) + out, report = migrate(d) + assert len(out["dialog"]) == 4 + assert out["dialog"][1] == {} + assert out["dialog"][2]["type"] == "text" and out["dialog"][3]["start"] == T2 + assert set(report.removed_dialogs) == {1} + + def test_analysis_on_recording_set_is_repointed(self): + d = v04( + dialog=[rec(recording_set=1), {"type": "recording-set", "start": T0, "recordings": [0]}], + analysis=[{"type": "summary", "dialog": 1, "vendor": "v", "body": "s", "encoding": "none"}], + ) + out, report = migrate(d) + a = out["analysis"][0] + assert a["dialog"] == 0 and a["sessions"] == 1 + assert any(e.code == "AMB-2" for e in report.inferred) + + def test_analysis_dialog_list_is_expanded(self): + d = v04( + dialog=[rec(recording_set=2), rec(), {"type": "recording-set", "start": T0, "recordings": [0]}], + analysis=[{"type": "summary", "dialog": [1, 2], "vendor": "v", "body": "s", "encoding": "none"}], + ) + out, _ = migrate(d) + assert out["analysis"][0]["dialog"] == [1, 0] + assert out["analysis"][0]["sessions"] == 1 + + def test_attachment_on_removed_dialog_gets_session(self): + d = v04( + dialog=[rec(recording_set=1), {"type": "recording-set", "start": T0, "recordings": [0]}], + attachments=[{"purpose": "notes", "start": T0, "party": 0, "dialog": 1, "body": "n", "encoding": "none", "mediatype": "text/plain"}], + ) + out, _ = migrate(d) + att = out["attachments"][0] + assert "dialog" not in att and att["session"] == 1 + + def test_analysis_on_transfer_dialog_goes_to_the_original_session(self): + d = v04( + dialog=[rec(), {"type": "transfer", "start": T1, "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 0, "target_dialog": 0}], + analysis=[{"type": "report", "dialog": 1, "vendor": "v", "body": "why", "encoding": "none"}], + ) + out, _ = migrate(d) + a = out["analysis"][0] + assert "dialog" not in a + assert a["sessions"] == out["events"][0]["sessions"] + + def test_references_to_kept_dialogs_are_untouched(self): + d = v04( + dialog=[rec(), text()], + analysis=[{"type": "summary", "dialog": [0, 1], "vendor": "v", "body": "s", "encoding": "none"}], + attachments=[{"purpose": "notes", "start": T0, "party": 0, "dialog": 1, "body": "n", "encoding": "none", "mediatype": "text/plain"}], + ) + out, report = migrate(d) + assert out["analysis"][0]["dialog"] == [0, 1] and "sessions" not in out["analysis"][0] + assert out["attachments"][0]["dialog"] == 1 + assert not [e for e in report.entries if e.step == "T10b"] + + +class TestIndexStability: + """Code that drops empty Dialogs before indexing must not break references.""" + + IDENT = ("type", "start", "duration", "mediatype", "body", "url", "disposition") + + def source(self): + return v04( + dialog=[ + rec(), # 0 + {"type": "recording-set", "start": T0, "recordings": [0, 3], "parties": [0, 1]}, # 1 + {"type": "transfer", "start": T1, "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 1, "consultation": 4, "target_dialog": 3}, # 2 + rec(start=T2, parties=[0, 2], party_history=[{"party": 2, "time": T2, "event": "join"}]), # 3 + text(parties=[1, 2]), # 4 + {"type": "incomplete", "start": T2, "parties": [2, 0], "disposition": "busy"}, # 5 + ], + analysis=[ + {"type": "a0", "dialog": 0, "vendor": "v", "body": "x", "encoding": "none"}, + {"type": "a3", "dialog": [3, 4], "vendor": "v", "body": "x", "encoding": "none"}, + {"type": "a5", "dialog": 5, "vendor": "v", "body": "x", "encoding": "none"}, + ], + attachments=[ + {"purpose": "p4", "start": T0, "party": 0, "dialog": 4, "body": "x", "encoding": "none", "mediatype": "text/plain"}, + {"purpose": "p5", "start": T0, "party": 0, "dialog": 5, "body": "x", "encoding": "none", "mediatype": "text/plain"}, + ], + ) + + def ident(self, d): + return {k: d[k] for k in self.IDENT if k in d} + + def test_dialog_array_length_and_positions_do_not_change(self): + src = self.source() + out, report = migrate(src) + assert len(out["dialog"]) == len(src["dialog"]) + removed = set(report.removed_dialogs) + assert removed == {1, 2} + for i, (a, b) in enumerate(zip(src["dialog"], out["dialog"])): + if i in removed: + assert b == {} + else: + assert self.ident(b) == self.ident(a), i + + def test_analysis_and_attachment_references_resolve_to_the_same_dialog(self): + src = self.source() + out, _ = migrate(src) + for a_src, a_out in zip(src["analysis"], out["analysis"]): + before = a_src["dialog"] if isinstance(a_src["dialog"], list) else [a_src["dialog"]] + after = a_out.get("dialog") + after = [] if after is None else (after if isinstance(after, list) else [after]) + for i in before: + if src["dialog"][i]["type"] in ("transfer", "recording-set"): + continue + assert i in after + assert self.ident(out["dialog"][i]) == self.ident(src["dialog"][i]) + assert all(out["dialog"][i] != {} for i in after) + for t_src, t_out in zip(src["attachments"], out["attachments"]): + i = t_src["dialog"] + assert t_out["dialog"] == i + assert self.ident(out["dialog"][i]) == self.ident(src["dialog"][i]) + + def test_session_and_event_references_resolve_to_the_intended_dialogs(self): + src = self.source() + out, _ = migrate(src) + # Every Session lists only non-empty Dialogs, found by absolute index. + for s in out["sessions"]: + for i in s.get("dialog", []): + assert out["dialog"][i] != {} + # party_history of dialog 3 became an event whose Session lists dialog 3. + join = next(e for e in out["events"] if e["type"] == "join") + sessions = join["sessions"] if isinstance(join["sessions"], list) else [join["sessions"]] + assert any(3 in out["sessions"][n]["dialog"] for n in sessions) + # Transfer events: original = recording-set Session (recordings 0 and 3), target = dialog 3, + # consultation = dialog 4. + by_type = {e["type"]: e for e in out["events"] if e["type"] != "join"} + assert out["sessions"][by_type["consultative-transfer"]["sessions"]]["dialog"] == [0, 3] + assert out["sessions"][by_type["consultative-transfer"]["target_session"]]["dialog"] == [3] + assert out["sessions"][by_type["consultation-start"]["consultation"]]["dialog"] == [4] + + def test_filtering_empty_dialogs_first_would_have_broken_the_references(self): + """This is why the empty placeholders exist: the naive filtered list shifts every later index.""" + src = self.source() + out, _ = migrate(src) + filtered = [d for d in out["dialog"] if d] + # Positions after the first removed Dialog move, so absolute indices in + # Sessions, Events, analysis and attachments no longer line up. + assert filtered[3]["type"] != out["dialog"][3]["type"] or filtered[1] != out["dialog"][1] + # The migrated array itself is positionally correct for every reference. + assert out["dialog"][4]["type"] == "text" and out["dialog"][5]["type"] == "incomplete" + for s in out["sessions"]: + for i in s.get("dialog", []): + assert i < len(out["dialog"]) + + def test_every_reference_in_the_result_resolves(self): + out, report = migrate(self.source()) + assert Vcon(out).is_valid() == (True, []) + assert not [e for e in report.unresolved if e.step == "post"] + + +class TestT11T12Renames: + def test_redacted_to_redacted_from(self): + r = {"uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", "type": "PII Redaction", "url": "https://e.com/u", "content_hash": "sha512-x"} + out, _ = migrate(v04(redacted=r)) + assert out["redacted_from"] == r and "redacted" not in out + + def test_amended_to_amended_from(self): + a = {"uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46"} + out, _ = migrate(v04(amended=a)) + assert out["amended_from"] == a and "amended" not in out + + def test_rename_keeps_position(self): + out, _ = migrate(v04(amended={"uuid": "x"})) + keys = list(out) + assert keys.index("amended_from") == list(v04(amended={"uuid": "x"})).index("amended") + + +class TestT13SignedInput: + def signed(self, payload, alg="RS256"): + b = lambda o: base64.urlsafe_b64encode(json.dumps(o).encode()).rstrip(b"=").decode() + return {"payload": b(payload), "signatures": [{"protected": b({"alg": alg}), "header": {"uuid": "x"}, "signature": "AAAA"}]} + + def test_signed_input_is_migrated_as_the_unsigned_payload(self): + out, report = migrate(self.signed(v04(dialog=[rec()]))) + assert "signatures" not in out and "payload" not in out + assert out["vcon"] == "0.5.0" and out["sessions"] + assert report.resign_required is True + assert any("Re-signing is required" in e.message for e in report.unresolved) + + def test_alg_none_is_called_out(self): + _, report = migrate(self.signed(v04(), alg="none")) + assert any("alg 'none'" in e.message for e in report.unresolved) + + def test_unsigned_input_does_not_require_resigning(self): + assert migrate(v04())[1].resign_required is False + + def test_bad_payload_raises(self): + with pytest.raises(MigrationError, match="payload"): + migrate_0_4_0_to_0_5_0({"payload": "!!!", "signatures": []}) + + def test_encrypted_input_raises(self): + with pytest.raises(MigrationError, match="decrypt"): + migrate_0_4_0_to_0_5_0({"protected": "x", "ciphertext": "y", "recipients": []}) + + def test_signed_payload_must_be_0_4_0(self): + with pytest.raises(MigrationError, match="expected '0.4.0'"): + migrate_0_4_0_to_0_5_0(self.signed({"vcon": "0.5.0", "uuid": "a", "created_at": "2022-01-01T00:00:00Z"})) + + def test_vcon_load_of_a_library_signed_0_4_0_document(self): + payload = v04(dialog=[rec()]) + signed = self.signed(payload) + v = Vcon(signed) + assert v.vcon == "0.5.0" + assert v.migration_report.resign_required + + +class TestT14Extensions: + LB = {"purpose": "lawful_basis", "start": T0, "party": 0, "dialog": 0, "body": {}, "encoding": "json", "mediatype": "application/json"} + + def test_extensions_in_use_are_added(self): + out, report = migrate(v04(dialog=[rec()], attachments=[self.LB])) + assert out["extensions"] == ["lawful_basis"] + assert any("lawful_basis" in e.message for e in report.inferred) + + def test_existing_list_is_kept_and_extended(self): + out, _ = migrate(v04(dialog=[rec()], attachments=[self.LB], extensions=["x"], critical=["y"])) + assert out["extensions"] == ["x", "lawful_basis", "y"] + + def test_wtf_analysis_adds_wtf(self): + out, _ = migrate(v04(dialog=[rec()], analysis=[{"type": "wtf_transcription", "dialog": 0, "vendor": "v", "body": {}, "encoding": "json"}])) + assert "wtf_transcription" in out["extensions"] + + def test_unidentifiable_extension_use_is_reported_not_invented(self): + d = v04(dialog=[rec(encoding="gzip", body="x")]) + out, report = migrate_0_4_0_to_0_5_0(d) + assert "extensions" not in out + assert any("cannot be identified" in e.message for e in report.unresolved) + + def test_no_extension_changes_when_none_in_use(self): + out, _ = migrate(v04(dialog=[rec()])) + assert "extensions" not in out + + +class TestLawfulBasisSurvivesMigration: + LB = {"purpose": "lawful_basis", "start": T0, "party": 0, "dialog": 0, "body": {"lawful_basis": "consent"}, + "encoding": "json", "mediatype": "application/json"} + + def test_attachment_is_kept_unchanged_and_the_gap_is_noted(self): + out, report = migrate(v04(dialog=[rec()], attachments=[copy.deepcopy(self.LB)])) + assert out["attachments"] == [self.LB] + assert "session" not in out["attachments"][0] + notes = [e for e in report.notes if "lawful_basis attachment scoped by dialog only" in e.message] + assert len(notes) == 1 + assert Vcon(out).find_lawful_basis_attachments() + + def test_attachment_that_already_has_a_session_is_not_flagged(self): + att = dict(self.LB, session=[0]) + _, report = migrate(v04(dialog=[rec()], attachments=[att])) + assert not [e for e in report.notes if "lawful_basis" in e.message] + + def test_attachment_on_a_removed_dialog_gets_the_session_of_the_recording_set(self): + att = dict(self.LB, dialog=1) + d = v04(dialog=[rec(recording_set=1), {"type": "recording-set", "start": T0, "recordings": [0]}], attachments=[att]) + out, _ = migrate(d) + assert out["attachments"][0]["session"] == 1 and "dialog" not in out["attachments"][0] + assert out["attachments"][0]["purpose"] == "lawful_basis" + + +class TestT15: + def test_noted_for_signed_input(self): + b = lambda o: base64.urlsafe_b64encode(json.dumps(o).encode()).rstrip(b"=").decode() + _, report = migrate_0_4_0_to_0_5_0({"payload": b(v04()), "signatures": []}) + assert any(e.step == "T15" for e in report.notes) + + +class TestReport: + def test_report_structure_and_serialization(self): + _, report = migrate(v04(dialog=[rec(), text(parties=[0, 1, 2])])) + assert isinstance(report, MigrationReport) + assert report.source_version == "0.4.0" and report.target_version == "0.5.0" + d = json.loads(json.dumps(report.to_dict())) + assert d["entries"] and d["steps_run"] + assert "inferred" in report.summary() + + def test_unpacks_as_a_pair(self): + result = migrate_0_4_0_to_0_5_0(v04()) + out, report = result + assert result.vcon is out and result.report is report + + def test_post_migration_problems_are_reported(self): + # An attachment that already lacked party was invalid in 0.4.0 and stays so. + d = v04(dialog=[rec()], attachments=[{"purpose": "x", "body": "b", "encoding": "none"}]) + _, report = migrate_0_4_0_to_0_5_0(d) + assert any(e.step == "post" and "party" in e.message for e in report.unresolved) + + def test_every_entry_has_a_known_kind(self): + _, report = migrate(v04(dialog=[rec(originator=1), text(parties=[0, 1, 2])])) + assert {e.kind for e in report.entries} <= {"inferred", "fallback", "unresolved", "info"} + + +class TestReadersAcceptBothVersions: + def test_0_4_0_json_is_migrated_on_load(self): + v = Vcon.build_from_json(json.dumps(v04(dialog=[rec(originator=1)]))) + assert v.vcon == "0.5.0" + assert v.migration_report is not None + assert v.sessions[0]["originator"] == 1 + assert v.is_valid() == (True, []) + + def test_0_5_0_input_is_not_touched(self): + src = {"vcon": "0.5.0", "uuid": "a", "created_at": "2022-01-01T00:00:00Z", "parties": [], "dialog": [{}], "sessions": [{}]} + v = Vcon(copy.deepcopy(src)) + assert v.migration_report is None + assert v.vcon_dict["dialog"] == [{}] and v.vcon_dict["sessions"] == [{}] + + def test_input_without_vcon_is_not_migrated_on_load(self): + d = v04(dialog=[rec(originator=1)]) + del d["vcon"] + v = Vcon(d) + assert v.migration_report is None + assert v.vcon_dict["dialog"][0]["originator"] == 1 + + def test_load_from_file_migrates(self, tmp_path): + p = tmp_path / "old.json" + p.write_text(json.dumps(v04(dialog=[rec()]))) + v = Vcon.load(str(p)) + assert v.vcon == "0.5.0" and v.migration_report + + def test_migrate_legacy_false_keeps_the_raw_document(self): + v = Vcon(v04(dialog=[rec()]), migrate_legacy=False) + assert v.vcon == "0.4.0" and v.migration_report is None + assert not v.is_valid()[0] + + def test_explicit_call_returns_a_vcon_with_report(self): + d = v04(dialog=[rec()]) + del d["vcon"] + v = Vcon.migrate_0_4_0_to_0_5_0(d) + assert v.vcon == "0.5.0" and v.migration_report and v.sessions + + def test_strict_migration_raises_through_the_constructor(self): + d = v04(dialog=[rec(), {"type": "transfer", "transferee": 0, "transfer_target": 2, "original": 0}]) + with pytest.raises(MigrationError): + Vcon(d, strict_migration=True) + + def test_writers_emit_0_5_0(self): + v = Vcon.build_from_json(json.dumps(v04(dialog=[rec()]))) + assert json.loads(v.to_json())["vcon"] == "0.5.0" diff --git a/tests/test_party.py b/tests/test_party.py index b301891..c79b8e1 100644 --- a/tests/test_party.py +++ b/tests/test_party.py @@ -1,5 +1,5 @@ from datetime import datetime -from vcon.party import Party, PartyHistory +from vcon.party import Party from vcon.civic_address import CivicAddress import pytest @@ -54,48 +54,6 @@ def test_party_with_civic_address(): assert party.civicaddress == address -def test_party_history(): - """Test PartyHistory class.""" - party_history = PartyHistory(0, "join", datetime.now()) - assert party_history.party == 0 - assert party_history.event == "join" - assert isinstance(party_history.time, datetime) - - -def test_party_history_to_dict(): - """Test PartyHistory to_dict method with ISO 8601 time serialization.""" - test_time = datetime(2023, 1, 15, 14, 30, 45, 123456) - party_history = PartyHistory(1, "drop", test_time) - - result = party_history.to_dict() - expected = { - "party": 1, - "event": "drop", - "time": "2023-01-15T14:30:45.123456" - } - - assert result == expected - assert isinstance(result["time"], str) - - -def test_party_history_valid_events(): - """Test that all valid party history events are accepted.""" - from datetime import datetime - - # Test all valid events - valid_events = [ - "join", "drop", "hold", "unhold", "mute", "unmute" - ] - - for event in valid_events: - party_history = PartyHistory(0, event, datetime.now()) - assert party_history.event == event - - # Test invalid event - with pytest.raises(ValueError, match="Invalid event"): - PartyHistory(0, "invalid", datetime.now()) - - def test_party_new_fields(): """Test the new required fields for Party.""" party = Party( diff --git a/tests/test_schema_compliance.py b/tests/test_schema_compliance.py index 5aac324..df04c9f 100644 --- a/tests/test_schema_compliance.py +++ b/tests/test_schema_compliance.py @@ -2,7 +2,7 @@ The schema is vendored at tests/schema/vcon_json_schema.json (see tests/schema/SOURCE.md for provenance) and matches the appendix schema of -draft-ietf-vcon-vcon-core-04. This test builds a vCon using only the +draft-ietf-vcon-vcon-core-05 (Appendix C). This test builds a vCon using only the library's public helpers -- add_tag, add_lawful_basis_attachment, add_dialog (with and without inline audio), and add_attachment -- and checks that the resulting dict validates with no post-processing. @@ -18,6 +18,8 @@ from vcon import Vcon from vcon.party import Party from vcon.dialog import Dialog, b64url_encode +from vcon.session import Session +from vcon.event import Event SCHEMA_PATH = Path(__file__).parent / "schema" / "vcon_json_schema.json" @@ -33,16 +35,20 @@ def test_vcon_built_with_public_helpers_validates_against_wg_schema(): vcon.add_party(Party(name="Alice", role="caller")) vcon.add_party(Party(name="Bob", role="agent")) + # One Session for the conversation; Dialog parties are contributors only, + # the receivers are the Session parties. + vcon.add_session(Session(start=vcon.created_at, parties=[0, 1])) + # Dialog without inline audio (plain text). text_dialog = Dialog( type="text", start=vcon.created_at, - parties=[0, 1], + parties=[0], body="Hello, how can I help?", encoding="none", mediatype="text/plain", ) - vcon.add_dialog(text_dialog) + vcon.add_dialog(text_dialog, session=0) # Dialog with inline audio, base64url-encoded per -04 (unpadded). audio_bytes = b"RIFF\x00\x00\x00\x00WAVEfmt fake audio payload" @@ -54,7 +60,7 @@ def test_vcon_built_with_public_helpers_validates_against_wg_schema(): encoding="base64url", mediatype="audio/x-wav", ) - vcon.add_dialog(audio_dialog) + vcon.add_dialog(audio_dialog, session=0) vcon.add_tag("category", "support") vcon.add_tag("priority", "high") @@ -66,8 +72,8 @@ def test_vcon_built_with_public_helpers_validates_against_wg_schema(): {"purpose": "recording", "granted": True, "granted_at": vcon.created_at} ], party_index=0, - dialog_index=1, ) + vcon.add_event(Event(type="join", time=vcon.created_at, sessions=0, party=0)) vcon.add_attachment( purpose="notes", @@ -75,6 +81,7 @@ def test_vcon_built_with_public_helpers_validates_against_wg_schema(): encoding="json", party=1, dialog=0, + session=0, ) vcon_dict = vcon.to_dict() @@ -97,6 +104,7 @@ def test_legacy_string_tags_body_still_validates_after_add_tag(): vcon = Vcon.build_new() vcon.add_party(Party(name="Alice")) + vcon.add_session(Session(parties=[0])) # Simulate a vCon written under -02 conventions / by an older release: # the tags attachment body is a JSON-encoded string, not a list. @@ -108,7 +116,7 @@ def test_legacy_string_tags_body_still_validates_after_add_tag(): "mediatype": "application/json", "start": vcon.created_at, "party": 0, - "dialog": 0, + "session": [0], } ) diff --git a/tests/test_session_event.py b/tests/test_session_event.py new file mode 100644 index 0000000..f2fb50e --- /dev/null +++ b/tests/test_session_event.py @@ -0,0 +1,281 @@ +"""Session, Session_Reference and Event Objects (core-05 sections 4.2 and 4.3).""" + +import pytest + +from vcon import Vcon, Dialog, Session, SessionReference, Event +from vcon.event import ( + EVENT_PARAMETER_RULES, + CORE_EVENT_TYPES, + validate_event, +) +from vcon.party import Party + +T = "2026-01-01T00:00:00Z" + + +def _valid_event(etype): + """A minimal valid Event dict for each core type.""" + base = {"type": etype, "time": T} + if etype == "channel-contributors": + return {**base, "dialog": 0, "channel": 0} + base.update({"sessions": 0, "party": 0}) + if etype in ("keydown", "keyup"): + base["button"] = "5" + elif etype == "consultation-start": + base.update(transferee=1, transfer_target=2, consultation=1) + elif etype == "blind-transfer": + base.update(transferee=1, transfer_target=2, target_session=1) + elif etype == "consultative-transfer": + base.update(transferee=1, transfer_target=2, consultation=1, target_session=2) + elif etype == "transfer-abandoned": + base.update(transferee=1) + return base + + +class TestSession: + def test_empty_session_is_allowed(self): + assert Session().to_dict() == {} + errors, _ = __import__("vcon.session", fromlist=["x"]).validate_session({}) + assert errors == [] + + def test_to_dict_fields(self): + s = Session( + start="2026-01-01T00:00:00Z", + duration=12.5, + parties=[0, 1], + originator=1, + session_id={"local": "a", "remote": "b"}, + sessions=[SessionReference(2, "child", "side call")], + dialog=[0, 1], + ) + d = s.to_dict() + assert d["parties"] == [0, 1] + assert d["originator"] == 1 + assert d["session_id"] == {"local": "a", "remote": "b"} + assert d["sessions"] == [{"session": 2, "type": "child", "description": "side call"}] + assert d["dialog"] == [0, 1] + + def test_session_reference_requires_type_and_index(self): + with pytest.raises(ValueError): + SessionReference(-1, "child") + with pytest.raises(ValueError): + SessionReference(0, "") + + def test_session_reference_validation(self): + vcon = Vcon.build_new() + vcon.add_session(Session(start=T, sessions=[{"session": 5, "type": "child"}])) + valid, errors = vcon.is_valid() + assert not valid + assert any("invalid session index: 5" in e for e in errors) + + def test_add_session_returns_index(self): + vcon = Vcon.build_new() + assert vcon.add_session(Session(start=T)) == 0 + assert vcon.add_session() == 1 + assert vcon.sessions == [{"start": "2026-01-01T00:00:00+00:00"}, {}] + + def test_session_dialog_index_checked(self): + vcon = Vcon.build_new() + vcon.add_session(Session(dialog=[3])) + valid, errors = vcon.is_valid() + assert not valid + assert any("invalid dialog index: 3" in e for e in errors) + + def test_session_party_index_checked(self): + vcon = Vcon.build_new() + vcon.add_party(Party(name="A")) + vcon.add_session(Session(parties=[0, 4])) + valid, errors = vcon.is_valid() + assert not valid + assert any("invalid party index: 4" in e for e in errors) + + def test_sessions_required_when_dialog_or_events_exist(self): + vcon = Vcon.build_new() + vcon.add_party(Party(name="A")) + vcon.add_dialog(Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none")) + valid, errors = vcon.is_valid() + assert not valid + assert any("At least one Session Object MUST exist" in e for e in errors) + + vcon2 = Vcon.build_new() + vcon2.add_party(Party(name="A")) + vcon2.add_event(Event(type="join", time=T, sessions=0, party=0)) + valid, errors = vcon2.is_valid() + assert any("At least one Session Object MUST exist" in e for e in errors) + + def test_add_dialog_to_session_and_unreferenced_dialog_warns(self): + vcon = Vcon.build_new() + vcon.add_party(Party(name="A")) + vcon.add_session(Session(start=T, parties=[0])) + idx = vcon.add_dialog( + Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none"), + session=0, + ) + assert idx == 0 + assert vcon.sessions[0]["dialog"] == [0] + assert vcon.is_valid() == (True, []) + vcon.add_dialog(Dialog.placeholder()) + assert vcon.is_valid()[0] # an empty Dialog needs no Session + vcon.add_dialog( + Dialog(type="text", start=T, parties=[0], body="y", mediatype="text/plain", encoding="none") + ) + assert any("not referenced by any Session" in w for w in vcon.get_validation_warnings()) + + +class TestEventTable: + @pytest.mark.parametrize("etype", CORE_EVENT_TYPES) + def test_minimal_valid_event_passes(self, etype): + errors, warnings = validate_event(_valid_event(etype)) + assert errors == [] + assert warnings == [] + + @pytest.mark.parametrize("etype", CORE_EVENT_TYPES) + def test_every_M_parameter_is_enforced(self, etype): + for param, code in EVENT_PARAMETER_RULES[etype].items(): + if code != "M": + continue + ev = _valid_event(etype) + del ev[param] + errors, _ = validate_event(ev) + assert any(param in e for e in errors), (etype, param, errors) + + @pytest.mark.parametrize("etype", CORE_EVENT_TYPES) + def test_every_X_parameter_is_rejected(self, etype): + sample = { + "sessions": 0, "party": 0, "dialog": 0, "channel": 0, "contributors": [0], + "button": "1", "transferee": 0, "transfer_target": 0, "consultation": 0, + "target_session": 0, + } + for param, code in EVENT_PARAMETER_RULES[etype].items(): + if code != "X": + continue + ev = _valid_event(etype) + ev[param] = sample[param] + errors, _ = validate_event(ev) + assert any(f"must not have field: {param}" in e for e in errors), (etype, param, errors) + + @pytest.mark.parametrize("etype", CORE_EVENT_TYPES) + def test_every_SN_parameter_warns(self, etype): + for param, code in EVENT_PARAMETER_RULES[etype].items(): + if code != "SN": + continue + ev = _valid_event(etype) + ev[param] = 0 + errors, warnings = validate_event(ev) + assert errors == [] + assert any(f"should not have field: {param}" in w for w in warnings) + + @pytest.mark.parametrize("etype", CORE_EVENT_TYPES) + def test_optional_parameters_are_accepted(self, etype): + for param, code in EVENT_PARAMETER_RULES[etype].items(): + if code != "O": + continue + ev = _valid_event(etype) + ev[param] = 1 if param != "contributors" else None + errors, warnings = validate_event(ev) + assert errors == [] and warnings == [], (etype, param) + + def test_table_matches_the_draft_for_transfer_types(self): + r = EVENT_PARAMETER_RULES + assert r["consultation-start"]["target_session"] == "X" + assert r["consultation-start"]["consultation"] == "M" + assert r["blind-transfer"]["consultation"] == "X" + assert r["blind-transfer"]["target_session"] == "M" + assert r["consultative-transfer"]["consultation"] == "M" + assert r["consultative-transfer"]["target_session"] == "M" + assert r["transfer-abandoned"]["transfer_target"] == "O" + assert r["transfer-abandoned"]["consultation"] == "O" + assert r["transfer-abandoned"]["target_session"] == "X" + assert r["channel-contributors"]["sessions"] == "X" + assert r["channel-contributors"]["party"] == "X" + assert r["keydown"]["button"] == "M" + assert r["join"]["button"] == "X" + + def test_transfer_sessions_must_be_a_single_index(self): + ev = _valid_event("blind-transfer") + ev["sessions"] = [0] + errors, _ = validate_event(ev) + assert any("single session index" in e for e in errors) + + def test_party_event_accepts_session_list_and_bare_integer(self): + for sessions in (0, [0, 1]): + ev = _valid_event("join") + ev["sessions"] = sessions + assert validate_event(ev)[0] == [] + + def test_time_must_parse(self): + ev = _valid_event("join") + ev["time"] = "not a time" + assert any("invalid 'time'" in e for e in validate_event(ev)[0]) + del ev["time"] + assert any("missing required field: time" in e for e in validate_event(ev)[0]) + + def test_unknown_type_checked_for_type_and_time_only(self): + errors, warnings = validate_event({"type": "tool-call", "time": T, "tool_name": "x"}) + assert errors == [] and warnings == [] + + def test_channel_contributors_must_reference_recording_dialog(self): + vcon = Vcon.build_new() + vcon.add_party(Party(name="A")) + vcon.add_session(Session(start=T, parties=[0])) + vcon.add_dialog( + Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none"), + session=0, + ) + vcon.add_event(Event(type="channel-contributors", time=T, dialog=0, channel=0, contributors=0)) + valid, errors = vcon.is_valid() + assert not valid + assert any("must reference a 'recording' Dialog" in e for e in errors) + + +class TestEventClass: + def test_blind_transfer_roundtrip(self): + e = Event( + type="blind-transfer", time=T, sessions=0, party=1, + transferee=0, transfer_target=2, target_session=1, + ) + assert e.to_dict() == { + "type": "blind-transfer", "time": T, "sessions": 0, "party": 1, + "transferee": 0, "transfer_target": 2, "target_session": 1, + } + assert Event.from_dict(e.to_dict()).to_dict() == e.to_dict() + + def test_constructor_enforces_the_table(self): + with pytest.raises(ValueError, match="button"): + Event(type="join", time=T, sessions=0, party=0, button="1") + with pytest.raises(ValueError, match="missing required field: button"): + Event(type="keydown", time=T, sessions=0, party=0) + with pytest.raises(ValueError, match="consultation"): + Event(type="blind-transfer", time=T, sessions=0, party=0, transferee=1, + transfer_target=2, target_session=1, consultation=1) + + def test_extension_event_type_and_params(self): + e = Event(type="tool-call", time=T, tool_name="search") + assert e.to_dict()["tool_name"] == "search" + + def test_vcon_add_event_and_validation_of_plain_dicts(self): + vcon = Vcon.build_new() + vcon.add_party(Party(name="A")) + vcon.add_session(Session(start=T, parties=[0])) + i = vcon.add_event(Event(type="join", time=T, sessions=0, party=0)) + assert i == 0 and vcon.events[0]["type"] == "join" + assert vcon.is_valid() == (True, []) + vcon.add_event({"type": "join", "time": T, "sessions": 0, "party": 0, "button": "1"}) + valid, errors = vcon.is_valid() + assert not valid + assert any("Event at index 1" in e and "button" in e for e in errors) + vcon.add_event({"type": "join", "time": T, "sessions": 7, "party": 9}) + errors = vcon.is_valid()[1] + assert any("invalid session index: 7" in e for e in errors) + assert any("invalid party index: 9" in e for e in errors) + + def test_unlisted_extension_event_type_requires_extensions(self): + vcon = Vcon.build_new() + vcon.add_party(Party(name="A")) + vcon.add_session(Session(start=T, parties=[0])) + vcon.add_event(Event(type="tool-call", time=T, sessions=0, party=0)) + valid, errors = vcon.is_valid() + assert not valid + assert any("events[0] type 'tool-call'" in e for e in errors) + vcon.add_extension("tool_calls") + assert vcon.is_valid() == (True, []) diff --git a/tests/test_vcon.py b/tests/test_vcon.py index 30a1f65..5d57b8d 100644 --- a/tests/test_vcon.py +++ b/tests/test_vcon.py @@ -1,6 +1,7 @@ from vcon import Vcon from vcon.party import Party from vcon.dialog import Dialog +from vcon.session import Session from typing import Union import pytest @@ -26,7 +27,7 @@ """ -test_vcon_string = ( +test_vcon_string_0_4_0 = ( '{"uuid":"0192aa73-e702-8cef-9dd8-dd37220d739c","vcon":"0.4.0",' '"created_at":"2024-10-20T15:02:55.490850+00:00","parties":[' '{"tel":"+14513886516","mailto":"david.scott@pickrandombusinesstype.com",' @@ -88,6 +89,29 @@ '(a Auto Repair Shop ) and is a conversation about billing."}}]}' ) + +def _to_0_5_0(legacy: str) -> str: + """The same conversation as a valid 0.5.0 document (what a 0.4.0 author would write now).""" + d = json.loads(legacy) + d["vcon"] = "0.5.0" + d["sessions"] = [ + { + "start": d["dialog"][0]["start"], + "duration": d["dialog"][0]["duration"], + "parties": [0, 1], + "dialog": [0], + } + ] + for att in d["attachments"]: + att.setdefault("start", d["created_at"]) + att.setdefault("party", 0) + att.setdefault("session", [0]) + att.setdefault("mediatype", "application/json") + return json.dumps(d) + + +test_vcon_string = _to_0_5_0(test_vcon_string_0_4_0) + GITHUB_WAV_URL = "https://github.com/vcon-dev/vcon-lib/raw/841eca9198397e768f478569a3595a70c6e892cc/tests/sample.mp3" @@ -151,17 +175,35 @@ def test_build_from_json() -> None: """ vcon = Vcon.build_from_json(test_vcon_string) assert vcon.uuid == "0192aa73-e702-8cef-9dd8-dd37220d739c" - assert vcon.vcon == "0.4.0" + assert vcon.vcon == "0.5.0" + assert vcon.migration_report is None assert vcon.created_at == "2024-10-20T15:02:55.490850+00:00" +def test_build_from_json_migrates_a_0_4_0_document() -> None: + """A document that declares 0.4.0 is migrated on load; the report says what it could not fix.""" + vcon = Vcon.build_from_json(test_vcon_string_0_4_0) + assert vcon.vcon == "0.5.0" + assert vcon.migration_report is not None + assert vcon.sessions[0]["dialog"] == [0] + assert vcon.sessions[0]["parties"] == [0, 1] + # The fixture's attachment never had start, party or a dialog, so it was not valid + # in 0.4.0 either. The migration does not invent them; it reports the gap. + assert any(e.step == "post" and "attachment" in e.message.lower() for e in vcon.migration_report.unresolved) + valid, errors = vcon.is_valid() + assert not valid and any("Attachment at index 0" in e for e in errors) + # Opting out keeps the raw document. + raw = Vcon.build_from_json(test_vcon_string_0_4_0, migrate_legacy=False) + assert raw.vcon == "0.4.0" and raw.migration_report is None + + def test_build_new() -> None: vcon = Vcon.build_new() assert vcon.uuid is not None - assert vcon.vcon == "0.4.0" + assert vcon.vcon == "0.5.0" assert vcon.created_at is not None assert "group" not in vcon.vcon_dict - assert "redacted" not in vcon.vcon_dict + assert "redacted_from" not in vcon.vcon_dict def test_tags() -> None: @@ -175,7 +217,11 @@ def test_tags() -> None: a for a in vcon.vcon_dict["attachments"] if a.get("purpose") == "tags" ) assert "party" in tags_att, "tags attachment missing required 'party' index" - assert "dialog" in tags_att, "tags attachment missing required 'dialog' index" + assert "dialog" in tags_att or "session" in tags_att, ( + "tags attachment needs dialog or session (core-05 section 4.6)" + ) + assert tags_att["session"] == [0] + assert vcon.vcon_dict["sessions"] == [{}] def test_add_attachment(): @@ -183,18 +229,20 @@ def test_add_attachment(): attachment = vcon.add_attachment(purpose="test_purpose", body="test_body") assert len(vcon.vcon_dict["attachments"]) == 1 - # start/party/dialog are required on every attachment by the WG JSON - # schema (draft-ietf-vcon-vcon-core-04); add_attachment() fills them in - # (start defaults to the vCon's created_at, party/dialog default to 0) - # when the caller doesn't supply them. + # start and party are required on every attachment, plus dialog or + # session (draft-ietf-vcon-vcon-core-05 section 4.6). add_attachment() + # fills them in: start defaults to the vCon's created_at, party to 0, and + # with neither dialog nor session given the attachment is scoped to every + # Session (an empty placeholder Session is added when there is none). assert vcon.vcon_dict["attachments"][0] == { "purpose": "test_purpose", "body": "test_body", "encoding": "none", "start": vcon.created_at, "party": 0, - "dialog": 0, + "session": [0], } + assert vcon.vcon_dict["sessions"] == [{}] assert isinstance(attachment, Attachment) @@ -251,7 +299,7 @@ def test_find_attachment_by_purpose() -> None: "encoding": "none", "start": vcon.created_at, "party": 0, - "dialog": 0, + "session": [0], } assert vcon.find_attachment_by_purpose("nonexistent_purpose") is None @@ -731,7 +779,7 @@ def test_load_from_file(tmp_path): vcon = Vcon.load(str(file_path)) assert isinstance(vcon, Vcon) assert vcon.uuid == "0192aa73-e702-8cef-9dd8-dd37220d739c" - assert vcon.vcon == "0.4.0" + assert vcon.vcon == "0.5.0" def test_load_from_file_not_found(): @@ -764,7 +812,7 @@ def test_load_from_url(mock_get): # Verify the vCon was loaded correctly assert vcon.uuid == "0192aa73-e702-8cef-9dd8-dd37220d739c" - assert vcon.vcon == "0.4.0" + assert vcon.vcon == "0.5.0" # Verify the mock was called correctly mock_get.assert_called_once_with(url) @@ -783,8 +831,8 @@ def test_load_detects_file_vs_url() -> None: try: # Replace methods with mocks as class methods so they bind correctly # Updated to accept all parameters - Vcon.load_from_file = classmethod(lambda cls, path, property_handling=None: path) - Vcon.load_from_url = classmethod(lambda cls, url, property_handling=None: url) + Vcon.load_from_file = classmethod(lambda cls, path, property_handling=None, **kw: path) + Vcon.load_from_url = classmethod(lambda cls, url, property_handling=None, **kw: url) # Test file path result = Vcon.load(file_path) @@ -1174,7 +1222,8 @@ def test_vcon_validation_with_video(): mediatype="video/mp4", filename="valid_video.mp4" ) - vcon.add_dialog(dialog) + vcon.add_session(Session(parties=[0])) + vcon.add_dialog(dialog, session=0) # Validate the vCon is_valid, errors = vcon.is_valid() @@ -1387,13 +1436,13 @@ def test_version_field_optional_load_from_file(tmp_path) -> None: def test_build_new_sets_version_field() -> None: - """build_new() sets vcon: '0.4.0' per draft-ietf-vcon-vcon-core-02 §4.1.1. + """build_new() sets vcon: '0.5.0' per draft-ietf-vcon-vcon-core-05 section 4.1.1. The field is deprecated in the draft but retained for parser compat; the library emits it by default to avoid surprises with strict parsers. """ vcon = Vcon.build_new() - assert vcon.vcon_dict["vcon"] == "0.4.0" + assert vcon.vcon_dict["vcon"] == "0.5.0" def test_no_version_field_remains_absent() -> None: @@ -1489,7 +1538,7 @@ def test_extensions_from_json(): json_str = ''' { "uuid": "123", - "vcon": "0.4.0", + "vcon": "0.5.0", "created_at": "2023-01-01T00:00:00Z", "extensions": ["video", "encryption"], "critical": ["encryption"] @@ -1505,45 +1554,45 @@ def test_extensions_property_handling(): """Test extensions with different property handling modes.""" vcon_dict = { "uuid": "123", - "vcon": "0.4.0", + "vcon": "0.5.0", "created_at": "2023-01-01T00:00:00Z", - "extensions": ["video"], + "extensions": ["video", "encryption"], "critical": ["encryption"], "custom_field": "value" } # Default mode - keep custom fields vcon = Vcon(vcon_dict, property_handling="default") - assert vcon.get_extensions() == ["video"] + assert vcon.get_extensions() == ["video", "encryption"] assert vcon.get_critical() == ["encryption"] assert "custom_field" in vcon.vcon_dict # Strict mode - remove custom fields vcon = Vcon(vcon_dict, property_handling="strict") - assert vcon.get_extensions() == ["video"] + assert vcon.get_extensions() == ["video", "encryption"] assert vcon.get_critical() == ["encryption"] assert "custom_field" not in vcon.vcon_dict # Meta mode - move custom fields to meta vcon = Vcon(vcon_dict, property_handling="meta") - assert vcon.get_extensions() == ["video"] + assert vcon.get_extensions() == ["video", "encryption"] assert vcon.get_critical() == ["encryption"] assert vcon.vcon_dict.get("meta", {}).get("custom_field") == "value" def test_build_new_emits_vcon_syntax_param() -> None: - """build_new() should emit vcon: '0.4.0' and round-trip through JSON.""" + """build_new() should emit vcon: '0.5.0' and round-trip through JSON.""" vcon = Vcon.build_new() serialized = vcon.to_json() reloaded = Vcon.build_from_json(serialized) - assert reloaded.vcon_dict["vcon"] == "0.4.0" + assert reloaded.vcon_dict["vcon"] == "0.5.0" def test_build_new_omits_empty_group_and_redacted() -> None: """build_new() should not seed empty group/redacted defaults.""" vcon = Vcon.build_new() assert "group" not in vcon.vcon_dict - assert "redacted" not in vcon.vcon_dict + assert "redacted_from" not in vcon.vcon_dict def test_is_valid_with_new_defaults() -> None: @@ -1553,11 +1602,12 @@ def test_is_valid_with_new_defaults() -> None: vcon = Vcon.build_new() vcon.add_party(Party(name="Alice")) + vcon.add_session(Session(start="2026-05-10T12:00:00Z", parties=[0])) vcon.add_dialog(Dialog( type="recording", start="2026-05-10T12:00:00Z", parties=[0], mediatype="audio/wav", - )) + ), session=0) valid, errors = vcon.is_valid() assert valid, f"Expected valid, got errors: {errors}" From b40544305a05e4281ab6e10eb01e6cb02c3812ce Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:03:56 -0500 Subject: [PATCH 02/12] Update docs and samples to vCon 0.5.0 Co-Authored-By: Claude Opus 5.5 --- API_REFERENCE.md | 172 +++++++++++++++------------ GUIDE.md | 24 ++-- LLM_GUIDE.md | 112 ++++++++--------- MIGRATION_GUIDE.md | 48 +++++++- README.md | 119 +++++++++++------- docs/source/version_management.rst | 10 +- extension_example.vcon.json | 2 +- samples/example_new_fields.vcon.json | 23 +++- samples/extension_example.py | 4 +- 9 files changed, 320 insertions(+), 194 deletions(-) diff --git a/API_REFERENCE.md b/API_REFERENCE.md index 639b53f..ec711f5 100644 --- a/API_REFERENCE.md +++ b/API_REFERENCE.md @@ -1,6 +1,21 @@ # vCon Library API Reference -Complete API documentation for the vCon library - a Python implementation of the latest vCon specification for Virtual Conversation objects. +Complete API documentation for the vCon library - a Python implementation of the vCon specification (`draft-ietf-vcon-vcon-core-05`, syntax `"0.5.0"`) for Virtual Conversation objects. + +## Changes in 1.0.0 (vCon 0.5.0) + +| Old (0.4.0) | New (0.5.0) | +| --- | --- | +| `vcon.redacted`, `vcon.amended` | `vcon.redacted_from`, `vcon.amended_from` | +| `PartyHistory`, `Dialog(party_history=...)` | `Event` objects in `vcon.events` (`Vcon.add_event`) | +| `Vcon.add_transfer_dialog()`, `"transfer"` Dialog type | transfer `Event` types (`blind-transfer`, `consultation-start`, `consultative-transfer`, `transfer-abandoned`) | +| `"recording-set"` Dialog type, `recordings`, `recording_set` | a `Session` listing the recordings | +| `Dialog(originator=...)` | `Session(originator=...)` | +| Dialog `parties` = sender and receivers | Dialog `parties` = contributors; `Session.parties` = receivers | +| Attachment `dialog` required | Attachment needs `party` plus `dialog` or `session` | +| `Vcon.sign(key)` | `Vcon.sign(key, alg="RS256")`; `alg` "none" raises `AlgorithmNotPermittedError`, as does `verify()` of such a vCon | +| `extensions` SHOULD list extensions | `is_valid()` errors when an extension in use is not listed | +| (new) | `Vcon.add_session`, `Vcon.sessions`, `Vcon.events`, `Dialog.placeholder()`, `migrate_0_4_0_to_0_5_0()` | ## Table of Contents @@ -11,7 +26,8 @@ Complete API documentation for the vCon library - a Python implementation of the - [Party](#party-class) - [Dialog](#dialog-class) - [CivicAddress](#civicaddress-class) - - [PartyHistory](#partyhistory-class) + - [Session and Event](#session-and-event-classes) + - [Migration](#migration) - [Attachment](#attachment-class) - [Extensions](#extensions) - [Extension Framework](#extension-framework) @@ -152,19 +168,23 @@ Find all dialogs of a specific type. text_dialogs = vcon.find_dialogs_by_type("text") ``` -###### `add_transfer_dialog(start: Union[datetime, str], transfer_data: Dict[str, Any], parties: List[int]) -> None` -Add a transfer dialog. +###### `add_session(session: Union[Session, dict, None] = None) -> int` +Add a Session Object (an empty placeholder when called with no argument) and return its index. ```python -transfer_data = { - "transferee": 0, - "transferor": 1, - "transfer_target": 2 -} -vcon.add_transfer_dialog(datetime.now(), transfer_data, [0, 1, 2]) +s = vcon.add_session(Session(start=datetime.now(), parties=[0, 1])) +vcon.add_dialog(dialog, session=s) # appends the new dialog index to Session s ``` -###### `add_incomplete_dialog(start: Union[datetime, str], disposition: str, parties: List[int]) -> None` +###### `add_event(event: Union[Event, dict]) -> int` +Add an Event Object and return its index. + +```python +vcon.add_event(Event(type="blind-transfer", time=datetime.now(), sessions=0, party=1, + transferee=0, transfer_target=2, target_session=1)) +``` + +###### `add_incomplete_dialog(start: Union[datetime, str], disposition: str, parties: List[int]) -> int` Add an incomplete dialog. ```python @@ -173,7 +193,7 @@ vcon.add_incomplete_dialog(datetime.now(), "no-answer", [0]) ##### Attachment Management -###### `add_attachment(purpose: str, body: Any, encoding: str = "none") -> Attachment` +###### `add_attachment(purpose: str, body: Any = None, encoding: str = "none", ..., party: Optional[int] = None, dialog: Optional[int] = None, session: Optional[Union[int, List[int]]] = None) -> Attachment` Add an attachment to the vCon. ```python @@ -281,7 +301,7 @@ Remove a must-support extension. ##### Extension-Specific Methods -###### `add_lawful_basis_attachment(lawful_basis: str, expiration: str, purpose_grants: list, party_index: Optional[int] = None, dialog_index: Optional[int] = None, **kwargs) -> None` +###### `add_lawful_basis_attachment(lawful_basis: str, expiration: str, purpose_grants: list, party_index: Optional[int] = None, dialog_index: Optional[int] = None, session_index: Optional[Union[int, List[int]]] = None, **kwargs) -> None` Add a lawful basis attachment to the vCon. ```python @@ -343,7 +363,7 @@ results = vcon.process_extensions() ##### Security -###### `sign(private_key: Union[rsa.RSAPrivateKey, bytes]) -> None` +###### `sign(private_key: Union[rsa.RSAPrivateKey, bytes], alg: str = "RS256") -> None` Sign the vCon with a private key. ```python @@ -426,11 +446,20 @@ Get the creation timestamp. ##### `updated_at` Get the update timestamp. -##### `redacted` -Get the redacted flag. +##### `redacted_from` +Get the Redacted_from Object (reference to the less redacted vCon). + +##### `amended_from` +Get the Amended_from Object (reference to the prior vCon instance). + +##### `sessions` +Get the `sessions` array. -##### `amended` -Get the amended flag. +##### `events` +Get the `events` array. + +##### `redacted_strings` +Get the `redacted_strings` array. ##### `group` Get the group information. @@ -517,27 +546,18 @@ Dialog( type: str, start: Union[datetime, str], parties: List[int], - originator: Optional[int] = None, mediatype: Optional[str] = None, filename: Optional[str] = None, body: Optional[str] = None, encoding: Optional[str] = None, url: Optional[str] = None, disposition: Optional[str] = None, - party_history: Optional[List[PartyHistory]] = None, - transferee: Optional[int] = None, - transferor: Optional[int] = None, - transfer_target: Optional[int] = None, - original: Optional[int] = None, - consultation: Optional[int] = None, - target_dialog: Optional[int] = None, campaign: Optional[str] = None, interaction: Optional[str] = None, skill: Optional[str] = None, duration: Optional[float] = None, meta: Optional[dict] = None, metadata: Optional[Dict[str, Any]] = None, - transfer: Optional[Dict[str, Any]] = None, signaling: Optional[Dict[str, Any]] = None, resolution: Optional[str] = None, frame_rate: Optional[float] = None, @@ -548,28 +568,21 @@ Dialog( content_hash: Optional[str] = None, application: Optional[str] = None, message_id: Optional[str] = None, + redacted_segments: Optional[List[Dict[str, Any]]] = None, **kwargs ) ``` **Parameters:** -- `type` (str): Dialog type ("text", "recording", "transfer", "incomplete", "audio", "video") +- `type` (str): Dialog type ("text", "recording", "incomplete"; "audio" and "video" are library conveniences) - `start` (Union[datetime, str]): Start time -- `parties` (List[int]): List of party indices -- `originator` (int, optional): Originator party index +- `parties` (List[int]): Indices of the contributors (the receivers are in the Session) - `mediatype` (str, optional): MIME type of content - `filename` (str, optional): Filename - `body` (str, optional): Content body - `encoding` (str, optional): Content encoding - `url` (str, optional): External URL - `disposition` (str, optional): Disposition for incomplete dialogs -- `party_history` (List[PartyHistory], optional): Party event history -- `transferee` (int, optional): Transferee party index -- `transferor` (int, optional): Transferor party index -- `transfer_target` (int, optional): Transfer target party index -- `original` (int, optional): Original dialog index -- `consultation` (int, optional): Consultation dialog index -- `target_dialog` (int, optional): Target dialog index - `campaign` (str, optional): Campaign identifier - `interaction` (str, optional): Interaction identifier - `skill` (str, optional): Skill identifier @@ -735,25 +748,29 @@ CivicAddress( ##### `to_dict() -> Dict[str, Optional[str]]` Convert CivicAddress to dictionary. -### PartyHistory Class +### Session and Event Classes -Represents party history events in a vCon dialog. +`Session(start=None, duration=None, parties=None, originator=None, session_id=None, sessions=None, dialog=None)` +and `SessionReference(session, type, description=None)` (types `child`, `peer`, `precursor`, `breakout`) are in +`vcon.session`. `to_dict()` omits unset parameters; `Session().to_dict() == {}` is a valid placeholder. -#### Constructor +`Event(type, time, sessions=None, party=None, dialog=None, channel=None, contributors=None, button=None, +transferee=None, transfer_target=None, consultation=None, target_session=None, validate=True, **extra)` is in +`vcon.event`. With `validate=True` the constructor applies the per-type parameter table +(`vcon.event.EVENT_PARAMETER_RULES`; M must, O optional, SN should not, X must not) and raises `ValueError`. +`validate_event(dict, ...)` returns `(errors, warnings)`. -```python -PartyHistory(party: int, event: str, time: datetime) -``` +`Dialog.placeholder()` creates an empty Dialog Object that serializes as `{}`. -**Parameters:** -- `party` (int): Index of the party -- `event` (str): Event type ("join", "drop", "hold", "unhold", "mute", "unmute") -- `time` (datetime): Time of the event +### Migration -#### Methods - -##### `to_dict() -> Dict[str, Any]` -Convert PartyHistory to dictionary. +`migrate_0_4_0_to_0_5_0(vcon, strict=False) -> MigrationResult(vcon, report)` (in `vcon.migration`) implements +Appendix A.1. `MIGRATION_STEPS` holds one entry per step T1 to T15. `MigrationReport` lists inferred values, +fallbacks and unresolved items (`report.inferred`, `.fallbacks`, `.unresolved`), the original content of removed +Dialogs (`report.removed_dialogs`) and `report.resign_required`. `MigrationError` is raised for input that cannot +be migrated and, in strict mode, when a required field has no source. `Vcon(...)`, `Vcon.build_from_json()` and +`Vcon.load*()` migrate input that declares `"vcon": "0.4.0"` (`migrate_legacy=False` turns that off) and keep the +report in `vcon.migration_report`. ### Attachment Class @@ -762,13 +779,16 @@ Represents an attachment in a vCon. #### Constructor ```python -Attachment(type: str, body: Any, encoding: str = "none") +Attachment(purpose: str, body: Any = None, encoding: str = "none", mediatype=None, filename=None, url=None, + content_hash=None, start=None, party=None, dialog=None, session=None) ``` **Parameters:** -- `type` (str): Type of attachment +- `purpose` (str): Purpose of the attachment - `body` (Any): Content of attachment -- `encoding` (str): Encoding format ("base64", "base64url", "none") +- `encoding` (str): Encoding format ("base64url", "json", "none") +- `party` (int): Party index (default 0) +- `dialog` (int), `session` (int or list): at least one is required; `Vcon.add_attachment()` fills `session` with every Session when neither is given #### Methods @@ -1165,7 +1185,7 @@ PROPERTY_HANDLING_META = "meta" # Move non-standard properties to meta ### Dialog Types ```python -VALID_TYPES = ["recording", "text", "transfer", "incomplete", "audio", "video"] +VALID_TYPES = ["recording", "text", "incomplete", "audio", "video"] ``` ### Disposition Values @@ -1177,10 +1197,12 @@ VALID_DISPOSITIONS = [ ] ``` -### Party History Events +### Event Types ```python -VALID_EVENTS = ["join", "drop", "hold", "unhold", "mute", "unmute"] +from vcon.event import CORE_EVENT_TYPES +# join, drop, hold, unhold, mute, unmute, keydown, keyup, consultation-start, +# blind-transfer, consultative-transfer, transfer-abandoned, channel-contributors ``` ### Attachment Encodings @@ -1285,15 +1307,19 @@ agent = Party(tel="+1987654321", name="Bob", role="agent") vcon.add_party(caller) vcon.add_party(agent) +# Session: the receivers. Dialog parties: the contributors. +vcon.add_session(Session(start=datetime.now(), parties=[0, 1])) + # Add dialog dialog = Dialog( type="text", start=datetime.now(), - parties=[0, 1], - originator=0, - body="Hello, I need help with my account." + parties=[0], + body="Hello, I need help with my account.", + encoding="none", + mediatype="text/plain", ) -vcon.add_dialog(dialog) +vcon.add_dialog(dialog, session=0) # Save to file vcon.save_to_file("conversation.vcon.json") @@ -1422,27 +1448,15 @@ party = Party( ) ``` -### Party History +### Events ```python -from vcon.party import PartyHistory - -# Create party history -history = [ - PartyHistory(0, "join", datetime.now()), - PartyHistory(1, "join", datetime.now()), - PartyHistory(0, "hold", datetime.now()), - PartyHistory(0, "unhold", datetime.now()), - PartyHistory(1, "drop", datetime.now()) -] +from vcon.event import Event -# Add to dialog -dialog = Dialog( - type="recording", - start=datetime.now(), - parties=[0, 1], - party_history=history -) +vcon.add_event(Event(type="join", time=datetime.now(), sessions=0, party=0)) +vcon.add_event(Event(type="hold", time=datetime.now(), sessions=0, party=0)) +vcon.add_event(Event(type="unhold", time=datetime.now(), sessions=0, party=0)) +vcon.add_event(Event(type="drop", time=datetime.now(), sessions=0, party=1)) ``` ### HTTP Operations diff --git a/GUIDE.md b/GUIDE.md index bc8654b..1943122 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -35,7 +35,10 @@ from vcon import Vcon - `dialog`: List of dialog entries - `attachments`: List of attachments - `analysis`: List of analysis entries -- `redacted`: Redaction information +- `redacted_from`: Reference to the less redacted vCon (0.5.0; was `redacted`) +- `amended_from`: Reference to the prior vCon instance (0.5.0; was `amended`) +- `sessions`: Session Objects grouping dialog and events (0.5.0) +- `events`: Event Objects (joins, drops, holds, key presses, transfers) (0.5.0) - `group`: Group information - `meta`: Metadata - `tags`: Tags attachment @@ -67,6 +70,7 @@ Represents a conversation entry. ```python from vcon.dialog import Dialog +from vcon.session import Session ``` #### Supported MIME Types @@ -188,15 +192,19 @@ index = vcon.find_party_index("tel", "+1234567890") ### Adding Dialog Entries ```python -# Add a text dialog +# A Session lists the receivers (0.5.0); Dialog parties are the contributors +vcon.add_session(Session(start="2024-03-21T10:00:00Z", parties=[0, 1])) + +# Add a text dialog to Session 0 dialog = Dialog( type="text", start="2024-03-21T10:00:00Z", - parties=[0, 1], + parties=[0], mediatype="text/plain", - body="Hello, how can I help?" + body="Hello, how can I help?", + encoding="none", ) -vcon.add_dialog(dialog) +vcon.add_dialog(dialog, session=0) ``` ### Working with Media @@ -617,6 +625,7 @@ print("Extension processing completed") from vcon import Vcon from vcon.party import Party from vcon.dialog import Dialog +from vcon.session import Session from datetime import datetime, timezone, timedelta # Create comprehensive vCon with extensions @@ -628,14 +637,15 @@ agent = Party(tel="+1987654321", name="Bob", role="agent") vcon.add_party(caller) vcon.add_party(agent) -# Add dialog +# Add a Session and the recording dialog +vcon.add_session(Session(start=datetime.now(timezone.utc), parties=[0, 1])) dialog = Dialog( type="recording", start=datetime.now(timezone.utc), parties=[0, 1], mediatype="audio/mp3" ) -vcon.add_dialog(dialog) +vcon.add_dialog(dialog, session=0) # Add lawful basis for consent vcon.add_lawful_basis_attachment( diff --git a/LLM_GUIDE.md b/LLM_GUIDE.md index b322a3d..00ed6fa 100644 --- a/LLM_GUIDE.md +++ b/LLM_GUIDE.md @@ -4,7 +4,7 @@ This guide provides a comprehensive overview of the vCon (Virtual Conversation) ## Overview -The vCon library is a Python implementation of the vCon 0.4.0 specification for structuring, managing, and manipulating conversation data in a standardized format. It enables the creation, validation, and manipulation of digital representations of conversations with rich metadata, supporting all modern conversation features including multimedia content, security, and extensibility. +The vCon library is a Python implementation of the vCon 0.5.0 specification (draft-ietf-vcon-vcon-core-05) for structuring, managing, and manipulating conversation data in a standardized format. It enables the creation, validation, and manipulation of digital representations of conversations with rich metadata, supporting all modern conversation features including multimedia content, security, and extensibility. ### Key Concepts @@ -130,7 +130,7 @@ party_index = vcon.find_party_index("name", "Alice Smith") # Returns index (0-b - `role`: Role in conversation ("caller", "agent", "bot", etc.) - `mailto`: Email address (e.g., "alice@example.com") -**Advanced Contact Methods (vCon 0.4.0):** +**Advanced Contact Methods (vCon 0.5.0):** - `sip`: SIP URI for VoIP communication (e.g., "sip:alice@example.com") - `did`: Decentralized Identifier for blockchain-based identity - `jCard`: vCard format contact information (RFC 7095) @@ -154,34 +154,38 @@ Represents a message or segment in the conversation. ```python from vcon.dialog import Dialog +from vcon.session import Session from datetime import datetime, timezone # Create a text dialog text_dialog = Dialog( type="text", start=datetime.now(timezone.utc).isoformat(), - parties=[0, 1], # Indices of parties involved - originator=0, # Index of the party that sent the message + parties=[0], # Contributors only; the receivers are in the Session mediatype="text/plain", - body="Hello, I need help with my account." + body="Hello, I need help with my account.", + encoding="none", ) -# Add to vCon -vcon.add_dialog(text_dialog) +# 0.5.0: a Session lists the receivers and the Dialogs it contains. +# The first Session party is the implied originator (use Session.originator otherwise). +vcon.add_session(Session(start=datetime.now(timezone.utc), parties=[0, 1])) + +# Add to vCon, in Session 0 +vcon.add_dialog(text_dialog, session=0) # Create an audio dialog audio_dialog = Dialog( type="audio", start=datetime.now(timezone.utc).isoformat(), parties=[0, 1], - originator=0, mediatype="audio/mp3", body=base64_encoded_audio, encoding="base64", filename="recording.mp3" ) -vcon.add_dialog(audio_dialog) +vcon.add_dialog(audio_dialog, session=0) # Find a dialog by property found_dialog = vcon.find_dialog("type", "text") @@ -190,23 +194,27 @@ found_dialog = vcon.find_dialog("type", "text") #### Special Dialog Types ```python -# Add a transfer dialog -vcon.add_transfer_dialog( - start=datetime.now(timezone.utc).isoformat(), - transfer_data={ - "reason": "Call forwarded", - "from": "+1234567890", - "to": "+1987654321" - }, - parties=[0, 1] -) +# A call transfer is an Event (the "transfer" Dialog type was removed in 0.5.0). +# `sessions` is the original call, `target_session` the call to the target. +from vcon.event import Event +vcon.add_event(Event( + type="blind-transfer", + time=datetime.now(timezone.utc), + sessions=0, party=1, # party is the Transferor + transferee=0, transfer_target=2, + target_session=1, +)) + +# An empty Dialog Object holds an array position so no other index moves +vcon.add_dialog(Dialog.placeholder()) # Add an incomplete dialog (for failed conversations) vcon.add_incomplete_dialog( start=datetime.now(timezone.utc).isoformat(), - disposition="NO_ANSWER", + disposition="no-answer", details={"ringDuration": 45000}, - parties=[0, 1] + parties=[0], # the party that attempted the call + session=0, ) ``` @@ -216,7 +224,6 @@ vcon.add_incomplete_dialog( # Check dialog type is_text = dialog.is_text() is_recording = dialog.is_recording() -is_transfer = dialog.is_transfer() is_incomplete = dialog.is_incomplete() is_audio = dialog.is_audio() is_video = dialog.is_video() @@ -228,7 +235,6 @@ is_email = dialog.is_email() **Valid Dialog Types:** - `"text"`: Text-based communication (chat, SMS, email) - `"recording"`: Audio/video recording -- `"transfer"`: Call transfer operation - `"incomplete"`: Failed or incomplete conversation setup - `"audio"`: Audio content - `"video"`: Video content @@ -313,7 +319,7 @@ vcon.add_analysis( analysis = vcon.find_analysis_by_type("sentiment") ``` -### 7. Extensions and Must-Support (vCon 0.4.0) +### 7. Extensions and Must-Support (vCon 0.5.0) Extensions allow vCons to declare optional features they use, while must-support indicates required features. @@ -685,7 +691,7 @@ processing_results = vcon.process_extensions() print("Extension processing completed") ``` -### 8. Civic Address Support (vCon 0.4.0) +### 8. Civic Address Support (vCon 0.5.0) Civic addresses provide location information for parties using the GEOPRIV standard. @@ -713,35 +719,37 @@ party = Party( address_dict = address.to_dict() ``` -### 9. Party History Events (vCon 0.4.0) +### 9. Events (vCon 0.5.0) -Track when parties join, leave, or change state during conversations. +Events replace party history. Track when parties join, leave, or change state, key presses and transfers. ```python -from vcon.party import PartyHistory +from vcon.event import Event from datetime import datetime -# Create party history events -history = [ - PartyHistory(0, "join", datetime.now()), # Party 0 joins - PartyHistory(1, "join", datetime.now()), # Party 1 joins - PartyHistory(0, "hold", datetime.now()), # Party 0 on hold - PartyHistory(0, "unhold", datetime.now()), # Party 0 off hold - PartyHistory(1, "drop", datetime.now()) # Party 1 drops -] +vcon.add_event(Event(type="join", time=datetime.now(), sessions=0, party=0)) +vcon.add_event(Event(type="join", time=datetime.now(), sessions=0, party=1)) +vcon.add_event(Event(type="hold", time=datetime.now(), sessions=0, party=0)) +vcon.add_event(Event(type="unhold", time=datetime.now(), sessions=0, party=0)) +vcon.add_event(Event(type="drop", time=datetime.now(), sessions=0, party=1)) -# Add to dialog -dialog = Dialog( - type="recording", - start=datetime.now(), - parties=[0, 1], - party_history=history -) +# Types: join, drop, hold, unhold, mute, unmute, keydown, keyup, +# consultation-start, blind-transfer, consultative-transfer, transfer-abandoned, +# channel-contributors. Each type has required, optional and forbidden +# parameters (vcon.event.EVENT_PARAMETER_RULES); Event() and is_valid() enforce them. +``` -# Valid event types: "join", "drop", "hold", "unhold", "mute", "unmute" +### 9b. Migrating a 0.4.0 vCon + +```python +from vcon import Vcon, migrate_0_4_0_to_0_5_0 + +vcon = Vcon.load("old.vcon.json") # "vcon": "0.4.0" is migrated on load +report = vcon.migration_report # inferred values, fallbacks, unresolved items +new_dict, report = migrate_0_4_0_to_0_5_0(old_dict, strict=True) # raises MigrationError if a required field has no source ``` -### 10. Advanced Dialog Features (vCon 0.4.0) +### 10. Advanced Dialog Features (vCon 0.5.0) New dialog fields for enhanced functionality. @@ -750,9 +758,9 @@ New dialog fields for enhanced functionality. dialog = Dialog( type="text", start=datetime.now(), - parties=[0, 1], - originator=0, + parties=[0], body="Hello, this is a test message!", + encoding="none", session_id={"local": "local-uuid", "remote": "remote-uuid"}, content_hash="c8d3d67f662a787e96e74ccb0a77803138c0f13495a186ccbde495c57c385608", application="chat-app", @@ -835,7 +843,6 @@ vcon.add_dialog(Dialog( type="text", start=datetime.now(timezone.utc).isoformat(), parties=[0, 1], - originator=0, # Caller mediatype="text/plain", body="Hello, I need help with my account." )) @@ -844,7 +851,6 @@ vcon.add_dialog(Dialog( type="text", start=datetime.now(timezone.utc).isoformat(), parties=[0, 1], - originator=1, # Agent mediatype="text/plain", body="I'd be happy to help. Can you provide your account number?" )) @@ -875,7 +881,6 @@ audio_dialog = Dialog( type="audio", start=datetime.now(timezone.utc).isoformat(), parties=[0, 1], - originator=0, mediatype="audio/mp3", body=audio_base64, encoding="base64", @@ -1054,7 +1059,6 @@ def create_basic_conversation(): type="text", start=datetime.now().isoformat(), parties=[0, 1], - originator=0, body="Hello, I need help." )) @@ -1088,7 +1092,6 @@ def create_multimedia_conversation(): type="text", start=datetime.now().isoformat(), parties=[0, 1], - originator=0, body="Hello, I need help with my account." )) @@ -1465,7 +1468,6 @@ def chat_to_vcon(chat_messages, participants): type="text", start=message["timestamp"], parties=[party_map[message["sender_id"]]], - originator=party_map[message["sender_id"]], body=message["content"] )) @@ -1715,7 +1717,7 @@ def validate_and_fix_vcon(vcon): elif "invalid dialog type" in error.lower(): # Try to fix invalid dialog types for dialog in vcon.dialog: - if dialog.get("type") not in ["text", "recording", "transfer", "incomplete", "audio", "video"]: + if dialog.get("type") not in ["text", "recording", "incomplete", "audio", "video"]: dialog["type"] = "text" # Default to text fixes_applied.append(f"Fixed invalid dialog type: {dialog.get('type')}") @@ -1811,4 +1813,4 @@ The vCon library provides a comprehensive framework for working with conversatio 14. **Export Transcriptions**: Leverage WTF export capabilities for subtitle formats 15. **Check Permissions**: Use lawful basis permission checking for privacy compliance -The vCon 0.4.0 specification provides a robust foundation for modern conversation data management with support for multimedia content, security, and extensibility. +The vCon 0.5.0 specification (draft-ietf-vcon-vcon-core-05) provides a robust foundation for modern conversation data management with support for multimedia content, security, and extensibility. diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 99fd348..bf12889 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -1,4 +1,50 @@ -# Migration Guide: Version Management Changes +# Migration Guide + +## Migrating to vCon 0.5.0 (library 1.0.0) + +Library 1.0.0 implements `draft-ietf-vcon-vcon-core-05` (syntax `"0.5.0"`). Readers accept 0.4.0 and 0.5.0; +writers emit 0.5.0. A vCon that declares `"vcon": "0.4.0"` is migrated when you load it: + +```python +from vcon import Vcon, migrate_0_4_0_to_0_5_0, MigrationError + +vcon = Vcon.load("old.vcon.json") # or Vcon(dict), Vcon.build_from_json(text) +print(vcon.migration_report.summary()) # what was inferred, what needs a person + +# Explicit form: returns the new dict and the report. strict=True raises MigrationError +# instead of using a documented fallback for a field the spec requires. +new_dict, report = migrate_0_4_0_to_0_5_0(old_dict, strict=False) + +# Opt out and keep the 0.4.0 dict as it is (is_valid() will report it as not 0.5.0) +vcon = Vcon.load("old.vcon.json", migrate_legacy=False) +``` + +The migration follows Appendix A.1 of the draft, one function per step (`vcon.migration.MIGRATION_STEPS`). +Removed `transfer` and `recording-set` Dialogs become empty Dialog Objects (`{}`) in place, so every dialog, +analysis, attachment and event index stays valid. Where A.1 is silent the migration applies a documented default and +lists it in the report (`report.inferred`); anything it cannot resolve is in `report.unresolved`. Signed input is +migrated as its unsigned payload; sign the result again (`report.resign_required`). + +Code that changes: + +| 0.4.0 | 0.5.0 | +| --- | --- | +| `vcon.redacted`, `vcon.amended` | `vcon.redacted_from`, `vcon.amended_from` | +| `PartyHistory`, `Dialog(party_history=...)` | `Event` and `Vcon.add_event()` (`event` is now `type`, `sessions` set) | +| `Vcon.add_transfer_dialog()` | transfer `Event` types | +| `Dialog(originator=...)` | `Session(originator=...)` | +| `Dialog(parties=[sender, *receivers])` | `Dialog(parties=[sender])`; receivers in `Session(parties=[...])` | +| `recording-set` Dialog | `Session(dialog=[...])` | +| attachments always `dialog=0` by default | attachments default to `session=[all Sessions]`; pass `dialog` or `session` | +| `vcon.sign(key)` accepts any header | `alg` "none" raises `AlgorithmNotPermittedError` on `sign()` and `verify()` | + +Also new: `is_valid()` now reports a missing Session when dialog or events exist, a missing `extensions` entry +for an extension in use (`lawful_basis`, `wtf_transcription`, or any value outside the core vocabulary), and an +attachment with inline content but no `mediatype`. + +--- + +# Earlier migration: Version Management Changes This guide helps you migrate your existing vCon code to work with the updated version management system. diff --git a/README.md b/README.md index 0d23879..583df44 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # vCon Library -A Python library for working with vCon (Virtual Conversation) objects according to the vCon specification. +A Python library for working with vCon (Virtual Conversation) objects according to the vCon specification, currently `draft-ietf-vcon-vcon-core-05` (syntax `"0.5.0"`). ## Overview @@ -12,7 +12,8 @@ The vCon library provides a complete implementation of the vCon format for repre - **Security**: Digital signatures and content hashing - **Extensibility**: Extensions and critical fields - **Location Data**: Civic address information (GEOPRIV) -- **Event Tracking**: Party history with join/drop/hold/mute events +- **Sessions and Events**: `sessions` group dialog by conversation, `events` record joins, drops, holds, key presses and call transfers +- **Migration**: `migrate_0_4_0_to_0_5_0()` upgrades 0.4.0 vCons, with a report of everything it inferred - **Privacy Compliance**: Lawful Basis extension for GDPR compliance - **Transcription Support**: WTF (World Transcription Format) extension for standardized speech-to-text @@ -23,6 +24,7 @@ The vCon library provides a complete implementation of the vCon format for repre from vcon import Vcon from vcon.party import Party from vcon.dialog import Dialog +from vcon.session import Session from datetime import datetime, timezone # Create a new vCon @@ -34,18 +36,36 @@ agent = Party(tel="+1987654321", name="Bob", role="agent") vcon.add_party(caller) vcon.add_party(agent) -# Add dialog +# A Session groups the dialog of one conversation. Its parties are the +# receivers; each Dialog's parties are only the contributors. +vcon.add_session(Session(start=datetime.now(timezone.utc), parties=[0, 1])) + +# Add dialog (to Session 0) dialog = Dialog( type="text", start=datetime.now(timezone.utc), - parties=[0, 1], - body="Hello, I need help with my account." + parties=[0], + body="Hello, I need help with my account.", + encoding="none", + mediatype="text/plain", ) -vcon.add_dialog(dialog) +vcon.add_dialog(dialog, session=0) # Save to file vcon.save_to_file("conversation.vcon.json") -print(f"Created vCon: {vcon.uuid}") +print(f"Created vCon: {vcon.uuid}") # syntax "0.5.0" +``` + +### Loading a 0.4.0 vCon +```python +# Readers accept 0.4.0 and 0.5.0. A document that declares "vcon": "0.4.0" +# is migrated to 0.5.0 on load; the report lists every inferred value. +vcon = Vcon.load("old.vcon.json") +print(vcon.migration_report.summary()) # "3 inferred, 0 fallback, 1 unresolved" + +# Or migrate explicitly (strict=True raises MigrationError instead of using a fallback) +from vcon import migrate_0_4_0_to_0_5_0 +new_dict, report = migrate_0_4_0_to_0_5_0(old_dict, strict=False) ``` ### Privacy Compliance with Lawful Basis Extension @@ -127,14 +147,15 @@ agent = Party(tel="+1987654321", name="Bob", role="agent") vcon.add_party(caller) vcon.add_party(agent) -# Add recording dialog +# One Session for the call, then the recording dialog in it +vcon.add_session(Session(start=datetime.now(timezone.utc), parties=[0, 1])) dialog = Dialog( type="recording", start=datetime.now(timezone.utc), parties=[0, 1], mediatype="audio/mp3" ) -vcon.add_dialog(dialog) +vcon.add_dialog(dialog, session=0) # Add lawful basis for consent vcon.add_lawful_basis_attachment( @@ -252,19 +273,35 @@ dialog = Dialog( ) ``` -### Party History Events +### Events (replacing party history) ```python -from vcon.party import PartyHistory -from datetime import datetime +from vcon.event import Event +from datetime import datetime, timezone + +now = datetime.now(timezone.utc) +# Events apply to the Sessions listed in `sessions`. +vcon.add_event(Event(type="join", time=now, sessions=0, party=0)) +vcon.add_event(Event(type="hold", time=now, sessions=0, party=0)) +vcon.add_event(Event(type="keydown", time=now, sessions=0, party=1, button="5")) + +# A blind transfer: `sessions` is the original call, `target_session` the call to the target +vcon.add_event(Event(type="blind-transfer", time=now, sessions=0, party=1, + transferee=0, transfer_target=2, target_session=1)) +``` +Each type has a parameter table (core-05 section 4.3.1.5) that `Event` and +`Vcon.is_valid()` enforce: required (M), optional (O), should not (SN, a warning) +and must not (X). -# Track party events -history = [ - PartyHistory(0, "join", datetime.now()), - PartyHistory(1, "join", datetime.now()), - PartyHistory(0, "hold", datetime.now()), - PartyHistory(0, "unhold", datetime.now()), - PartyHistory(1, "drop", datetime.now()) -] +### Sessions +```python +from vcon.session import Session, SessionReference + +vcon.add_session(Session( + start=now, duration=300, parties=[0, 1], # parties are the receivers + originator=1, # only when not the first party + sessions=[SessionReference(1, "child")], # child, peer, precursor, breakout +)) +vcon.add_session() # an empty placeholder Session is allowed ``` ### Disposition Values for Incomplete Dialogs @@ -419,6 +456,7 @@ pip install vcon from vcon import Vcon from vcon.party import Party from vcon.dialog import Dialog +from vcon.session import Session from datetime import datetime # Create a new vCon @@ -431,15 +469,20 @@ bob = Party(tel="+1987654321", name="Bob", role="agent") vcon.add_party(alice) vcon.add_party(bob) +# A Session lists the receivers; Dialog parties are the contributors +vcon.add_session(Session(start=datetime.now(), parties=[0, 1])) + # Add dialog dialog = Dialog( type="text", start=datetime.now(), - parties=[0, 1], - body="Hello, this is a test message!" + parties=[0], + body="Hello, this is a test message!", + encoding="none", + mediatype="text/plain", ) -vcon.add_dialog(dialog) +vcon.add_dialog(dialog, session=0) # Save to file vcon.save_to_file("conversation.vcon.json") @@ -546,23 +589,18 @@ vcon = Vcon.load("file.json", property_handling="meta") vcon = Vcon.load("file.json", property_handling="default") ``` -### Transfer Dialogs +### Call Transfers -```python -# Create transfer dialog -transfer_data = { - "transferee": 0, - "transferor": 1, - "transfer_target": 2, - "original": 0, - "target_dialog": 1 -} +The `transfer` dialog type was removed in 0.5.0. A transfer is one or two Events +(`consultation-start`, `blind-transfer`, `consultative-transfer`, +`transfer-abandoned`) that reference Sessions for the original, consultation and +target calls. See "Events" above. -vcon.add_transfer_dialog( - start=datetime.now(), - transfer_data=transfer_data, - parties=[0, 1, 2] -) +### Empty Dialog Objects + +```python +# Holds a position in the dialog array so no other index moves +vcon.add_dialog(Dialog.placeholder()) # serializes as {} ``` ### Analysis Data @@ -585,8 +623,9 @@ This library implements the latest vCon specification with: - ✅ All required fields and validation - ✅ Proper media type support - ✅ Civic address (GEOPRIV) compliance -- ✅ Party history event tracking -- ✅ Transfer dialog support +- ✅ Sessions and Events, with the per-event-type parameter table enforced +- ✅ Migration from 0.4.0 (`migrate_0_4_0_to_0_5_0`) +- ✅ `extensions` completeness and `alg: "none"` rejection - ✅ Content hashing and security - ✅ Extensions and critical - ✅ Flexible versioning (version field is optional) diff --git a/docs/source/version_management.rst b/docs/source/version_management.rst index 6d1135e..7ea0d85 100644 --- a/docs/source/version_management.rst +++ b/docs/source/version_management.rst @@ -93,8 +93,8 @@ The version field is now optional. You can choose to: # Option 2: Manually add version field if needed vcon = Vcon.build_new() - vcon.vcon_dict["vcon"] = "0.4.0" - # vcon.vcon will be "0.4.0" + vcon.vcon_dict["vcon"] = "0.5.0" + # vcon.vcon will be "0.5.0" Backward Compatibility ~~~~~~~~~~~~~~~~~~~~~~ @@ -120,8 +120,8 @@ Creating Versionless vCons print(vcon.vcon) # None # Add version field manually if needed - vcon.vcon_dict["vcon"] = "0.4.0" - print(vcon.vcon) # "0.4.0" + vcon.vcon_dict["vcon"] = "0.5.0" + print(vcon.vcon) # "0.5.0" Working with Existing vCons ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -173,7 +173,7 @@ Common Issues 2. **Version field not found**: - Check if the vCon object has a version field: ``vcon.vcon is not None`` - - Add version field manually if needed: ``vcon.vcon_dict["vcon"] = "0.4.0"`` + - Add version field manually if needed: ``vcon.vcon_dict["vcon"] = "0.5.0"`` 3. **Validation errors**: - Ensure required fields (uuid, created_at) are present diff --git a/extension_example.vcon.json b/extension_example.vcon.json index 5dcd651..914a923 100644 --- a/extension_example.vcon.json +++ b/extension_example.vcon.json @@ -1 +1 @@ -{"uuid": "019987a8-9b30-80e1-9dd8-dd37220d739c", "redacted": {}, "group": [], "parties": [{"tel": "tel:+1234567890", "stir": "caller"}], "dialog": [{"type": "recording", "start": "2025-09-26T20:13:18.000410+00:00", "parties": [0], "mediatype": "audio/mp3", "body": "dGVzdCBhdWRpbyBkYXRh", "encoding": "base64url", "metadata": {}, "meta": {}}], "attachments": [{"purpose": "lawful_basis", "encoding": "json", "body": {"lawful_basis": "consent", "expiration": "2026-09-26T20:13:18.000441+00:00", "purpose_grants": [{"purpose": "recording", "granted": true, "granted_at": "2025-09-26T20:13:18.000444+00:00"}, {"purpose": "analysis", "granted": true, "granted_at": "2025-09-26T20:13:18.000445+00:00", "conditions": ["anonymized_data_only"]}]}, "party": 0}, {"purpose": "wtf_transcription", "encoding": "json", "body": {"transcript": {"text": "Hello, this is a test transcription.", "language": "en", "duration": 3.5, "confidence": 0.95}, "segments": [{"id": 0, "start": 0.0, "end": 1.5, "text": "Hello, this is", "confidence": 0.95}, {"id": 1, "start": 1.5, "end": 3.5, "text": "a test transcription.", "confidence": 0.94}], "metadata": {"created_at": "2025-09-26T20:13:18.000531+00:00", "processed_at": "2025-09-26T20:13:18.000533+00:00", "provider": "whisper", "model": "whisper-1"}}, "party": 0, "dialog": 0}], "analysis": [], "created_at": "2025-09-26T20:13:18.000078+00:00", "extensions": ["lawful_basis", "wtf_transcription"]} \ No newline at end of file +{"vcon": "0.5.0", "uuid": "01a19846-340f-8b74-9dd8-dd37220d739c", "parties": [{"tel": "tel:+1234567890", "stir": "caller"}], "dialog": [{"type": "recording", "start": "2026-11-01T18:01:40.111984+00:00", "parties": [0], "mediatype": "audio/mp3", "body": "dGVzdCBhdWRpbyBkYXRh", "encoding": "base64url"}], "attachments": [{"purpose": "lawful_basis", "encoding": "json", "body": {"lawful_basis": "consent", "expiration": "2027-11-01T18:01:40.112011+00:00", "purpose_grants": [{"purpose": "recording", "granted": true, "granted_at": "2026-11-01T18:01:40.112015+00:00"}, {"purpose": "analysis", "granted": true, "granted_at": "2026-11-01T18:01:40.112015+00:00", "conditions": ["anonymized_data_only"]}]}, "party": 0, "session": [0], "mediatype": "application/json", "start": "2026-11-01T18:01:40.111731+00:00"}, {"purpose": "wtf_transcription", "encoding": "json", "body": {"transcript": {"text": "Hello, this is a test transcription.", "language": "en", "duration": 3.5, "confidence": 0.95}, "segments": [{"id": 0, "start": 0.0, "end": 1.5, "text": "Hello, this is", "confidence": 0.95}, {"id": 1, "start": 1.5, "end": 3.5, "text": "a test transcription.", "confidence": 0.94}], "metadata": {"created_at": "2026-11-01T18:01:40.112091+00:00", "processed_at": "2026-11-01T18:01:40.112092+00:00", "provider": "whisper", "model": "whisper-1"}}, "party": 0, "dialog": 0, "session": [0], "mediatype": "application/json", "start": "2026-11-01T18:01:40.111731+00:00"}], "analysis": [], "created_at": "2026-11-01T18:01:40.111731+00:00", "sessions": [{"start": "2026-11-01T18:01:40.111969+00:00", "parties": [0], "dialog": [0]}], "extensions": ["lawful_basis", "wtf_transcription"]} \ No newline at end of file diff --git a/samples/example_new_fields.vcon.json b/samples/example_new_fields.vcon.json index ced18b4..8ba9a37 100644 --- a/samples/example_new_fields.vcon.json +++ b/samples/example_new_fields.vcon.json @@ -1,6 +1,5 @@ { "uuid": "019822fb-309a-8716-9dd8-dd37220d739c", - "redacted": {}, "group": [], "parties": [ { @@ -33,8 +32,7 @@ "type": "text", "start": "2025-07-19T15:59:04.090841", "parties": [ - 0, - 1 + 0 ], "body": "Hello, this is a test message!", "session_id": { @@ -43,7 +41,9 @@ }, "content_hash": "yNPWf2YqeH6W50zLCneAMTjA8TSVoYbMveSVxXw4Vgg=", "metadata": {}, - "meta": {} + "meta": {}, + "mediatype": "text/plain", + "encoding": "none" } ], "attachments": [], @@ -55,5 +55,18 @@ ], "critical": [ "encryption" + ], + "vcon": "0.5.0", + "sessions": [ + { + "start": "2025-07-19T15:59:04.090841", + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } ] -} \ No newline at end of file +} diff --git a/samples/extension_example.py b/samples/extension_example.py index 4e28382..1710dda 100644 --- a/samples/extension_example.py +++ b/samples/extension_example.py @@ -35,7 +35,9 @@ def main(): # Add a dialog from vcon.dialog import Dialog + from vcon.session import Session from datetime import datetime, timezone + vcon.add_session(Session(start=datetime.now(timezone.utc), parties=[0])) dialog = Dialog( type="recording", start=datetime.now(timezone.utc), @@ -44,7 +46,7 @@ def main(): body="dGVzdCBhdWRpbyBkYXRh", # "test audio data" in base64 encoding="base64url" ) - vcon.add_dialog(dialog) + vcon.add_dialog(dialog, session=0) print("Added dialog") # Example 1: Lawful Basis Extension From 8c173eb183222dbcb114181978c44c1790085e99 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:03:57 -0500 Subject: [PATCH 03/12] Bump to 1.0.0 for the breaking core-05 port Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 4 +-- setup.py | 2 +- 3 files changed, 76 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f92006..5057976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,78 @@ # Changelog +## [1.0.0] - Unreleased + +Retargets the library to `draft-ietf-vcon-vcon-core-05` (syntax `"0.5.0"`). +This is a breaking release: the Dialog Object lost its transfer, recording-set, +party history and originator content, which moved to the new Session and Event +Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. + +### Added +- `Session` and `SessionReference` (`vcon.session`), the top-level `sessions` + array, `Vcon.add_session()` and `Vcon.sessions`. +- `Event` (`vcon.event`), the top-level `events` array, `Vcon.add_event()` and + `Vcon.events`. The per-event-type parameter table (section 4.3.1.5) is + enforced by `Event(...)`, `validate_event()` and `Vcon.is_valid()`. +- `redacted_from`, `amended_from` and `redacted_strings` top-level parameters + and properties; Dialog `redacted_segments`; Attachment `session`; Analysis + `sessions`, `attachment` and `analysis`. +- Empty Dialog Objects: `Dialog.placeholder()` serializes as `{}`. +- `migrate_0_4_0_to_0_5_0(vcon, strict=False)` (`vcon.migration`), a table + driven implementation of Appendix A.1 (`MIGRATION_STEPS`, one entry per step + T1 to T15) that returns `MigrationResult(vcon, report)`. The + `MigrationReport` lists every inferred value, every fallback for a required + field and every unresolved item, and keeps the original content of removed + Dialogs. `MigrationError` is raised for input that cannot be migrated and, in + strict mode, when a required field has no source. Signed input is migrated as + its unsigned payload and the report sets `resign_required`; the library never + re-signs. +- `Vcon.migrate_0_4_0_to_0_5_0()` classmethod, `Vcon.migration_report`, and the + `migrate_legacy` and `strict_migration` parameters on `Vcon()`, + `build_from_json()`, `load()`, `load_from_file()` and `load_from_url()`. +- `Vcon.get_validation_warnings()` for SHOULD-level findings. +- `Vcon.sign(key, alg="RS256")`; `AlgorithmNotPermittedError`. + +### Changed +- **Breaking:** `build_new()` emits `"vcon": "0.5.0"`. +- **Breaking:** a vCon that declares `"vcon": "0.4.0"` (or a signed vCon whose + payload does) is migrated on load, so `vcon.vcon` reads `"0.5.0"` and indices + are preserved. Use `migrate_legacy=False` to keep the raw 0.4.0 dict. +- **Breaking:** `Vcon.redacted` and `Vcon.amended` are now `redacted_from` and + `amended_from`. +- **Breaking:** Dialog types are `recording`, `text` and `incomplete` (plus the + library's `audio` and `video` conveniences). The `transfer` type and the + `recording-set` type are gone, as are the Dialog parameters `party_history`, + `originator`, `transferee`, `transferor`, `transfer_target`, `original`, + `consultation`, `target_dialog`, `transfer`, `recordings` and `recording_set`; + passing one to `Dialog()` raises `ValueError`. `PartyHistory` and + `Vcon.add_transfer_dialog()` were removed; use `Event`. +- **Breaking:** Dialog `parties` are the contributors only; the receivers are + the `parties` of the Session that lists the Dialog. +- **Breaking:** `add_incomplete_dialog()` no longer writes a `body` (an + incomplete Dialog has no content); `details` is kept in `metadata["details"]`. +- **Breaking:** attachments need `party` plus `dialog` or `session`. The + `dialog` default of 0 is gone. With neither given, `add_attachment()`, + `add_tag()`, `add_lawful_basis_attachment()` and + `add_wtf_transcription_attachment()` scope the attachment to every Session and + add an empty placeholder Session if there is none. `add_lawful_basis_attachment()` + and `add_wtf_transcription_attachment()` take `session_index`. +- **Breaking:** `add_analysis()` takes `dialog` as an optional keyword. +- **Breaking:** `is_valid()` now also checks: a Session exists when there is + dialog or events; all Session, Event, attachment and analysis references; the + Event parameter table; `redacted_from` and `amended_from` exclusivity; that + `extensions` lists every extension in use (`lawful_basis`, + `wtf_transcription`, or any value outside the core vocabulary) and every + `critical` entry; inline attachment `mediatype`; `__REDACTED_REF_#` + references against `redacted_strings`; and that `vcon`, when present, is + `"0.5.0"`. Dialog `mediatype` parameters (`; boundary=...`) and `multipart/*` + subtypes are accepted; analysis no longer requires `dialog`. +- **Breaking:** `sign()` and `verify()` reject JWS `alg` "none" with + `AlgorithmNotPermittedError`; `verify()` returns False when no `alg` is present. +- `add_dialog()` and `add_incomplete_dialog()` return the new Dialog's index and + take an optional `session`. +- Vendored test schema is now the core-05 Appendix C schema, with the Appendix B + examples under `tests/schema/examples/`. + ## [0.10.0] - Unreleased Retargets the library to `draft-ietf-vcon-vcon-core-04`. Under -04 section diff --git a/pyproject.toml b/pyproject.toml index 1371ebb..056a767 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [tool.poetry] name = "vcon" -version = "0.10.0" -description = "The vCon library - Complete vCon 0.4.0 specification implementation" +version = "1.0.0" +description = "The vCon library - vCon 0.5.0 (draft-ietf-vcon-vcon-core-05) specification implementation" authors = ["Thomas McCarthy-Howe "] license = "MIT" readme = "README.md" diff --git a/setup.py b/setup.py index cc59f55..12ff616 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name="vcon", - version="0.10.0", + version="1.0.0", author="Thomas McCarthy-Howe", author_email="ghostofbasho@gmail.com", description="A package for working with vCon containers", From 5dcbc383c58284f51c6e3aba353f308d9ddb4f04 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:12:14 -0500 Subject: [PATCH 04/12] Fix data loss and broken references in the 0.4.0 to 0.5.0 migration - Refuse input without "vcon" that already carries 0.5.0-only parameters (sessions, events, redacted_from, amended_from, redacted_strings); it was re-migrated and its sessions and events overwritten. - Recording-sets: take membership from recording_set back-references as well as the recordings list; a set listed inside another becomes a "child" Session_Reference (indices are allocated before filling, so forward references work); unmapped recording-set parameters and stray recording_set/recordings values are reported with their values. - Transfers: a transfer Dialog's originator is reported, not dropped. T4 now runs before T3, so party_history Events list every Session of their Dialog, including the Sessions created for a transfer's calls (AMB-3). - party_history: the time fallback chain is Dialog start, then created_at (strict raises); the unusable original time is kept in the report; extension parameters are carried onto the Event unless they clash with a core Event parameter, and either way are reported. - text/incomplete Dialogs whose first party is null no longer promote a receiver to sender/originator; an empty Party Object stands in and the gap is reported. - New step T10c: an attachment with neither dialog nor session is scoped to the only Session when exactly one exists (reported as inferred), and reported as unresolved otherwise. Co-Authored-By: Claude Opus 5.5 --- src/vcon/migration.py | 207 ++++++++++++++++++++++++++++----- tests/test_migration_0_4_0.py | 9 +- tests/test_migration_review.py | 198 +++++++++++++++++++++++++++++++ 3 files changed, 384 insertions(+), 30 deletions(-) create mode 100644 tests/test_migration_review.py diff --git a/src/vcon/migration.py b/src/vcon/migration.py index 55cb9cb..9f1d506 100644 --- a/src/vcon/migration.py +++ b/src/vcon/migration.py @@ -10,7 +10,11 @@ run before any array is rewritten, and ``T10`` blanks the removed Dialogs in place at the end, so the array length and every other index are unchanged. - T13 T15 T1 -> T8 T9 T9b T6 -> T2 T7 T3 T4(+T5) -> T10 T10b -> T11 T12 T14 + T13 T15 T1 -> T8 T9 T9b T6 -> T2 T7 T4(+T5) T3 -> T10 T10b T10c -> T11 T12 T14 + +T4 runs before T3 so that the Sessions T5 creates for a transfer's original, +consultation and target calls are known when T3 builds the party_history +Events: an Event lists every Session of the Dialog it came from (AMB-3). Nothing is invented silently. Every value the draft does not dictate is listed in the :class:`MigrationReport` (kind ``inferred``), every field that had to be @@ -34,6 +38,7 @@ from dateutil import parser +from .event import EVENT_PARAMETERS as _EVENT_PARAMS from .validation import extensions_in_use, validate_vcon_dict logger = logging.getLogger(__name__) @@ -41,6 +46,11 @@ SOURCE_VERSION = "0.4.0" TARGET_VERSION = "0.5.0" +#: Top-level parameters that exist only in 0.5.0. Input that has one of them is +#: already 0.5.0 even when it omits the (optional, deprecated) ``vcon`` parameter; +#: migrating it again would overwrite its ``sessions`` and ``events``. +_V050_ONLY_KEYS = ("sessions", "events", "redacted_from", "amended_from", "redacted_strings") + class MigrationError(ValueError): """The vCon cannot be migrated (or, in strict mode, a MUST field has no source).""" @@ -428,16 +438,21 @@ def _step_t3_party_history(ctx: _Context) -> None: if _parse_dt(entry.get("time")): ev["time"] = entry["time"] else: - fb = src_d.get("start") + # MUST field: Dialog start, then the vCon created_at. + fb, src = src_d.get("start"), "Dialog start" + if not _parse_dt(fb): + fb, src = ctx.out.get("created_at"), "vCon created_at" + if not _parse_dt(fb): + raise MigrationError( + f"T3: dialog[{i}].party_history[{n}] has no time, and neither the Dialog start " + "nor the vCon created_at can stand in" + ) ctx.need_fallback( "T3", - f"dialog[{i}].party_history[{n}] has no usable time; used the Dialog start " - f"({fb!r}) as the Event time.", None, dialog=i, + f"dialog[{i}].party_history[{n}] has no usable time ({entry.get('time')!r}); used the " + f"{src} ({fb!r}) as the Event time.", None, dialog=i, entry=n, + original_time=entry.get("time"), source=src, time=fb, ) - if fb is None: - raise MigrationError( - f"T3: dialog[{i}].party_history[{n}] has no time and the Dialog has no start" - ) ev["time"] = fb if sess: ev["sessions"] = sess[0] if len(sess) == 1 else sess @@ -456,7 +471,22 @@ def _step_t3_party_history(ctx: _Context) -> None: ctx.report.add( "T3", UNRESOLVED, f"dialog[{i}].party_history[{n}] has 'button' on a '{entry['event']}' event " - "(only keydown and keyup carry it); button not migrated.", None, dialog=i, + "(only keydown and keyup carry it); button not migrated.", None, dialog=i, entry=n, + dropped={"button": entry["button"]}, + ) + # Parameters a 0.4.0 extension added to the entry: carried onto the Event + # unless the name is a core Event parameter (which would change its meaning). + unknown = {k: v for k, v in entry.items() if k not in ("party", "time", "event", "button")} + if unknown: + carried = {k: v for k, v in unknown.items() if k not in _EVENT_PARAMS} + dropped = {k: v for k, v in unknown.items() if k in _EVENT_PARAMS} + ev.update(carried) + ctx.report.add( + "T3", UNRESOLVED, + f"dialog[{i}].party_history[{n}] had non-core parameter(s) {sorted(unknown)}; " + f"carried onto the Event: {sorted(carried)}, dropped (name clashes with a core Event " + f"parameter): {sorted(dropped)}. List the defining extension in 'extensions'.", + None, dialog=i, entry=n, carried=carried, dropped=dropped, ) ctx.events.append(ev) if src_d.get("type") != "recording-set" and isinstance(dialogs[i], dict): @@ -628,7 +658,7 @@ def event_time(which: str) -> str: ctx.events.append(ev) extra = sorted( set(tr) - - {"type", "start", "transferee", "transferor", "transfer_target", "original", "consultation", "target_dialog", "parties", "originator", "party_history"} + - {"type", "start", "transferee", "transferor", "transfer_target", "original", "consultation", "target_dialog", "parties", "party_history"} ) if extra or tr.get("parties"): ctx.report.add( @@ -636,6 +666,7 @@ def event_time(which: str) -> str: f"transfer dialog[{k}] had parameters with no Event equivalent " f"({extra + (['parties'] if tr.get('parties') else [])}); not migrated. " "Original kept in report.removed_dialogs.", None, dialog=k, + dropped={f: tr[f] for f in extra + (["parties"] if tr.get("parties") else [])}, ) @@ -660,23 +691,60 @@ def _step_t7_recording_sets(ctx: _Context) -> None: The recording-set's own start, duration, parties, session_id and originator move to the Session (A.1 is silent: AMB-4). ``recording_set`` is removed from each recording. + + Membership is the union of the set's ``recordings`` list and the recordings + whose ``recording_set`` points at it (core-04 made ``recordings`` MUST and + ``recording_set`` SHOULD, so stored data can carry either side only). A + recording-set listed in another recording-set's ``recordings`` becomes a + ``child`` Session_Reference of that set's Session. Every Session index is + allocated before any is filled, so a nested set can point forward. """ dialogs = ctx.out.get("dialog") - for k, kind in ctx.removed.items(): - if kind != "recording-set": + rs_ids = [k for k, kind in ctx.removed.items() if kind == "recording-set"] + for k in rs_ids: + ctx.rs_session[k] = ctx.new_session({}) + + # recording_set back-references from kept Dialogs. + back: Dict[int, List[int]] = {} + for i in ctx.kept(): + ref = ctx.dialogs[i].get("recording_set") + if ref is None: continue + if _is_int(ref) and ref in ctx.rs_session: + back.setdefault(ref, []).append(i) + else: + ctx.report.add( + "T7", UNRESOLVED, + f"dialog[{i}] recording_set={ref!r} does not reference a recording-set Dialog; " + "parameter removed, no Session membership derived from it.", None, dialog=i, recording_set=ref, + ) + + for k in rs_ids: rs = ctx.dialogs[k] + sidx = ctx.rs_session[k] recs_raw = rs.get("recordings") recs: List[int] = [] + children: List[int] = [] if isinstance(recs_raw, list): for r in recs_raw: - if _is_int(r) and 0 <= r < len(ctx.dialogs) and r not in ctx.removed and isinstance(ctx.dialogs[r], dict): + if _is_int(r) and r in ctx.rs_session and r != k: + if ctx.rs_session[r] not in children: + children.append(ctx.rs_session[r]) + elif _is_int(r) and 0 <= r < len(ctx.dialogs) and r not in ctx.removed and isinstance(ctx.dialogs[r], dict) and ctx.dialogs[r]: if r not in recs: recs.append(r) else: - ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] lists recordings entry {r!r}, which is not a kept Dialog; left out of the Session.", None, dialog=k) + ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] lists recordings entry {r!r}, which is not a kept Dialog or another recording-set; left out of the Session.", None, dialog=k, entry=r) else: - ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] has no recordings list; Session has no dialog.", None, dialog=k) + ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] has no recordings list.", None, dialog=k) + added_back = [i for i in back.get(k, []) if i not in recs] + if added_back: + recs.extend(added_back) + ctx.report.add( + "T7", INFERRED, + f"dialog(s) {added_back} name recording-set dialog[{k}] in recording_set but are not in its " + f"recordings list; added to Session {sidx}.", None, dialog=k, added=added_back, session=sidx, + ) sess: Dict[str, Any] = {} d_start, d_dur = ctx.span(recs) if recs else (None, None) if _parse_dt(rs.get("start")): @@ -694,6 +762,8 @@ def _step_t7_recording_sets(ctx: _Context) -> None: orig = rs.get("originator") if _is_int(orig) and (not parties or orig != parties[0]): sess["originator"] = orig + elif orig is not None and not _is_int(orig): + ctx.report.add("T7", UNRESOLVED, f"recording-set dialog[{k}] originator {orig!r} is not a party index; dropped.", None, dialog=k) sid = rs.get("session_id") if isinstance(sid, dict): sess["session_id"] = sid @@ -705,12 +775,17 @@ def _step_t7_recording_sets(ctx: _Context) -> None: f"recording-set dialog[{k}] session_id is not a single SessionId Object; Session.session_id not set.", "AMB-4", dialog=k, session_id=sid, ) + if children: + sess["sessions"] = [{"session": c, "type": "child"} for c in children] + ctx.report.add( + "T7", INFERRED, + f"recording-set dialog[{k}] lists other recording-set(s); Session {sidx} references their " + f"Session(s) {children} as 'child'.", "AMB-1", dialog=k, session=sidx, children=children, + ) if recs: sess["dialog"] = recs order = ("start", "duration", "parties", "originator", "session_id", "sessions", "dialog") - sess = {key: sess[key] for key in order if key in sess} - sidx = ctx.new_session(sess) - ctx.rs_session[k] = sidx + ctx.sessions[sidx] = {key: sess[key] for key in order if key in sess} for r in recs: ctx.dialog_sessions.setdefault(r, []).append(sidx) fields_moved = [f for f in ("start", "duration", "parties", "session_id", "originator") if f in rs] @@ -720,21 +795,54 @@ def _step_t7_recording_sets(ctx: _Context) -> None: "(A.1 silent about them); Session start/duration/parties fall back to values derived from the recordings when absent.", "AMB-4", dialog=k, session=sidx, ) - if ctx.catch_all is not None: + extra = sorted( + set(rs) - {"type", "recordings", "start", "duration", "parties", "session_id", "originator", "party_history"} + ) + if extra: + ctx.report.add( + "T7", UNRESOLVED, + f"recording-set dialog[{k}] had parameter(s) {extra} with no Session equivalent; not migrated. " + "Original kept in report.removed_dialogs.", None, dialog=k, dropped={f: rs[f] for f in extra}, + ) + if ctx.catch_all is not None and recs: ctx.report.add( "T7", UNRESOLVED, f"Session {sidx} (recording-set dialog[{k}]) overlaps Session {ctx.catch_all}, which also lists its " "recordings; A.1 does not say whether to relate them, so no Session_Reference was added.", "AMB-1", session=sidx, catch_all=ctx.catch_all, ) - for r in recs: - if isinstance(dialogs, list) and isinstance(dialogs[r], dict): - dialogs[r].pop("recording_set", None) - # Remove any stray recording_set / recordings on kept dialogs. + # recording_set has been consumed above; recordings is only legal on recording-sets. if isinstance(dialogs, list): for i in ctx.kept(): dialogs[i].pop("recording_set", None) - dialogs[i].pop("recordings", None) + if "recordings" in dialogs[i]: + ctx.report.add( + "T7", UNRESOLVED, + f"dialog[{i}] ({ctx.dialogs[i].get('type')!r}) had a recordings parameter, which only a " + "recording-set may carry; removed.", None, dialog=i, recordings=dialogs[i].pop("recordings"), + ) + + +def _first_slot_is_null(parties: Any) -> bool: + return isinstance(parties, list) and len(parties) > 0 and parties[0] is None + + +def _unknown_first_party(ctx: _Context, step: str, i: int, kind: str, role: str) -> int: + """The first party slot of a text/incomplete Dialog is null: its sender is unknown. + + The next party in the list is a receiver, so promoting it would invent a + sender. An empty Party Object stands in (4.2.4: "If the originator is not + known, an empty Party Object ... may be used"), and it becomes the Session + originator so the first receiver is not implied to be the originator. + """ + e = ctx.empty_party(step, role) + ctx.originators[i] = e + ctx.report.add( + step, UNRESOLVED, + f"{kind} dialog[{i}] has null as its first party, so its {role} is unknown; an empty Party " + f"Object (parties[{e}]) stands in rather than promoting a receiver.", None, dialog=i, party=e, + ) + return e def _step_t8_text_parties(ctx: _Context) -> None: @@ -750,7 +858,12 @@ def _step_t8_text_parties(ctx: _Context) -> None: ctx.report.add("T8", UNRESOLVED, f"text dialog[{i}] has no parties; sender and receivers unknown.", None, dialog=i) continue orig = ctx.dialogs[i].get("originator") - sender = orig if _is_int(orig) else p[0] + if _is_int(orig): + sender = orig + elif _first_slot_is_null(ctx.dialogs[i].get("parties")): + sender = _unknown_first_party(ctx, "T8", i, "text", "sender") + else: + sender = p[0] dialogs[i]["parties"] = [sender] ctx.receivers[i] = p if sender in p else [sender] + p @@ -767,7 +880,12 @@ def _step_t9_incomplete_parties(ctx: _Context) -> None: if not p: continue orig = ctx.dialogs[i].get("originator") - who = orig if _is_int(orig) else p[0] + if _is_int(orig): + who = orig + elif _first_slot_is_null(ctx.dialogs[i].get("parties")): + who = _unknown_first_party(ctx, "T9", i, "incomplete", "originator") + else: + who = p[0] dialogs[i]["parties"] = [who] ctx.receivers[i] = p if who in p else [who] + p @@ -898,6 +1016,34 @@ def targets(e: int) -> Tuple[List[int], Optional[int]]: ) +def _step_t10c_unscoped_attachments(ctx: _Context) -> None: + """Scope an attachment that has neither ``dialog`` nor ``session``. + + Core-04 required ``dialog``, but older writers omitted it, so stored data + has such attachments. Core-05 needs one of ``dialog`` or ``session`` + (4.6.4). Only when the result has exactly one Session is the scope + unambiguous (that Session is the whole conversation); it is then set and + reported. Otherwise nothing is invented and the gap is reported. + """ + for n, att in enumerate(ctx.out.get("attachments") or []): + if not isinstance(att, dict) or "dialog" in att or "session" in att: + continue + if len(ctx.sessions) == 1: + att["session"] = 0 + ctx.report.add( + "T10c", INFERRED, + f"attachments[{n}] had neither dialog nor session; scoped to the only Session (session=0).", + None, attachment=n, purpose=att.get("purpose"), + ) + else: + ctx.report.add( + "T10c", UNRESOLVED, + f"attachments[{n}] has neither dialog nor session and the vCon has {len(ctx.sessions)} " + "Sessions, so its scope cannot be chosen; set dialog or session by hand.", + None, attachment=n, purpose=att.get("purpose"), + ) + + def _step_t13_unwrap_signed(ctx: _Context) -> None: """T13: a signed vCon is migrated as its unsigned payload; it must be signed again. @@ -1012,10 +1158,11 @@ class MigrationStep: MigrationStep("T6", "Dialog originator -> Session originator", "A.1 bullet 5", _step_t6_originator), MigrationStep("T2", "Add a Session referencing all Dialogs", "A.1 bullet 2", _step_t2_sessions), MigrationStep("T7", "recording-set Dialog -> Session", "A.1 bullet 9", _step_t7_recording_sets), - MigrationStep("T3", "party_history -> Events", "A.1 bullet 3", _step_t3_party_history), MigrationStep("T4", "transfer Dialog -> transfer Events (with T5 Session references)", "A.1 bullet 4", _step_t4_transfers), + MigrationStep("T3", "party_history -> Events", "A.1 bullet 3", _step_t3_party_history), MigrationStep("T10", "Removed Dialogs -> {} in place", "A.1 bullet 10; 4.5.1", _step_t10_blank_removed), MigrationStep("T10b", "Re-point analysis/attachment references to removed Dialogs", "AMB-2", _step_t10b_retarget), + MigrationStep("T10c", "Scope unscoped attachments to the only Session", "4.6.4 (A.1 silent)", _step_t10c_unscoped_attachments), MigrationStep("T11", "redacted -> redacted_from", "A.1 bullet 7", _step_t11), MigrationStep("T12", "amended -> amended_from", "A.1 bullet 8", _step_t12), MigrationStep("T14", "extensions lists every extension in use", "A.1 bullet 12; 4.1.3", _step_t14_extensions), @@ -1065,6 +1212,12 @@ def migrate_0_4_0_to_0_5_0(vcon: Any, *, strict: bool = False) -> MigrationResul if v is not None and v != SOURCE_VERSION: raise MigrationError(f"cannot migrate: input vcon is {v!r}, expected {SOURCE_VERSION!r}") if v is None: + markers = sorted(k for k in _V050_ONLY_KEYS if k in ctx.out) + if markers: + raise MigrationError( + f"cannot migrate: input has no 'vcon' parameter but has 0.5.0-only " + f"parameter(s) {markers}; it is already 0.5.0 (vcon is optional there)" + ) report.add("T13", INFO, "Input has no 'vcon' parameter; treated as 0.4.0.") out = ctx.out diff --git a/tests/test_migration_0_4_0.py b/tests/test_migration_0_4_0.py index 2a5e1e4..0f8e057 100644 --- a/tests/test_migration_0_4_0.py +++ b/tests/test_migration_0_4_0.py @@ -70,7 +70,7 @@ class TestTableDriven: def test_one_entry_per_transform_step(self): ids = [s.id for s in MIGRATION_STEPS] assert sorted(ids) == sorted( - ["T1", "T2", "T3", "T4", "T6", "T7", "T8", "T9", "T9b", "T10", "T11", "T12", "T13", "T14", "T15", "T10b"] + ["T1", "T2", "T3", "T4", "T6", "T7", "T8", "T9", "T9b", "T10", "T11", "T12", "T13", "T14", "T15", "T10b", "T10c"] ) assert len(ids) == len(set(ids)) assert all(s.source and s.title and callable(s.func) for s in MIGRATION_STEPS) @@ -627,9 +627,12 @@ def test_signed_payload_must_be_0_4_0(self): def test_vcon_load_of_a_library_signed_0_4_0_document(self): payload = v04(dialog=[rec()]) signed = self.signed(payload) + # Loading keeps the signature (verify first); migration is explicit. v = Vcon(signed) - assert v.vcon == "0.5.0" - assert v.migration_report.resign_required + assert v.migration_report is None and v.vcon_dict["payload"] == signed["payload"] + m = Vcon.migrate_0_4_0_to_0_5_0(signed) + assert m.vcon == "0.5.0" + assert m.migration_report.resign_required class TestT14Extensions: diff --git a/tests/test_migration_review.py b/tests/test_migration_review.py new file mode 100644 index 0000000..838094b --- /dev/null +++ b/tests/test_migration_review.py @@ -0,0 +1,198 @@ +"""Regression tests for migration defects found in review. + +Each test pins one case where the first port lost data, invented a value, or +broke a reference: the semantics here are the ones other ports copy. +""" + +import json +import warnings + +import pytest + +from vcon import Vcon, migrate_0_4_0_to_0_5_0, MigrationError +from vcon.migration import FALLBACK, INFERRED, UNRESOLVED +from tests.test_migration_0_4_0 import v04, rec, text, migrate, T0, T1, T2 + + +def kinds(report, kind, step=None): + return [e for e in report.entries if e.kind == kind and (step is None or e.step == step)] + + +class TestAlreadyMigratedInput: + def test_missing_vcon_with_sessions_is_refused_not_remigrated(self): + d = {"uuid": "u", "created_at": T0, "parties": [{}, {}], "dialog": [rec()], + "sessions": [{"start": T0, "parties": [1, 0], "dialog": [0]}], + "events": [{"type": "join", "time": T0, "sessions": 0, "party": 0}]} + with pytest.raises(MigrationError, match="already 0.5.0"): + migrate_0_4_0_to_0_5_0(d) + + @pytest.mark.parametrize("key", ["redacted_from", "amended_from", "redacted_strings"]) + def test_missing_vcon_with_other_050_only_keys_is_refused(self, key): + d = {"uuid": "u", "created_at": T0, key: {"uuid": "x"} if key != "redacted_strings" else []} + with pytest.raises(MigrationError, match="already 0.5.0"): + migrate_0_4_0_to_0_5_0(d) + + def test_missing_vcon_plain_040_shape_still_migrates(self): + d = v04(dialog=[rec()]) + del d["vcon"] + out, _ = migrate(d) + assert out["vcon"] == "0.5.0" and out["sessions"][0]["dialog"] == [0] + + +class TestRecordingSets: + def test_back_reference_only_membership_is_kept(self): + # recording names the set, set has no recordings list (core-04: recording_set SHOULD, recordings MUST) + out, report = migrate(v04(dialog=[rec(recording_set=1), {"type": "recording-set", "start": T0}])) + assert out["sessions"][1]["dialog"] == [0] + assert any("recording_set" in e.message for e in kinds(report, INFERRED, "T7")) + + def test_back_reference_merged_with_partial_recordings_list(self): + out, _ = migrate(v04(dialog=[rec(recording_set=2), rec(recording_set=2), + {"type": "recording-set", "start": T0, "recordings": [0]}])) + assert out["sessions"][1]["dialog"] == [0, 1] + + def test_recording_set_pointing_nowhere_is_reported(self): + _, report = migrate(v04(dialog=[rec(recording_set=5)])) + assert any("recording_set=5" in e.message for e in kinds(report, UNRESOLVED, "T7")) + + def test_nested_recording_set_becomes_child_reference(self): + out, _ = migrate(v04(dialog=[rec(), rec(), + {"type": "recording-set", "recordings": [0, 1]}, + {"type": "recording-set", "recordings": [2]}])) + # Session 1 <- dialog[2], Session 2 <- dialog[3] + assert out["sessions"][2]["sessions"] == [{"session": 1, "type": "child"}] + assert out["sessions"][1]["dialog"] == [0, 1] + + def test_nested_forward_reference_resolves(self): + out, _ = migrate(v04(dialog=[rec(), {"type": "recording-set", "recordings": [2]}, + {"type": "recording-set", "recordings": [0]}])) + assert out["sessions"][1]["sessions"] == [{"session": 2, "type": "child"}] + assert out["sessions"][2]["dialog"] == [0] + + def test_unmapped_recording_set_fields_are_reported_with_values(self): + _, report = migrate(v04(dialog=[rec(recording_set=1), { + "type": "recording-set", "recordings": [0], "application": "pbx", "meta": {"k": 1}}])) + e = [x for x in kinds(report, UNRESOLVED, "T7") if "no Session equivalent" in x.message] + assert e and e[0].details["dropped"] == {"application": "pbx", "meta": {"k": 1}} + + +class TestTransfers: + def test_transfer_originator_is_reported(self): + _, report = migrate(v04(dialog=[rec(), {"type": "transfer", "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 0, "start": T1, + "originator": 1}])) + e = [x for x in kinds(report, UNRESOLVED, "T4") if "no Event equivalent" in x.message] + assert e and e[0].details["dropped"]["originator"] == 1 + + def test_party_history_events_include_transfer_role_session(self): + # dialog[0] is in a recording-set and is the transfer's original call + out, _ = migrate(v04(dialog=[ + rec(recording_set=1, party_history=[{"party": 0, "time": T0, "event": "join"}]), + {"type": "recording-set", "recordings": [0]}, + {"type": "transfer", "transferee": 0, "transferor": 1, "transfer_target": 2, + "original": 0, "start": T1}, + ])) + sessions_of_0 = [n for n, s in enumerate(out["sessions"]) if 0 in s.get("dialog", [])] + join = [e for e in out["events"] if e["type"] == "join"][0] + assert sorted(join["sessions"]) == sorted(sessions_of_0) + assert len(sessions_of_0) == 3 + + def test_transfer_whose_original_is_recording_set_uses_its_session(self): + out, _ = migrate(v04(dialog=[rec(recording_set=1), {"type": "recording-set", "recordings": [0]}, + {"type": "transfer", "transferee": 0, "transferor": 1, + "transfer_target": 2, "original": 1, "target_dialog": 3, "start": T1}, + rec(parties=[0, 2], start=T2)])) + ev = out["events"][0] + assert ev["sessions"] == 1 and out["sessions"][1]["dialog"] == [0] + assert out["sessions"][ev["target_session"]]["dialog"] == [3] + + +class TestPartyHistory: + def test_unparseable_time_is_kept_in_the_report(self): + _, report = migrate(v04(dialog=[rec(party_history=[{"party": 0, "time": "yesterday-ish", "event": "join"}])])) + fb = kinds(report, FALLBACK, "T3") + assert fb and fb[0].details["original_time"] == "yesterday-ish" + + def test_no_time_and_no_dialog_start_falls_back_to_created_at(self): + d = rec(party_history=[{"party": 0, "event": "join"}]) + del d["start"] + out, report = migrate(v04(dialog=[d])) + assert out["events"][0]["time"] == "2022-06-21T13:53:00-04:00" + assert kinds(report, FALLBACK, "T3")[0].details["source"] == "vCon created_at" + + def test_no_time_strict_raises(self): + d = rec(party_history=[{"party": 0, "event": "join"}]) + del d["start"] + with pytest.raises(MigrationError): + migrate_0_4_0_to_0_5_0(v04(dialog=[d]), strict=True) + + def test_extension_parameters_are_carried_not_dropped(self): + out, report = migrate(v04(dialog=[rec(party_history=[ + {"party": 0, "time": T0, "event": "join", "x_reason": "callback", "channel": 3}])])) + ev = out["events"][0] + assert ev["x_reason"] == "callback" and "channel" not in ev + e = [x for x in kinds(report, UNRESOLVED, "T3") if "non-core" in x.message][0] + assert e.details["dropped"] == {"channel": 3} + + def test_party_history_on_text_and_incomplete(self): + out, _ = migrate(v04(dialog=[ + text(parties=[0, 1, 2], party_history=[{"party": 1, "time": T1, "event": "join"}]), + {"type": "incomplete", "start": T2, "parties": [1, 0], "disposition": "busy", + "party_history": [{"party": 1, "time": T2, "event": "drop"}]}, + ])) + assert [e["type"] for e in out["events"]] == ["join", "drop"] + assert all(e["sessions"] == 0 and "dialog" not in e for e in out["events"]) + assert all("party_history" not in d for d in out["dialog"]) + + +class TestNullFirstParty: + def test_text_with_null_sender_does_not_promote_a_receiver(self): + out, report = migrate(v04(dialog=[text(parties=[None, 1, 2])])) + sender = out["dialog"][0]["parties"][0] + assert sender not in (1, 2) + assert out["parties"][sender] == {} + s = out["sessions"][0] + assert s["parties"][0] == sender or s.get("originator") == sender + assert any("null" in e.message for e in kinds(report, UNRESOLVED, "T8")) + + def test_incomplete_with_null_originator_does_not_promote(self): + out, _ = migrate(v04(dialog=[{"type": "incomplete", "start": T0, "parties": [None, 2], + "disposition": "no-answer"}])) + who = out["dialog"][0]["parties"][0] + assert who != 2 and out["parties"][who] == {} + + def test_recording_null_channel_is_kept(self): + out, _ = migrate(v04(dialog=[rec(parties=[None, 1])])) + assert out["dialog"][0]["parties"] == [None, 1] + + +class TestOriginator: + def test_originator_not_first_moves_to_session(self): + out, _ = migrate(v04(dialog=[text(parties=[0, 1, 2], originator=2)])) + assert out["dialog"][0]["parties"] == [2] + assert out["sessions"][0]["parties"] == [0, 1, 2] + assert out["sessions"][0]["originator"] == 2 + + +class TestUnscopedAttachments: + def att(self, **kw): + a = {"purpose": "note", "start": T0, "party": 0, "body": "x", "encoding": "none", "mediatype": "text/plain"} + a.update(kw) + return a + + def test_single_session_scope_is_inferred_and_reported(self): + out, report = migrate(v04(dialog=[rec()], attachments=[self.att()])) + assert out["attachments"][0]["session"] == 0 + assert kinds(report, INFERRED, "T10c") + + def test_several_sessions_leave_it_unresolved(self): + out, report = migrate_0_4_0_to_0_5_0( + v04(dialog=[rec(recording_set=1), {"type": "recording-set", "recordings": [0]}], + attachments=[self.att()])) + assert "session" not in out["attachments"][0] and "dialog" not in out["attachments"][0] + assert kinds(report, UNRESOLVED, "T10c") + + def test_lawful_basis_keeps_dialog_only(self): + lb = self.att(purpose="lawful_basis", dialog=0, body={}, encoding="json", mediatype="application/json") + out, _ = migrate(v04(dialog=[rec()], attachments=[lb])) + assert out["attachments"][0]["dialog"] == 0 and "session" not in out["attachments"][0] From e141dc6119118d2361c1dcd2a0fb7c63aad9ebc6 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:12:14 -0500 Subject: [PATCH 05/12] Keep signed and opted-out 0.4.0 input intact on load Migrating on load rewrote a signed 0.4.0 vCon as its unsigned payload, so verify() could no longer run and a load-and-save path replaced a signed record with an unsigned one. A signed 0.4.0 vCon is now kept as loaded; migration is explicit through Vcon.migrate_0_4_0_to_0_5_0(). An unmigrated 0.4.0 dict (signed, or migrate_legacy=False) is no longer run through the 0.5.0 property allow-lists, which stripped party_history, originator, redacted and the other legacy parameters in strict and meta mode. Co-Authored-By: Claude Opus 5.5 --- src/vcon/vcon.py | 35 ++++++++++++++++++++++++++++++----- tests/test_load_legacy.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 tests/test_load_legacy.py diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 2492cde..98b50fc 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -291,10 +291,13 @@ def __init__( """ Initialize a Vcon object from a dictionary. - A dict that declares ``"vcon": "0.4.0"`` (or a signed vCon whose payload - does) is migrated to 0.5.0 here, using ``migrate_0_4_0_to_0_5_0``. The - report is kept in ``self.migration_report``. A dict with any other (or no) - ``vcon`` value is taken as is. + A dict that declares ``"vcon": "0.4.0"`` is migrated to 0.5.0 here, using + ``migrate_0_4_0_to_0_5_0``. The report is kept in ``self.migration_report``. + A signed vCon whose payload is 0.4.0 is NOT migrated on load, because + migrating drops the signature: verify it, then call + ``Vcon.migrate_0_4_0_to_0_5_0()``. An unmigrated 0.4.0 dict (signed, or + ``migrate_legacy=False``) is kept as is; ``property_handling`` is not + applied to it. A dict with any other (or no) ``vcon`` value is taken as is. Args: vcon_dict: A dictionary representing a vCon. Defaults to an empty dict. @@ -325,7 +328,18 @@ def __init__( #: MigrationReport when the input was migrated from 0.4.0, else None. self.migration_report: Optional[MigrationReport] = None - if migrate_legacy and self._is_legacy_0_4_0(vcon_dict): + legacy = self._is_legacy_0_4_0(vcon_dict) + signed_legacy = legacy and "vcon" not in vcon_dict + if signed_legacy: + # Migrating rewrites the payload, which drops the signature. Doing that + # implicitly would make verify() impossible and, on a load-and-save + # path, overwrite a signed record with an unsigned one. Keep it signed; + # migrate explicitly with Vcon.migrate_0_4_0_to_0_5_0() after verifying. + logger.warning( + "Signed 0.4.0 vCon loaded unmigrated; verify it, then call " + "Vcon.migrate_0_4_0_to_0_5_0() (the result must be signed again)" + ) + elif migrate_legacy and legacy: migrated, self.migration_report = _migrate_0_4_0_to_0_5_0( vcon_dict, strict=strict_migration ) @@ -335,6 +349,17 @@ def __init__( ) vcon_dict = migrated + if legacy and self.migration_report is None: + # An unmigrated 0.4.0 (or signed 0.4.0) dict is kept as is: the 0.5.0 + # allow-lists of property_handling would strip its legacy parameters + # (party_history, originator, redacted, ...), which is silent data loss. + if self.property_handling != PROPERTY_HANDLING_DEFAULT: + logger.warning( + "0.4.0 vCon kept unmigrated: property_handling=%r not applied", self.property_handling + ) + self.vcon_dict = json.loads(json.dumps(vcon_dict)) + return + # Version field is now optional - no version management required # Handle created_at diff --git a/tests/test_load_legacy.py b/tests/test_load_legacy.py new file mode 100644 index 0000000..640b4da --- /dev/null +++ b/tests/test_load_legacy.py @@ -0,0 +1,33 @@ +"""Loading 0.4.0 input: what is migrated implicitly and what is kept as is.""" + +import json +import warnings + +from vcon import Vcon +from tests.test_migration_0_4_0 import v04, rec, T0 + + +class TestLoadPath: + def signed(self, payload): + import base64 + b = lambda o: base64.urlsafe_b64encode(json.dumps(o).encode()).decode().rstrip("=") + return {"payload": b(payload), "signatures": [{"protected": b({"alg": "RS256"}), "signature": "c2ln", "header": {"x5c": []}}]} + + def test_signed_040_is_not_migrated_on_load(self): + s = self.signed(v04(dialog=[rec()])) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + v = Vcon(s) + assert v.migration_report is None + assert v.vcon_dict["signatures"] == s["signatures"] and v.vcon_dict["payload"] == s["payload"] + + def test_signed_040_explicit_migration_still_works(self): + v = Vcon.migrate_0_4_0_to_0_5_0(self.signed(v04(dialog=[rec()]))) + assert v.migration_report.resign_required and "signatures" not in v.vcon_dict + + def test_opt_out_keeps_legacy_fields_even_in_strict_property_mode(self): + d = v04(redacted={"uuid": "x", "type": "PII"}, + dialog=[rec(originator=1, party_history=[{"party": 0, "time": T0, "event": "join"}])]) + v = Vcon(d, property_handling="strict", migrate_legacy=False) + assert v.vcon_dict["redacted"] == {"uuid": "x", "type": "PII"} + assert v.vcon_dict["dialog"][0]["party_history"] and v.vcon_dict["dialog"][0]["originator"] == 1 From 79828b7524d3f70db4cefe23c00dbb2a7b2934f0 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:13:59 -0500 Subject: [PATCH 06/12] Stop inventing attachment scope With neither dialog nor session, add_attachment(), add_lawful_basis_attachment() and add_wtf_transcription_attachment() scoped the attachment to every Session and added an empty placeholder Session when there was none. For a consent record that asserts a scope nobody stated. A given dialog_index was also widened to every Session listing that dialog. Now the scope is defaulted only when it is unambiguous (exactly one Session, which is then the whole conversation); otherwise ValueError. dialog_index alone stays dialog-only, with a warning for lawful_basis. add_tag() keeps the whole-vCon behaviour since tags describe the entire vCon. Co-Authored-By: Claude Opus 5.5 --- API_REFERENCE.md | 2 +- CHANGELOG.md | 12 +++-- MIGRATION_GUIDE.md | 2 +- src/vcon/vcon.py | 98 +++++++++++++++++++---------------- tests/test_core05_changes.py | 53 +++++++++++++------ tests/test_core05_examples.py | 1 + tests/test_vcon.py | 20 +++---- 7 files changed, 113 insertions(+), 75 deletions(-) diff --git a/API_REFERENCE.md b/API_REFERENCE.md index ec711f5..559ee8a 100644 --- a/API_REFERENCE.md +++ b/API_REFERENCE.md @@ -788,7 +788,7 @@ Attachment(purpose: str, body: Any = None, encoding: str = "none", mediatype=Non - `body` (Any): Content of attachment - `encoding` (str): Encoding format ("base64url", "json", "none") - `party` (int): Party index (default 0) -- `dialog` (int), `session` (int or list): at least one is required; `Vcon.add_attachment()` fills `session` with every Session when neither is given +- `dialog` (int), `session` (int or list): at least one is required; `Vcon.add_attachment()` sets `session` to the only Session when the vCon has exactly one and neither is given, and raises `ValueError` otherwise #### Methods diff --git a/CHANGELOG.md b/CHANGELOG.md index 5057976..fa22883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,10 +52,14 @@ Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. incomplete Dialog has no content); `details` is kept in `metadata["details"]`. - **Breaking:** attachments need `party` plus `dialog` or `session`. The `dialog` default of 0 is gone. With neither given, `add_attachment()`, - `add_tag()`, `add_lawful_basis_attachment()` and - `add_wtf_transcription_attachment()` scope the attachment to every Session and - add an empty placeholder Session if there is none. `add_lawful_basis_attachment()` - and `add_wtf_transcription_attachment()` take `session_index`. + `add_lawful_basis_attachment()` and `add_wtf_transcription_attachment()` use + the only Session when the vCon has exactly one and raise `ValueError` + otherwise; no placeholder Session is added and a given `dialog_index` is never + widened to a Session. `add_tag()` (whole-vCon metadata) lists every Session + and adds an empty placeholder Session when there is none. + `add_lawful_basis_attachment()` and `add_wtf_transcription_attachment()` take + `session_index`; `add_lawful_basis_attachment()` logs a warning when the scope + is dialog only or `party_index` is defaulted. - **Breaking:** `add_analysis()` takes `dialog` as an optional keyword. - **Breaking:** `is_valid()` now also checks: a Session exists when there is dialog or events; all Session, Event, attachment and analysis references; the diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index bf12889..f61400a 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -35,7 +35,7 @@ Code that changes: | `Dialog(originator=...)` | `Session(originator=...)` | | `Dialog(parties=[sender, *receivers])` | `Dialog(parties=[sender])`; receivers in `Session(parties=[...])` | | `recording-set` Dialog | `Session(dialog=[...])` | -| attachments always `dialog=0` by default | attachments default to `session=[all Sessions]`; pass `dialog` or `session` | +| attachments always `dialog=0` by default | pass `dialog` or `session`; with neither, the only Session is used when exactly one exists, else `ValueError` (`add_tag()` lists every Session) | | `vcon.sign(key)` accepts any header | `alg` "none" raises `AlgorithmNotPermittedError` on `sign()` and `verify()` | Also new: `is_valid()` now reports a missing Session when dialog or events exist, a missing `extensions` entry diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 98b50fc..1334fc0 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -146,8 +146,8 @@ def __init__( Under core-05 (section 4.6) an attachment needs ``party`` and at least one of ``dialog`` or ``session``. ``party`` defaults to 0. Neither ``dialog`` nor ``session`` is defaulted here, because the right index - depends on the vCon; ``Vcon.add_attachment()`` fills in the vCon's - Sessions when neither is given. + depends on the vCon; ``Vcon.add_attachment()`` defaults it only when the + vCon has exactly one Session. Args: purpose: The purpose of the attachment @@ -689,27 +689,42 @@ def _resolve_attachment_scope( self, dialog: Optional[int] = None, session: Optional[Union[int, List[int]]] = None, + whole_vcon: bool = False, ) -> Dict[str, Any]: """ Work out the ``dialog`` / ``session`` scope for a new attachment. - Core-05 section 4.6 needs at least one of the two. When the caller gives - neither, the attachment is scoped to every Session in the vCon; if the - vCon has no Session yet, an empty placeholder Session is added (an empty - Session Object is permitted) and referenced. + Core-05 section 4.6 needs at least one of the two. The caller's values + are used as given. With neither given, the scope is defaulted only when + it is unambiguous: the vCon has exactly one Session, which is then the + whole conversation. Otherwise ``ValueError`` is raised, because picking + a Session (or adding a placeholder one) would invent the scope. + + ``whole_vcon=True`` is for library metadata that describes the whole + vCon (``add_tag``): every Session is listed, and an empty placeholder + Session is added when there is none. """ scope: Dict[str, Any] = {} if dialog is not None: scope["dialog"] = dialog if session is not None: scope["session"] = session - if not scope: - sessions = self.vcon_dict.setdefault("sessions", []) + if scope: + return scope + sessions = self.vcon_dict.get("sessions") or [] + if whole_vcon: if not sessions: - sessions.append({}) - logger.info("Added placeholder Session to scope an attachment") - scope["session"] = list(range(len(sessions))) - return scope + self.vcon_dict.setdefault("sessions", []).append({}) + sessions = self.vcon_dict["sessions"] + logger.warning("Added an empty placeholder Session to scope the tags attachment") + return {"session": list(range(len(sessions)))} + if len(sessions) == 1: + return {"session": 0} + raise ValueError( + "An attachment needs dialog or session (core-05 section 4.6). The vCon has " + f"{len(sessions)} Sessions, so no default can be chosen; pass dialog= or session= " + "(add a Session first with add_session() if the vCon has none)." + ) def add_tag(self, tag_name: str, tag_value: str) -> None: """ @@ -739,7 +754,7 @@ def add_tag(self, tag_name: str, tag_value: str) -> None: "start": self.vcon_dict.get("created_at"), "party": 0, } - tags_attachment.update(self._resolve_attachment_scope()) + tags_attachment.update(self._resolve_attachment_scope(whole_vcon=True)) self.vcon_dict["attachments"].append(tags_attachment) else: # Normalize a legacy (pre-0.10.0 / -02 convention) JSON-string @@ -868,14 +883,14 @@ def add_lawful_basis_attachment( """ Add a lawful basis attachment to the vCon. - The attachment has ``purpose`` ``"lawful_basis"`` and, under core-05, - is scoped to Sessions with ``session`` plus ``party``. ``party`` is the - party recording the basis (default 0). ``session`` is ``session_index`` - if given; otherwise the Sessions that list ``dialog_index`` (when given - and found); otherwise every Session in the vCon (an empty placeholder - Session is added if there is none). ``dialog`` is added only when - ``dialog_index`` is given. The ``lawful_basis`` extension name is added - to ``extensions``. + The attachment has ``purpose`` ``"lawful_basis"``. Under core-05 it is + scoped with ``party`` plus ``session``: pass ``session_index`` (and + ``party_index``, the party that records the basis). The scope is never + widened or invented: ``dialog_index`` alone gives a dialog-only scope (a + warning is logged, because 0.5.0 scopes a basis to Sessions), and with + neither index the only Session is used when the vCon has exactly one; + otherwise ``ValueError`` is raised. ``party`` defaults to 0 with a + warning. The ``lawful_basis`` extension name is added to ``extensions``. Args: lawful_basis: The lawful basis type (consent, contract, etc.) @@ -911,13 +926,19 @@ def add_lawful_basis_attachment( # party is required (default 0, add_tag()'s convention); core-05 # also needs dialog or session, and the basis is scoped to Sessions. + if party_index is None: + logger.warning( + "lawful_basis attachment: party_index not given, defaulting to 0; " + "it should be the party that records the basis" + ) attachment["party"] = party_index if party_index is not None else 0 - attachment.update( - self._resolve_attachment_scope( - dialog=dialog_index, - session=session_index if session_index is not None - else self._sessions_for_dialog(dialog_index), + if session_index is None and dialog_index is not None: + logger.warning( + "lawful_basis attachment scoped by dialog only; core-05 scopes a basis " + "to Sessions, pass session_index" ) + attachment.update( + self._resolve_attachment_scope(dialog=dialog_index, session=session_index) ) # Fill in mediatype/start, also required by the schema, unless @@ -949,8 +970,9 @@ def add_wtf_transcription_attachment( """ Add a WTF transcription attachment to the vCon. - Scoped like ``add_lawful_basis_attachment``: ``dialog_index`` and/or - ``session_index``, else every Session in the vCon. + Scoped by ``dialog_index`` and/or ``session_index`` as given; with + neither, the only Session when the vCon has exactly one, else + ``ValueError`` (see ``add_attachment``). Args: transcript: Transcript information dictionary @@ -985,11 +1007,7 @@ def add_wtf_transcription_attachment( attachment["party"] = party_index if party_index is not None else 0 attachment.update( - self._resolve_attachment_scope( - dialog=dialog_index, - session=session_index if session_index is not None - else self._sessions_for_dialog(dialog_index), - ) + self._resolve_attachment_scope(dialog=dialog_index, session=session_index) ) # Fill in mediatype/start, also required by the schema, unless @@ -1073,16 +1091,6 @@ def add_wtf_transcription_analysis( except ImportError: raise RuntimeError("WTF extension not available") - def _sessions_for_dialog(self, dialog_index: Optional[int]) -> Optional[List[int]]: - """Indices of the Sessions that list ``dialog_index``, or None if there are none.""" - if dialog_index is None: - return None - found = [ - n for n, s in enumerate(self.vcon_dict.get("sessions", [])) - if isinstance(s, dict) and dialog_index in (s.get("dialog") or []) - ] - return found or None - def find_lawful_basis_attachments(self, party_index: Optional[int] = None) -> List[Dict[str, Any]]: """ Find lawful basis attachments in the vCon. @@ -1275,8 +1283,8 @@ def add_attachment( Core-05 needs ``party`` plus ``dialog`` or ``session``. ``party`` defaults to 0. If neither ``dialog`` nor ``session`` is given, the attachment is - scoped to every Session in the vCon (an empty placeholder Session is added - if there is none). + scoped to the only Session when the vCon has exactly one; otherwise + ``ValueError`` is raised rather than inventing a scope. Args: purpose: The purpose of the attachment diff --git a/tests/test_core05_changes.py b/tests/test_core05_changes.py index 2336215..e896962 100644 --- a/tests/test_core05_changes.py +++ b/tests/test_core05_changes.py @@ -108,13 +108,35 @@ def test_bad_references_are_errors(self): assert any("invalid party index: 7" in e for e in errors) assert any("invalid session index: 3" in e for e in errors) - def test_default_scope_is_every_session(self): + def test_default_scope_is_the_only_session(self): v = _base() - v.add_session(Session(start=T)) v.add_attachment("x", body="b") - assert v.vcon_dict["attachments"][0]["session"] == [0, 1] + assert v.vcon_dict["attachments"][0]["session"] == 0 assert v.vcon_dict["attachments"][0]["party"] == 0 + def test_no_default_scope_with_several_sessions(self): + v = _base() + v.add_session(Session(start=T)) + with pytest.raises(ValueError, match="dialog or session"): + v.add_attachment("x", body="b") + assert v.vcon_dict["attachments"] == [] + + def test_no_placeholder_session_is_invented(self): + v = Vcon.build_new() + with pytest.raises(ValueError, match="dialog or session"): + v.add_attachment("x", body="b") + assert v.sessions == [] + + def test_tags_describe_the_whole_vcon(self): + v = Vcon.build_new() + v.add_tag("k", "v") + assert v.sessions == [{}] + assert v.vcon_dict["attachments"][0]["session"] == [0] + w = _base() + w.add_session(Session(start=T)) + w.add_tag("k", "v") + assert w.vcon_dict["attachments"][0]["session"] == [0, 1] + def test_attachment_class_has_session_and_no_dialog_default(self): a = Attachment("p", body="b", session=[0]) d = a.to_dict() @@ -316,23 +338,25 @@ def test_attachment_carries_session_and_party(self): v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS, party_index=1) att = v.find_lawful_basis_attachments()[0] assert att["purpose"] == "lawful_basis" - assert att["session"] == [0] + assert att["session"] == 0 assert att["party"] == 1 assert "dialog" not in att - def test_default_scope_is_all_sessions(self): + def test_no_default_scope_with_several_sessions(self): v = _base() v.add_session(Session(start=T)) - v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS) - assert v.find_lawful_basis_attachments()[0]["session"] == [0, 1] + with pytest.raises(ValueError, match="dialog or session"): + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS) + assert v.find_lawful_basis_attachments() == [] - def test_dialog_index_adds_dialog_and_uses_sessions_listing_it(self): + def test_dialog_index_alone_is_not_widened_to_a_session(self): + # A consent record for one dialog must not silently cover the whole Session. v = _base() v.add_session(Session(start=T)) v.add_dialog(Dialog(type="text", start=T, parties=[0], body="x", mediatype="text/plain", encoding="none"), session=1) v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS, dialog_index=0) att = v.find_lawful_basis_attachments()[0] - assert att["dialog"] == 0 and att["session"] == [1] + assert att["dialog"] == 0 and "session" not in att def test_explicit_session_index(self): v = _base() @@ -340,13 +364,12 @@ def test_explicit_session_index(self): v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS, session_index=1) assert v.find_lawful_basis_attachments()[0]["session"] == 1 - def test_placeholder_session_is_added_when_there_is_none(self): + def test_no_placeholder_session_is_invented(self): v = Vcon.build_new() v.add_party(Party(name="A")) - v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS) - assert v.sessions == [{}] - assert v.find_lawful_basis_attachments()[0]["session"] == [0] - assert v.is_valid() == (True, []) + with pytest.raises(ValueError, match="dialog or session"): + v.add_lawful_basis_attachment(lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=self.GRANTS) + assert v.sessions == [] def test_wtf_attachment_is_scoped_too(self): v = _base() @@ -355,7 +378,7 @@ def test_wtf_attachment_is_scoped_too(self): segments=[{"id": 0, "start": 0.0, "end": 1.0, "text": "hi", "confidence": 0.9}], metadata={"created_at": T, "processed_at": T, "provider": "p", "model": "m"}, ) - assert v.find_wtf_attachments()[0]["session"] == [0] + assert v.find_wtf_attachments()[0]["session"] == 0 class TestRedactedStrings: diff --git a/tests/test_core05_examples.py b/tests/test_core05_examples.py index 02162c4..85ea2df 100644 --- a/tests/test_core05_examples.py +++ b/tests/test_core05_examples.py @@ -108,6 +108,7 @@ def test_library_built_vcon_with_every_object_kind_validates(): vcon.add_lawful_basis_attachment( lawful_basis="consent", expiration="2030-01-01T00:00:00Z", purpose_grants=[{"purpose": "recording", "granted": True, "granted_at": T}], + party_index=0, session_index=[0, 1, 2], ) vcon.add_analysis(type="summary", vendor="v", body="s", dialog=0, sessions=[0], attachment=0) vcon.add_wtf_transcription_analysis( diff --git a/tests/test_vcon.py b/tests/test_vcon.py index 5d57b8d..eb8613b 100644 --- a/tests/test_vcon.py +++ b/tests/test_vcon.py @@ -226,23 +226,25 @@ def test_tags() -> None: def test_add_attachment(): vcon = Vcon() + # start and party are required on every attachment, plus dialog or + # session (draft-ietf-vcon-vcon-core-05 section 4.6). add_attachment() + # fills start (the vCon's created_at) and party (0). The scope is only + # defaulted when the vCon has exactly one Session; with none it is an error + # rather than an invented placeholder Session. + with pytest.raises(ValueError, match="dialog or session"): + vcon.add_attachment(purpose="test_purpose", body="test_body") + vcon.add_session() attachment = vcon.add_attachment(purpose="test_purpose", body="test_body") assert len(vcon.vcon_dict["attachments"]) == 1 - # start and party are required on every attachment, plus dialog or - # session (draft-ietf-vcon-vcon-core-05 section 4.6). add_attachment() - # fills them in: start defaults to the vCon's created_at, party to 0, and - # with neither dialog nor session given the attachment is scoped to every - # Session (an empty placeholder Session is added when there is none). assert vcon.vcon_dict["attachments"][0] == { "purpose": "test_purpose", "body": "test_body", "encoding": "none", "start": vcon.created_at, "party": 0, - "session": [0], + "session": 0, } - assert vcon.vcon_dict["sessions"] == [{}] assert isinstance(attachment, Attachment) @@ -292,14 +294,14 @@ def test_get_tag() -> None: def test_find_attachment_by_purpose() -> None: vcon = Vcon.build_new() - vcon.add_attachment(body={"key": "value"}, purpose="test_purpose") + vcon.add_attachment(body={"key": "value"}, purpose="test_purpose", session=0) assert vcon.find_attachment_by_purpose("test_purpose") == { "purpose": "test_purpose", "body": {"key": "value"}, "encoding": "none", "start": vcon.created_at, "party": 0, - "session": [0], + "session": 0, } assert vcon.find_attachment_by_purpose("nonexistent_purpose") is None From 38a6985c37dc8a34acd9a80bda7aa5760a964d5d Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:14:56 -0500 Subject: [PATCH 07/12] Never emit audio/video Dialog types; warn on read Core-05 section 4.5.1 defines recording, text and incomplete (or an extension value). Dialog(type="audio"/"video") now warns and builds a "recording", and the video helpers write "recording"; the media kind stays in mediatype. A stored vCon with audio/video Dialogs still validates, with a warning. Validation also warns on a Session originator equal to its first party (4.2.4) and on Session or attachment references to an empty placeholder Dialog. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++-- src/vcon/dialog.py | 24 +++++++++++++++++++--- src/vcon/validation.py | 20 +++++++++++++++++- tests/test_core05_changes.py | 39 ++++++++++++++++++++++++++++++++++++ tests/test_dialog.py | 10 ++++----- tests/test_vcon.py | 12 +++++------ 6 files changed, 94 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa22883..d2f8f8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,10 @@ Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. are preserved. Use `migrate_legacy=False` to keep the raw 0.4.0 dict. - **Breaking:** `Vcon.redacted` and `Vcon.amended` are now `redacted_from` and `amended_from`. -- **Breaking:** Dialog types are `recording`, `text` and `incomplete` (plus the - library's `audio` and `video` conveniences). The `transfer` type and the +- **Breaking:** Dialog types are `recording`, `text` and `incomplete`. + `Dialog(type="audio" | "video")` still works but warns (DeprecationWarning) + and builds a `recording`; the video helpers also write `recording`. On read, + `audio`/`video` Dialogs are accepted and `get_validation_warnings()` notes them. The `transfer` type and the `recording-set` type are gone, as are the Dialog parameters `party_history`, `originator`, `transferee`, `transferor`, `transfer_target`, `original`, `consultation`, `target_dialog`, `transfer`, `recordings` and `recording_set`; diff --git a/src/vcon/dialog.py b/src/vcon/dialog.py index 5ec79c7..489bc48 100644 --- a/src/vcon/dialog.py +++ b/src/vcon/dialog.py @@ -4,6 +4,7 @@ import os import logger import tempfile +import warnings from datetime import datetime from typing import Optional, List, Dict, Union, Any, Tuple from dateutil import parser @@ -148,6 +149,10 @@ def _reject_removed_parameters(kwargs: Dict[str, Any]) -> None: ) +#: Accepted on input for backward compatibility, normalized to "recording". +LEGACY_MEDIA_DIALOG_TYPES = ("audio", "video") + + class Dialog: """ A class representing a dialog segment in a vCon conversation. @@ -356,6 +361,19 @@ def __init__( if value is not None: setattr(self, key, value) + # "audio" and "video" are not core-05 Dialog types (4.5.1: recording, + # text, incomplete or an extension value). They are accepted for + # backward compatibility but never emitted: the Dialog is a recording, + # and the media kind stays in mediatype. + if type in LEGACY_MEDIA_DIALOG_TYPES: + warnings.warn( + f'Dialog type "{type}" is not a core-05 type; using "recording" ' + "(the media kind is carried by mediatype)", + DeprecationWarning, + stacklevel=2, + ) + self.type = "recording" + # Handling for specific dialog types if type == "incomplete" and not hasattr(self, "disposition"): raise ValueError("Dialog type 'incomplete' requires a disposition") @@ -605,8 +623,8 @@ def add_video_data(self, video_data, filename=None, mediatype=None, inline=True, Returns: None """ - # Set dialog type to video - self.type = "video" + # A video is a "recording" Dialog in core-05; mediatype says it is video. + self.type = "recording" # Auto-detect mediatype from filename if not provided if not mediatype and filename: @@ -884,7 +902,7 @@ def add_streaming_video_reference(self, reference_id, mediatype, metadata=None) Returns: None """ - self.type = "video" + self.type = "recording" self.url = f"stream://{reference_id}" self.mediatype = mediatype diff --git a/src/vcon/validation.py b/src/vcon/validation.py index 5c75161..8b936c0 100644 --- a/src/vcon/validation.py +++ b/src/vcon/validation.py @@ -17,7 +17,8 @@ SYNTAX_VERSION = "0.5.0" CORE_DIALOG_TYPES = ("recording", "text", "incomplete") -#: Dialog types the library itself builds although core-05 does not define them. +#: Dialog types older versions of this library wrote although core-05 does not +#: define them. Accepted on read with a warning; the library never writes them. LIBRARY_DIALOG_TYPES = ("audio", "video") CORE_ENCODINGS = ("base64url", "json", "none") CORE_DISPOSITIONS = ( @@ -285,6 +286,11 @@ def validate_vcon_dict( f"Dialog at index {i} has type '{dialog_type}', which was removed in 0.5.0 " "(use Events and Sessions; migrate with migrate_0_4_0_to_0_5_0())." ) + elif dialog_type in LIBRARY_DIALOG_TYPES and not ext_listed: + warnings.append( + f"Dialog at index {i} has type '{dialog_type}', which core-05 does not define; " + "it is read as 'recording' (written by older library versions)." + ) elif ( dialog_type not in CORE_DIALOG_TYPES and dialog_type not in LIBRARY_DIALOG_TYPES @@ -371,6 +377,16 @@ def validate_vcon_dict( for i, d in enumerate(dialogs): if isinstance(d, dict) and d and i not in referenced_dialogs: warnings.append(f"Dialog at index {i} is not referenced by any Session Object.") + empty_dialogs = {i for i, d in enumerate(dialogs) if isinstance(d, dict) and not d} + for n, s in enumerate(sessions): + if isinstance(s, dict): + if isinstance(s.get("parties"), list) and s["parties"] and s.get("originator") == s["parties"][0]: + warnings.append( + f"Session at index {n} has originator equal to its first party; originator is " + "only provided when the first party is not the originator (4.2.4)." + ) + for x in sorted(empty_dialogs & set(x for x in (s.get("dialog") or []) if _is_index(x))): + warnings.append(f"Session at index {n} lists dialog {x}, which is an empty placeholder Dialog.") # --- events ----------------------------------------------------------- for i, ev in enumerate(events): @@ -421,6 +437,8 @@ def validate_vcon_dict( dv = attachment["dialog"] if not _is_index(dv) or dv >= dialog_count: errors.append(f"Attachment at index {i} references invalid dialog index: {dv}") + elif dv in empty_dialogs: + warnings.append(f"Attachment at index {i} references dialog {dv}, an empty placeholder Dialog.") if "session" in attachment: sv = attachment["session"] vals = sv if isinstance(sv, list) else [sv] diff --git a/tests/test_core05_changes.py b/tests/test_core05_changes.py index e896962..80ef853 100644 --- a/tests/test_core05_changes.py +++ b/tests/test_core05_changes.py @@ -409,3 +409,42 @@ def test_version_absent_is_accepted(self): def test_other_versions_are_not_valid(self): v = Vcon({"uuid": "a", "created_at": T, "vcon": "0.3.0"}) assert not v.is_valid()[0] + + +class TestLegacyMediaDialogTypes: + """audio/video: accepted on read with a warning, never written (core-05 4.5.1).""" + + @pytest.mark.parametrize("kind", ["audio", "video"]) + def test_constructor_normalizes_to_recording(self, kind): + with pytest.warns(DeprecationWarning, match="not a core-05 type"): + d = Dialog(type=kind, start=T, parties=[0], mediatype=f"{kind}/mp4" if kind == "video" else "audio/wav", + url="https://e.com/x", content_hash="sha512-x") + assert d.to_dict()["type"] == "recording" + + def test_video_helpers_emit_recording(self): + d = Dialog(type="recording", start=T, parties=[0]) + d.add_streaming_video_reference("ref", "video/mp4") + assert d.type == "recording" and d.is_video() + + def test_read_is_a_warning_not_an_error(self): + v = _base() + v.vcon_dict["dialog"].append({"type": "video", "start": T, "parties": [0], "mediatype": "video/mp4", + "url": "https://e.com/v.mp4", "content_hash": "sha512-x"}) + v.vcon_dict["sessions"][0]["dialog"] = [0] + assert v.is_valid() == (True, []) + assert any("type 'video'" in w for w in v.get_validation_warnings()) + + +class TestValidationWarnings: + def test_redundant_session_originator_warns(self): + v = _base() + v.vcon_dict["sessions"][0]["originator"] = 0 + assert any("originator equal to its first party" in w for w in v.get_validation_warnings()) + + def test_reference_to_empty_dialog_warns(self): + v = _base() + v.add_dialog(Dialog.placeholder(), session=0) + v.add_attachment("x", body="b", dialog=0, mediatype="text/plain") + w = v.get_validation_warnings() + assert any("lists dialog 0, which is an empty placeholder" in x for x in w) + assert any("Attachment at index 0 references dialog 0" in x for x in w) diff --git a/tests/test_dialog.py b/tests/test_dialog.py index 72a5bbc..9fbb800 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -61,7 +61,7 @@ def test_initialization_with_missing_optional_parameters(self): ) # When & Then - assert dialog.type == "audio" + assert dialog.type == "recording" # audio/video normalize to recording assert not hasattr(dialog, "duration") assert not hasattr(dialog, "mediatype") @@ -141,7 +141,7 @@ def test_meta_variable_in_dialog(self): dialog = Dialog(type=type, start=start, parties=parties, meta=meta) - assert dialog.type == type + assert dialog.type == "recording" # audio/video normalize to recording assert dialog.start == start assert dialog.parties == parties assert dialog.meta == meta @@ -452,7 +452,7 @@ def test_video_type_dialog(self): ) assert dialog.is_video() - assert dialog.type == "video" + assert dialog.type == "recording" # audio/video normalize to recording # Check mediatype by using the to_dict method if direct attribute access isn't possible dialog_dict = dialog.to_dict() @@ -509,7 +509,7 @@ def test_add_video_data_inline(self): # Verify via to_dict dialog_dict = dialog.to_dict() - assert dialog_dict.get("type") == "video" + assert dialog_dict.get("type") == "recording" # audio/video normalize to recording assert dialog_dict.get("mediatype") == "video/mp4" assert dialog_dict.get("filename") == "test_video.mp4" assert "body" in dialog_dict @@ -575,7 +575,7 @@ def test_add_video_data_external(self, mocker): # Verify the dialog has the expected attributes dialog_dict = dialog.to_dict() - assert dialog_dict.get("type") == "video" + assert dialog_dict.get("type") == "recording" # audio/video normalize to recording assert dialog_dict.get("url") == url assert dialog_dict.get("mediatype") == "video/mp4" assert dialog_dict.get("filename") == "remote_video.mp4" diff --git a/tests/test_vcon.py b/tests/test_vcon.py index eb8613b..d29d835 100644 --- a/tests/test_vcon.py +++ b/tests/test_vcon.py @@ -1006,7 +1006,7 @@ def test_add_video_dialog(): # Verify it was added correctly assert len(vcon.dialog) == 1 - assert vcon.dialog[0]["type"] == "video" + assert vcon.dialog[0]["type"] == "recording" # audio/video normalize to recording assert vcon.dialog[0]["mediatype"] == "video/mp4" @pytest.mark.parametrize("format_name,mediatype", [ @@ -1071,7 +1071,7 @@ def test_dialog_property_handling(): # Verify properties are preserved dialog_dict = new_vcon.dialog[0] - assert dialog_dict["type"] == "video" + assert dialog_dict["type"] == "recording" # audio/video normalize to recording assert dialog_dict["mediatype"] == "video/mp4" assert dialog_dict["filename"] == "test_video.mp4" @@ -1253,7 +1253,7 @@ def test_video_metadata_in_vcon(): vcon.add_dialog(dialog) # Verify the basic properties - assert vcon.dialog[0]["type"] == "video" + assert vcon.dialog[0]["type"] == "recording" # audio/video normalize to recording assert vcon.dialog[0]["mediatype"] == "video/mp4" @pytest.mark.skip("Property handling mode tests need vCon implementation check") @@ -1298,7 +1298,7 @@ def test_load_save_file_with_videos(tmp_path): loaded_vcon = Vcon.load_from_file(str(temp_file)) # Verify video properties were preserved - assert loaded_vcon.dialog[0]["type"] == "video" + assert loaded_vcon.dialog[0]["type"] == "recording" # audio/video normalize to recording assert loaded_vcon.dialog[0]["mediatype"] == "video/mp4" assert loaded_vcon.dialog[0]["filename"] == "test_video.mp4" @@ -1351,7 +1351,7 @@ def test_integration_basic_video_workflow(): # Verify the conversation flow assert len(vcon.dialog) == 3 assert vcon.dialog[0]["type"] == "text" - assert vcon.dialog[1]["type"] == "video" + assert vcon.dialog[1]["type"] == "recording" # audio/video normalize to recording assert vcon.dialog[2]["type"] == "text" # Verify the video properties @@ -1365,7 +1365,7 @@ def test_integration_basic_video_workflow(): # Verify everything is preserved assert len(new_vcon.dialog) == 3 - assert new_vcon.dialog[1]["type"] == "video" + assert new_vcon.dialog[1]["type"] == "recording" # audio/video normalize to recording assert new_vcon.dialog[1]["mediatype"] == "video/mp4" def test_version_field_optional() -> None: From fa4e21807004827e246dd270837918f68acfc25d Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:15:37 -0500 Subject: [PATCH 08/12] Add deprecation paths for removed 0.4.0 API Vcon.redacted and Vcon.amended become deprecated aliases of redacted_from and amended_from. PartyHistory is kept as a deprecated class with to_event(). Dialog.is_transfer() warns and returns False. add_transfer_dialog() raises NotImplementedError naming the Event replacement instead of AttributeError. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++--- src/vcon/dialog.py | 7 ++++++ src/vcon/party.py | 45 +++++++++++++++++++++++++++++++++++- src/vcon/vcon.py | 27 ++++++++++++++++++++++ tests/test_core05_changes.py | 30 +++++++++++++++++++++--- 5 files changed, 110 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2f8f8a..b2f039b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,7 +38,7 @@ Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. payload does) is migrated on load, so `vcon.vcon` reads `"0.5.0"` and indices are preserved. Use `migrate_legacy=False` to keep the raw 0.4.0 dict. - **Breaking:** `Vcon.redacted` and `Vcon.amended` are now `redacted_from` and - `amended_from`. + `amended_from`; the old names remain as deprecated aliases. - **Breaking:** Dialog types are `recording`, `text` and `incomplete`. `Dialog(type="audio" | "video")` still works but warns (DeprecationWarning) and builds a `recording`; the video helpers also write `recording`. On read, @@ -46,8 +46,10 @@ Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. `recording-set` type are gone, as are the Dialog parameters `party_history`, `originator`, `transferee`, `transferor`, `transfer_target`, `original`, `consultation`, `target_dialog`, `transfer`, `recordings` and `recording_set`; - passing one to `Dialog()` raises `ValueError`. `PartyHistory` and - `Vcon.add_transfer_dialog()` were removed; use `Event`. + passing one to `Dialog()` raises `ValueError`. `PartyHistory` is deprecated + (it warns and converts with `to_event(sessions)`); `Vcon.add_transfer_dialog()` + raises `NotImplementedError` pointing at `Event`; `Dialog.is_transfer()` warns + and returns False. - **Breaking:** Dialog `parties` are the contributors only; the receivers are the `parties` of the Session that lists the Dialog. - **Breaking:** `add_incomplete_dialog()` no longer writes a `body` (an diff --git a/src/vcon/dialog.py b/src/vcon/dialog.py index 489bc48..1f6379e 100644 --- a/src/vcon/dialog.py +++ b/src/vcon/dialog.py @@ -531,6 +531,13 @@ def is_recording(self) -> bool: """ return hasattr(self, "type") and self.type == "recording" + def is_transfer(self) -> bool: + """Deprecated: core-05 has no transfer Dialog type, so this is always False.""" + warnings.warn( + "Dialog.is_transfer() is deprecated: transfers are Events in core-05", DeprecationWarning, stacklevel=2 + ) + return False + def is_placeholder(self) -> bool: """ Check if the dialog is an empty placeholder Dialog Object (``{}``). diff --git a/src/vcon/party.py b/src/vcon/party.py index dd192fd..1638ad3 100644 --- a/src/vcon/party.py +++ b/src/vcon/party.py @@ -1,4 +1,5 @@ -from typing import Optional +import warnings +from typing import Any, Dict, List, Optional, Union from vcon.civic_address import CivicAddress from datetime import datetime @@ -118,3 +119,45 @@ def to_dict(self): else: party_dict[key] = value return party_dict + + +class PartyHistory: + """Deprecated 0.4.0 Party_History Object, kept so old imports keep working. + + core-05 replaced Dialog ``party_history`` with Event Objects. Build an + ``Event`` directly, or convert with :meth:`to_event`, which needs the + Session index (or indices) the event belongs to. A ``PartyHistory`` can no + longer be attached to a Dialog. + """ + + VALID_EVENTS = ["join", "drop", "hold", "unhold", "mute", "unmute", "keydown", "keyup"] + + def __init__(self, party: int, event: str, time: Union[datetime, str], button: Optional[str] = None): + warnings.warn( + "PartyHistory is deprecated: use vcon.event.Event (core-05 Event Object)", + DeprecationWarning, + stacklevel=2, + ) + if event not in PartyHistory.VALID_EVENTS: + raise ValueError(f"Invalid event '{event}'. Must be one of: {PartyHistory.VALID_EVENTS}") + self.party = party + self.event = event + self.time = time + self.button = button + + def to_dict(self) -> Dict[str, Any]: + """The 0.4.0 shape (``event``, not ``type``).""" + out: Dict[str, Any] = { + "party": self.party, + "event": self.event, + "time": self.time.isoformat() if hasattr(self.time, "isoformat") else self.time, + } + if self.button is not None: + out["button"] = self.button + return out + + def to_event(self, sessions: Union[int, List[int]]): + """The equivalent core-05 Event (``event`` renamed ``type``, no ``dialog``).""" + from .event import Event + + return Event(type=self.event, time=self.time, sessions=sessions, party=self.party, button=self.button) diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 1334fc0..67039b4 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -17,6 +17,7 @@ from cryptography.hazmat.primitives import serialization import requests import logging +import warnings from .party import Party from .dialog import Dialog, b64url_encode from .body import decode_body @@ -1677,6 +1678,20 @@ def add_dialog(self, dialog: Dialog, session: Optional[int] = None) -> int: logger.info(f"Added dialog of type {getattr(dialog, 'type', 'placeholder')}") return index + def add_transfer_dialog(self, *args: Any, **kwargs: Any) -> None: + """Removed: core-05 has no transfer Dialog type. + + Raises ``NotImplementedError`` with the replacement: a transfer is one + or two transfer Events (``blind-transfer``, ``consultation-start`` plus + ``consultative-transfer``, or ``transfer-abandoned``) added with + ``add_event(Event(...))``, whose ``sessions``/``consultation``/ + ``target_session`` reference Sessions for the calls involved. + """ + raise NotImplementedError( + "add_transfer_dialog() was removed in vCon 0.5.0: record a transfer as transfer " + "Events with add_event(Event(type='blind-transfer', ...)); see vcon.event" + ) + def add_session(self, session: Union[Session, Dict[str, Any], None] = None) -> int: """ Add a Session Object and return its index in the ``sessions`` array. @@ -1946,6 +1961,18 @@ def events(self) -> List[Dict[str, Any]]: """The ``events`` array (Event Objects).""" return self.vcon_dict.get("events", []) + @property + def redacted(self): + """Deprecated 0.4.0 name; returns ``redacted_from``.""" + warnings.warn("Vcon.redacted is deprecated; use Vcon.redacted_from (core-05)", DeprecationWarning, stacklevel=2) + return self.redacted_from + + @property + def amended(self): + """Deprecated 0.4.0 name; returns ``amended_from``.""" + warnings.warn("Vcon.amended is deprecated; use Vcon.amended_from (core-05)", DeprecationWarning, stacklevel=2) + return self.amended_from + @property def redacted_from(self): return self.vcon_dict.get("redacted_from") diff --git a/tests/test_core05_changes.py b/tests/test_core05_changes.py index 80ef853..99d2beb 100644 --- a/tests/test_core05_changes.py +++ b/tests/test_core05_changes.py @@ -29,8 +29,7 @@ def test_properties_replace_old_names(self): v = Vcon({"uuid": "a", "created_at": T, "redacted_from": {"uuid": "b", "type": "PII"}}) assert v.redacted_from == {"uuid": "b", "type": "PII"} assert v.amended_from is None - assert not hasattr(v, "redacted") - assert not hasattr(v, "amended") + # the 0.4.0 names remain as deprecated aliases (TestDeprecatedApi) w = Vcon({"uuid": "a", "created_at": T, "amended_from": {"uuid": "b"}}) assert w.amended_from == {"uuid": "b"} @@ -203,7 +202,8 @@ def test_removed_types_and_parameters_fail_validation(self): assert any("'party_history', which was removed" in e for e in errors) def test_no_transfer_dialog_helper(self): - assert not hasattr(Vcon, "add_transfer_dialog") + with pytest.raises(NotImplementedError): + Vcon.build_new().add_transfer_dialog() def test_multipart_alternative_mediatype_with_parameters(self): v = _base() @@ -448,3 +448,27 @@ def test_reference_to_empty_dialog_warns(self): w = v.get_validation_warnings() assert any("lists dialog 0, which is an empty placeholder" in x for x in w) assert any("Attachment at index 0 references dialog 0" in x for x in w) + + +class TestDeprecatedApi: + def test_redacted_and_amended_aliases(self): + v = Vcon({"uuid": "a", "created_at": T, "redacted_from": {"uuid": "b", "type": "PII"}}) + with pytest.warns(DeprecationWarning): + assert v.redacted == {"uuid": "b", "type": "PII"} + with pytest.warns(DeprecationWarning): + assert v.amended is None + + def test_add_transfer_dialog_points_at_events(self): + with pytest.raises(NotImplementedError, match="add_event"): + Vcon.build_new().add_transfer_dialog(start=T, transfer_data={}, parties=[0, 1]) + + def test_is_transfer_is_false(self): + with pytest.warns(DeprecationWarning): + assert Dialog(type="text", start=T, parties=[0]).is_transfer() is False + + def test_party_history_converts_to_event(self): + from vcon.party import PartyHistory + with pytest.warns(DeprecationWarning): + ph = PartyHistory(0, "keydown", T, button="5") + assert ph.to_dict()["event"] == "keydown" + assert ph.to_event(sessions=0).to_dict() == {"type": "keydown", "time": T, "sessions": 0, "party": 0, "button": "5"} From c5b003fddd3c64dfc7a380ebdda671e7d8b6db86 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:16:06 -0500 Subject: [PATCH 09/12] Flag lawful_basis attachments without party or session scope The extension validator checked only the body. It now warns when a lawful_basis attachment has no party, or no session (core-05 scopes a basis to Sessions; an attachment needs dialog or session). Co-Authored-By: Claude Opus 5.5 --- src/vcon/extensions/lawful_basis/validation.py | 11 +++++++++++ tests/test_core05_changes.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/vcon/extensions/lawful_basis/validation.py b/src/vcon/extensions/lawful_basis/validation.py index 08068af..69c20b7 100644 --- a/src/vcon/extensions/lawful_basis/validation.py +++ b/src/vcon/extensions/lawful_basis/validation.py @@ -72,6 +72,17 @@ def validate_attachment(self, attachment: Dict[str, Any]) -> ValidationResult: # Check encoding if attachment.get("encoding") != "json": result.add_error("Lawful basis attachment must use 'json' encoding") + + # Core-05 scope (4.6.3 to 4.6.5). Warnings, so a bare body built by + # create_lawful_basis_attachment() can still be checked before it is + # placed in a vCon; Vcon.is_valid() enforces party and dialog/session. + if "party" not in attachment: + result.add_warning("Lawful basis attachment has no party (core-05 requires it)") + if "session" not in attachment: + result.add_warning( + "Lawful basis attachment has no session; core-05 scopes a basis to Sessions" + + ("" if "dialog" in attachment else " and an attachment needs dialog or session") + ) # Validate body structure. Accept both the -04 shape (body already # the decoded object) and a legacy JSON-string body. diff --git a/tests/test_core05_changes.py b/tests/test_core05_changes.py index 99d2beb..795fd72 100644 --- a/tests/test_core05_changes.py +++ b/tests/test_core05_changes.py @@ -472,3 +472,17 @@ def test_party_history_converts_to_event(self): ph = PartyHistory(0, "keydown", T, button="5") assert ph.to_dict()["event"] == "keydown" assert ph.to_event(sessions=0).to_dict() == {"type": "keydown", "time": T, "sessions": 0, "party": 0, "button": "5"} + + +class TestLawfulBasisValidatorScope: + def test_missing_party_and_session_are_flagged(self): + from vcon.extensions.lawful_basis.validation import LawfulBasisValidator + att = {"purpose": "lawful_basis", "encoding": "json", "dialog": 0, + "body": {"lawful_basis": "consent", "expiration": "2030-01-01T00:00:00Z", + "purpose_grants": [{"purpose": "recording", "granted": True, "granted_at": T}]}} + r = LawfulBasisValidator().validate_attachment(att) + assert any("no party" in w for w in r.warnings) + assert any("no session" in w for w in r.warnings) + att.update(party=0, session=0) + r = LawfulBasisValidator().validate_attachment(att) + assert not any("party" in w or "session" in w for w in r.warnings) From 3a95a0e98871d1d83e385ed25af1de78f1ac5ded Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:16:21 -0500 Subject: [PATCH 10/12] Document the migration and load-path changes Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 ++++++++++++++--- MIGRATION_GUIDE.md | 6 +++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2f039b..108a1ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,9 +34,20 @@ Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. ### Changed - **Breaking:** `build_new()` emits `"vcon": "0.5.0"`. -- **Breaking:** a vCon that declares `"vcon": "0.4.0"` (or a signed vCon whose - payload does) is migrated on load, so `vcon.vcon` reads `"0.5.0"` and indices - are preserved. Use `migrate_legacy=False` to keep the raw 0.4.0 dict. +- **Breaking:** a vCon that declares `"vcon": "0.4.0"` is migrated on load, so + `vcon.vcon` reads `"0.5.0"` and indices are preserved. Use + `migrate_legacy=False` to keep the raw 0.4.0 dict (property handling is not + applied to it, so legacy parameters survive). A signed 0.4.0 vCon is kept + signed on load; migrate it explicitly after verifying. +- Migration details: recording-set membership is the union of `recordings` and + the recordings' `recording_set`; a nested recording-set becomes a `child` + Session_Reference; party_history Events list every Session of their Dialog, + including Sessions made for a transfer's calls; a missing Event time falls + back to the Dialog start, then `created_at`; party_history extension + parameters are carried onto the Event; a null first party on a text or + incomplete Dialog becomes an empty Party Object instead of promoting a + receiver; an attachment with no scope gets the only Session when exactly one + exists (step T10c). Every one of these is listed in the report. - **Breaking:** `Vcon.redacted` and `Vcon.amended` are now `redacted_from` and `amended_from`; the old names remain as deprecated aliases. - **Breaking:** Dialog types are `recording`, `text` and `incomplete`. diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index f61400a..9096703 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -23,7 +23,11 @@ The migration follows Appendix A.1 of the draft, one function per step (`vcon.mi Removed `transfer` and `recording-set` Dialogs become empty Dialog Objects (`{}`) in place, so every dialog, analysis, attachment and event index stays valid. Where A.1 is silent the migration applies a documented default and lists it in the report (`report.inferred`); anything it cannot resolve is in `report.unresolved`. Signed input is -migrated as its unsigned payload; sign the result again (`report.resign_required`). +not migrated on load, because migrating drops the signature: verify it, then call +`Vcon.migrate_0_4_0_to_0_5_0(signed)` (or the function), which migrates the unsigned payload; sign the result again +(`report.resign_required`). Input with no `vcon` parameter that already has `sessions`, `events`, `redacted_from`, +`amended_from` or `redacted_strings` is 0.5.0 and is refused. Persist `report.to_dict()` next to each migrated +record: it holds the original content of every removed Dialog and every value that was inferred or dropped. Code that changes: From 1265de31dfaba9e60fc0a7ec10bec8e68fc4442d Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 14:35:06 -0500 Subject: [PATCH 11/12] Fix null parties crash and non-RFC 3339 dates in 0.4.0 migration A null vCon parties value crashed when an unknown-party placeholder was needed; it is now treated like absent and reported. Dialog starts that are not RFC 3339 date-times (free-form strings, out-of-range fields) are no longer used as a Session start: strict mode raises MigrationError, default mode records an unresolved entry. Matches the TypeScript port. Co-Authored-By: Claude Opus 5.5 --- src/vcon/migration.py | 64 ++++++++++++++++++++++++++++++----- tests/test_migration_0_4_0.py | 39 +++++++++++++++++++++ 2 files changed, 94 insertions(+), 9 deletions(-) diff --git a/src/vcon/migration.py b/src/vcon/migration.py index 9f1d506..6ce20f9 100644 --- a/src/vcon/migration.py +++ b/src/vcon/migration.py @@ -32,12 +32,11 @@ import copy import json import logging +import re from dataclasses import dataclass, field -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple -from dateutil import parser - from .event import EVENT_PARAMETERS as _EVENT_PARAMS from .validation import extensions_in_use, validate_vcon_dict @@ -166,16 +165,39 @@ def _is_int(v: Any) -> bool: return isinstance(v, int) and not isinstance(v, bool) +_DATE_RE = re.compile( + r"^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$" +) + + def _parse_dt(value: Any) -> Optional[datetime]: + """Parse an RFC 3339 / ISO 8601 date-time, or return None. + + Free-form strings such as ``"Jan 1 2022 10:00"`` and out-of-range fields + (February 30, hour 24) are rejected, matching the TypeScript port. A value + with no offset is read as UTC. Fractional seconds keep microseconds. + """ if not isinstance(value, str): return None + m = _DATE_RE.match(value.strip()) + if not m: + return None + ys, mos, ds, hs, mis, ss, frac, tz = m.groups() try: - dt = parser.parse(value) - except Exception: + offset = timedelta(0) + if tz and tz.upper() != "Z": + digits = tz[1:].replace(":", "") + oh, om = int(digits[:2]), int(digits[2:] or "0") + if oh > 23 or om > 59: + return None + offset = timedelta(hours=oh, minutes=om) * (-1 if tz[0] == "-" else 1) + micro = int(frac[1:7].ljust(6, "0")) if frac else 0 + return datetime( + int(ys), int(mos), int(ds), int(hs or 0), int(mis or 0), int(ss or 0), micro, + tzinfo=timezone(offset), + ) + except ValueError: return None - if dt.tzinfo is None: - dt = dt.replace(tzinfo=timezone.utc) - return dt def _num(seconds: float) -> Any: @@ -263,7 +285,14 @@ def new_session(self, session: Dict[str, Any]) -> int: def empty_party(self, step: str, role: str) -> int: """Index of an empty Party Object, appended once (4.3.9: unknown party).""" if self._empty_party is None: - parties = self.out.setdefault("parties", []) + parties = self.out.get("parties") + if not isinstance(parties, list): + # Absent or null `parties` is treated alike (as the TypeScript port does). + if "parties" in self.out: + self.report.add( + step, INFERRED, "vCon 'parties' was not an array (null); treated as absent.", None, + ) + parties = self.out["parties"] = [] parties.append({}) self._empty_party = len(parties) - 1 self.report.add( @@ -365,8 +394,25 @@ def make_session(self, step: str, idxs: List[int], label: str) -> Dict[str, Any] # --------------------------------------------------------------------------- +def _check_dialog_dates(ctx: _Context) -> None: + """core-05 Date is RFC 3339: a Dialog start that is not one is never used as a Session start. + + Strict mode raises; otherwise the value is reported as unresolved. + """ + for i, d in enumerate(ctx.dialogs): + if not isinstance(d, dict) or d.get("start") is None or _parse_dt(d["start"]): + continue + msg = f"dialog[{i}] start {d['start']!r} is not an RFC 3339 date-time" + if ctx.strict: + raise MigrationError(f"T1: {msg} (strict mode)") + ctx.report.add( + "T1", UNRESOLVED, f"{msg}; not used to derive a Session start.", None, dialog=i, start=d["start"], + ) + + def _step_t1_version(ctx: _Context) -> None: """T1: ``vcon`` "0.4.0" -> "0.5.0".""" + _check_dialog_dates(ctx) if "vcon" not in ctx.out: ctx.report.add("T1", INFERRED, "Input had no 'vcon' parameter; set to '0.5.0' (AMB-12: writers emit it).", "AMB-12") ctx.out["vcon"] = TARGET_VERSION diff --git a/tests/test_migration_0_4_0.py b/tests/test_migration_0_4_0.py index 0f8e057..f2c323a 100644 --- a/tests/test_migration_0_4_0.py +++ b/tests/test_migration_0_4_0.py @@ -765,3 +765,42 @@ def test_strict_migration_raises_through_the_constructor(self): def test_writers_emit_0_5_0(self): v = Vcon.build_from_json(json.dumps(v04(dialog=[rec()]))) assert json.loads(v.to_json())["vcon"] == "0.5.0" + + +class TestNullPartiesAndNonRfcDates: + """Regressions from a differential run against the TypeScript port.""" + + @pytest.mark.parametrize("top", [None, "absent"]) + def test_null_parties_treated_like_absent(self, top): + d = v04(dialog=[text(parties=[None, 1])]) + if top == "absent": + del d["parties"] + else: + d["parties"] = None + res = migrate_0_4_0_to_0_5_0(d) + assert res.vcon["parties"] == [{}] + assert any("empty Party" in e.message for e in res.report.entries) + migrate_0_4_0_to_0_5_0(d, strict=True) + + def test_null_dialog_parties_does_not_raise(self): + res = migrate_0_4_0_to_0_5_0(v04(dialog=[text(parties=None), rec(parties=None)])) + assert res.vcon["vcon"] == "0.5.0" + + def test_free_form_date_not_used_as_session_start(self): + res = migrate_0_4_0_to_0_5_0(v04(dialog=[rec(start="Jan 1 2022 10:00")])) + assert "start" not in res.vcon["sessions"][0] + assert any(e.step == "T1" and "RFC 3339" in e.message for e in res.report.unresolved) + + def test_free_form_date_strict_raises(self): + with pytest.raises(MigrationError, match="RFC 3339"): + migrate_0_4_0_to_0_5_0(v04(dialog=[rec(start="Jan 1 2022 10:00")]), strict=True) + + @pytest.mark.parametrize("start", ["2022-02-30T00:00:00Z", "2022-01-01T24:00:00Z", "2022-01-01T00:00:00+24:00"]) + def test_out_of_range_date_rejected(self, start): + res = migrate_0_4_0_to_0_5_0(v04(dialog=[rec(start=start)])) + assert "start" not in res.vcon["sessions"][0] + + def test_microseconds_kept(self): + res = migrate_0_4_0_to_0_5_0(v04(dialog=[ + rec(start="2022-01-01T00:00:00.123456Z", duration=10), rec(start="2022-01-01T00:00:00.5Z", duration=10)])) + assert res.vcon["sessions"][0]["duration"] == 10.376544 From acd65a25b4fc8659c6eea1056b87487c797094b5 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 15 Nov 2026 08:22:45 -0500 Subject: [PATCH 12/12] Pin CI to Python 3.12 and date the 1.0.0 changelog entry The runner image no longer provides Python 3.12.8, so the version-check and build-linux jobs failed at setup. Use the floating 3.12 so the runner picks a current patch release. Date the 1.0.0 entry 2026-11-15 and the 0.10.0 entry 2026-09-26 (its tag date). --- .github/workflows/python-package-poetry.yml | 8 ++++---- CHANGELOG.md | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/python-package-poetry.yml b/.github/workflows/python-package-poetry.yml index 6fd09b1..52713ec 100644 --- a/.github/workflows/python-package-poetry.yml +++ b/.github/workflows/python-package-poetry.yml @@ -10,10 +10,10 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Set up Python 3.12.8 + - name: Set up Python 3.12 uses: actions/setup-python@v3 with: - python-version: '3.12.8' + python-version: '3.12' - name: Check pyproject.toml / setup.py / CHANGELOG.md versions agree run: python3 scripts/check_version.py @@ -26,10 +26,10 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Set up Python 3.12.8 + - name: Set up Python 3.12 uses: actions/setup-python@v3 with: - python-version: '3.12.8' + python-version: '3.12' - name: Install Poetry run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 108a1ed..e0aee23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [1.0.0] - Unreleased +## [1.0.0] - 2026-11-15 Retargets the library to `draft-ietf-vcon-vcon-core-05` (syntax `"0.5.0"`). This is a breaking release: the Dialog Object lost its transfer, recording-set, @@ -92,7 +92,7 @@ Objects. Readers accept 0.4.0 and 0.5.0; writers emit 0.5.0. - Vendored test schema is now the core-05 Appendix C schema, with the Appendix B examples under `tests/schema/examples/`. -## [0.10.0] - Unreleased +## [0.10.0] - 2026-09-26 Retargets the library to `draft-ietf-vcon-vcon-core-04`. Under -04 section 2.3.2, a `"json"`-encoded `body` is the JSON *value* itself (object, array,