diff --git a/.github/workflows/python-package-poetry.yml b/.github/workflows/python-package-poetry.yml index 01a8684..6fd09b1 100644 --- a/.github/workflows/python-package-poetry.yml +++ b/.github/workflows/python-package-poetry.yml @@ -1,8 +1,23 @@ name: Python Package using Poetry -on: [push] +on: + push: + pull_request: jobs: + version-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up Python 3.12.8 + uses: actions/setup-python@v3 + with: + python-version: '3.12.8' + + - name: Check pyproject.toml / setup.py / CHANGELOG.md versions agree + run: python3 scripts/check_version.py + build-linux: runs-on: ubuntu-latest strategy: diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index 2bd32ee..b7e54b7 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -1,6 +1,16 @@ -# This workflow will upload a Python Package using Twine when a release is created -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries - +# This workflow publishes to PyPI when a `v*` tag is pushed. The tag push +# IS the release: nothing else in this repo should run `poetry publish`, +# `twine upload`, or cut a GitHub release by hand. See CHANGELOG.md 0.10.0 +# for the rationale (this project was previously triggering on +# `release: published`, which decoupled the release event from the tag and +# commit it was supposed to represent). +# +# Auth: this workflow uses a stored PyPI API token (secrets.PYPI_API_TOKEN), +# not PyPI trusted publishing (OIDC). Switching to trusted publishing would +# need the project registered for it on PyPI first, so that migration is +# left as a separate follow-up; this change only fixes the trigger and adds +# the pre-publish version guard. +# # This workflow uses actions that are not certified by GitHub. # They are provided by a third-party and are governed by # separate terms of service, privacy policy, and support @@ -9,8 +19,9 @@ name: Upload Python Package on: - release: - types: [published] + push: + tags: + - 'v*' permissions: contents: read @@ -26,6 +37,8 @@ jobs: uses: actions/setup-python@v3 with: python-version: '3.x' + - name: Check that the tag matches pyproject.toml's version + run: python3 scripts/check_version.py --tag "${GITHUB_REF_NAME}" - name: Install Poetry run: | curl -sSL https://install.python-poetry.org | python - diff --git a/.gitignore b/.gitignore index 7a5ecf1..a4f877e 100644 --- a/.gitignore +++ b/.gitignore @@ -128,4 +128,8 @@ cython_debug/ .idea/ # MAC OS -.DS_Store \ No newline at end of file +.DS_Store + +# oh-my-claudecode plugin scratch (session ids, tool throttles, per-machine +# absolute worktree paths) -- never commit this +.omc/ \ No newline at end of file diff --git a/API_REFERENCE.md b/API_REFERENCE.md index a7ff29e..639b53f 100644 --- a/API_REFERENCE.md +++ b/API_REFERENCE.md @@ -218,6 +218,13 @@ sentiment = vcon.find_analysis_by_type("sentiment") ##### Tag Management +Tags are stored as a `"tags"`-purpose attachment whose body is a list of +`"name:value"` strings (per `draft-ietf-vcon-vcon-core-04`, a `"json"`-encoded +body is the JSON value itself, not a serialized string). `get_tag()` and +`add_tag()` also accept a legacy JSON-*string* tags body -- as written under +-02 conventions, or by this library prior to 0.10.0 -- decoding it +automatically; `add_tag()` normalizes it back to a list in place. + ###### `add_tag(tag_name: str, tag_value: str) -> None` Add a tag to the vCon. diff --git a/CHANGELOG.md b/CHANGELOG.md index b881327..9f92006 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,84 @@ # Changelog +## [0.10.0] - Unreleased + +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, +string, number, bool, or null), not a `json.dumps` string. `add_tag()`'s +list body and `add_lawful_basis_attachment()`'s object body were already +correct under -04; this release brings readers, defaults, and the WTF/ +lawful-basis extensions in line with the same convention, and fixes a +handful of adjacent spec-compliance gaps. + +### Changed +- **Breaking (output shape):** every attachment created via `add_attachment()`, + `add_lawful_basis_attachment()`, and `add_wtf_transcription_attachment()` + now defaults `party` and `dialog` to `0` when not supplied (matching + `add_tag()`'s existing convention), `start` to the vCon's `created_at`, + and `mediatype` to `"application/json"` for `encoding="json"` bodies. + The WG JSON schema requires `start`, `party`, `dialog` on every + attachment; previously these were omitted unless explicitly passed, + producing non-compliant output. Callers that inspected the *absence* of + these keys (rather than their values) will see a difference. +- `Attachment.__init__` applies the same `party`/`dialog`/`mediatype` + defaults directly, so `Attachment(...)` constructed outside of a `Vcon` + gets the same defaults as `Vcon.add_attachment()`. +- `Dialog.to_dict()` no longer emits empty `meta: {}` / `metadata: {}` + placeholders. Both attributes are still initialized internally for + backward-compatible attribute access (`dialog.meta`, `dialog.metadata`); + only the serialized form changes. +- Inline `base64url` bodies written by the library (`Dialog.add_image_data()`, + `Dialog.add_video_data()`, `Dialog.transcode_video()`, `Dialog.to_inline_data()`, + `Attachment.from_image()`) are now unpadded, per -04's JWS/RFC 7515-style + base64url convention. New `vcon.dialog.b64url_encode()` / + `vcon.dialog.b64url_decode()` helpers encode without padding and decode + padded-or-unpadded input respectively; internal decode call sites + (`add_video_data`, `generate_thumbnail`, `extract_video_metadata`, + `transcode_video`) were updated to use `b64url_decode()` so both old + (padded) and new (unpadded) bodies still decode. +- `.github/workflows/python-publish.yml` now triggers on `push: tags: + ['v*']` instead of `release: published`. The tag push is the release; + nothing else should publish. Publishing auth is unchanged (a stored + `PYPI_API_TOKEN` secret via `pypa/gh-action-pypi-publish`) -- this repo's + existing workflow was not already using PyPI trusted publishing (OIDC), + so switching auth methods was out of scope for this change and is left + as a separate follow-up. + +### Added +- `vcon.body.decode_body(entry)` (also exposed as `Vcon.decoded_body(entry)`), + a shared helper that decodes an attachment/analysis/dialog `body`, + accepting both the -04 shape (body already the decoded value) and a + legacy JSON-encoded string body (as written under -02 conventions, or by + this library prior to 0.10.0). Used by `Vcon.get_tag()`/`add_tag()` and + by the lawful-basis and WTF extension validators/processors, so every + body-reading call site in the library now accepts both shapes. +- `vcon.dialog.b64url_encode()` / `vcon.dialog.b64url_decode()`, public + unpadded-base64url encode/decode helpers (see Changed, above). +- `tests/schema/vcon_json_schema.json`, a vendored copy of the vCon working + group's reference JSON schema (see `tests/schema/SOURCE.md` for + provenance), plus `tests/test_schema_compliance.py`, which builds a vCon + using only public helpers (`add_tag`, `add_lawful_basis_attachment`, + `add_dialog`, `add_attachment`) and validates it against that schema with + no post-processing. `jsonschema` added as a dev dependency. +- `scripts/check_version.py`, a version-consistency guard: compares + `pyproject.toml`'s version against the newest `## [x.y.z]` CHANGELOG + heading and (if present) `setup.py`'s hardcoded version, and, given + `--tag `, also checks a release tag against the pyproject version. + Wired into CI on every push/PR, and into the publish workflow immediately + before publishing so a release cut from the wrong commit fails loudly. + +### Fixed +- `Vcon.get_tag()` and `Vcon.add_tag()` now accept a legacy JSON-string + `tags` body (written under -02 conventions, or by this library prior to + 0.10.0) as well as the -04 list-valued body. `add_tag()` normalizes a + legacy string body to a list in place, preserving existing tags, before + appending the new one. +- The lawful-basis and WTF extension validators/processors + (`extensions/lawful_basis/validation.py`, `extensions/lawful_basis/processing.py`, + `extensions/wtf/validation.py`, `extensions/wtf/processing.py`, + `extensions/wtf/extension.py`) now decode a legacy JSON-string attachment + body before working with it, instead of assuming it is already a `dict`. + ## [0.9.6] - 2026-06-04 ### Security diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index da36c1e..99fd348 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -311,4 +311,28 @@ vcon.save_to_file("conversation.json") - Check the full documentation in `docs/source/new_required_fields.rst` - Run the example: `python samples/example_new_fields.py` - Review the test files for usage examples -- Open an issue if you encounter problems +- Open an issue if you encounter problems + +## Migrating to 0.10.0 (draft-ietf-vcon-vcon-core-04) + +0.10.0 retargets the library to `draft-ietf-vcon-vcon-core-04`. The +specification's body semantics did not change from prior guidance in this +library (a `"json"`-encoded body was always meant to be a JSON value, not a +string), but two behavior changes follow from aligning with the WG's +reference JSON schema: + +- **Legacy string bodies are now read transparently.** If you (or an + adapter) previously wrote a `"json"`-encoded body as a `json.dumps` + string -- for example a `tags` attachment body written as + `'["category:support"]'` instead of `["category:support"]` -- `get_tag()`, + `add_tag()`, and the lawful-basis/WTF extension validators now decode + that string automatically. `add_tag()` also normalizes a legacy string + body back to a list, in place, the first time you call it on that vCon. + You don't need to migrate existing data by hand. +- **New attachments get more defaults filled in.** `add_attachment()`, + `add_lawful_basis_attachment()`, and `add_wtf_transcription_attachment()` + now default `party`/`dialog` to `0` and `start` to the vCon's + `created_at` when you don't supply them, because the WG JSON schema + requires `start`, `party`, and `dialog` on every attachment. If your code + checked for the *absence* of these keys (rather than their values), check + the CHANGELOG's 0.10.0 entry before upgrading. diff --git a/poetry.lock b/poetry.lock index 1d5f497..fe9f13c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -12,6 +12,18 @@ files = [ {file = "alabaster-0.7.13.tar.gz", hash = "sha256:a27a4a084d5e690e16e01e03ad2b2e552c61a65469419b907243193de1a84ae2"}, ] +[[package]] +name = "attrs" +version = "26.1.0" +description = "Classes Without Boilerplate" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309"}, + {file = "attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"}, +] + [[package]] name = "authlib" version = "1.7.2" @@ -531,6 +543,43 @@ cryptography = ">=45.0.1" [package.extras] drafts = ["pycryptodome"] +[[package]] +name = "jsonschema" +version = "4.26.0" +description = "An implementation of JSON Schema validation for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce"}, + {file = "jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326"}, +] + +[package.dependencies] +attrs = ">=22.2.0" +jsonschema-specifications = ">=2023.03.6" +referencing = ">=0.28.4" +rpds-py = ">=0.25.0" + +[package.extras] +format = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3987", "uri-template", "webcolors (>=1.11)"] +format-nongpl = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3986-validator (>0.1.0)", "rfc3987-syntax (>=1.1.0)", "uri-template", "webcolors (>=24.6.0)"] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +description = "The JSON Schema meta-schemas and vocabularies, exposed as a Registry" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe"}, + {file = "jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d"}, +] + +[package.dependencies] +referencing = ">=0.31.0" + [[package]] name = "logger" version = "1.4" @@ -940,6 +989,23 @@ files = [ [package.dependencies] six = ">=1.5" +[[package]] +name = "referencing" +version = "0.37.0" +description = "JSON Referencing + Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231"}, + {file = "referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8"}, +] + +[package.dependencies] +attrs = ">=22.2.0" +rpds-py = ">=0.7.0" +typing-extensions = {version = ">=4.4.0", markers = "python_version < \"3.13\""} + [[package]] name = "requests" version = "2.34.2" @@ -962,6 +1028,132 @@ urllib3 = ">=1.26,<3" socks = ["PySocks (>=1.5.6,!=1.5.7)"] use-chardet-on-py3 = ["chardet (>=3.0.2,<8)"] +[[package]] +name = "rpds-py" +version = "2026.6.3" +description = "Python bindings to Rust's persistent data structures (rpds)" +optional = false +python-versions = ">=3.11" +groups = ["dev"] +files = [ + {file = "rpds_py-2026.6.3-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:7b689145a1485c335569bd056464f3243a29af7ed3871c7be31ad624ba239bc7"}, + {file = "rpds_py-2026.6.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:db08f45aecde626498fb3df07bcf6d2ec040af42e859a4f5040d79c200342911"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:acc992ab27b15f852c76755eb2ab7dce86585ddadba6fa5946e58556088845b4"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7f88d653e7b3b779d71ae7454e20dcc9b6bae903f33c269db9f2be41bda3f261"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e52655eaf81e32593abedaa4bfe33170c8cfedf3365ed9be6e11e07f148f0278"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dfcc8b909769d19db55c7cc9541eb64b9b774b1057ffffb4f1048070475bb9f9"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9c1255b302953c86a486b81d330d5ee1d5bd937691ce271b6be0ef0e299eaab7"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:8d2294a31386bfa251d8c8a39472beee17db67d4f1a6eabea665d35c9a4461c3"}, + {file = "rpds_py-2026.6.3-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f8f23ead891a3b762f35ab3b04623da7056545b48aa60d59957e6789914545da"}, + {file = "rpds_py-2026.6.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:421aba32367055614287a4292b6a17f1939c9452299f7a0209c117e990b646d4"}, + {file = "rpds_py-2026.6.3-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1e5822dfc2f0d4ab7e745eaa6d85945069329beeccef965af3f3bb26058fcab6"}, + {file = "rpds_py-2026.6.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:83e35b57523816c8613fd0776b40cd8bb9f596b37ddd2692eb4a6bb5ab2f8c93"}, + {file = "rpds_py-2026.6.3-cp311-cp311-win32.whl", hash = "sha256:de3eceba0b683bcbb1ab93da016d0270df1f9ae7be716b40214c5dafac6ea45a"}, + {file = "rpds_py-2026.6.3-cp311-cp311-win_amd64.whl", hash = "sha256:2c54a076ca4d370980ab57bc0e31df57bbe8d41340436a90ef8b1219a3cbb127"}, + {file = "rpds_py-2026.6.3-cp311-cp311-win_arm64.whl", hash = "sha256:168c733a7112e071bb7a66460e667edfcff06c017a3c523f7a8a8e08d0140804"}, + {file = "rpds_py-2026.6.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0"}, + {file = "rpds_py-2026.6.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a"}, + {file = "rpds_py-2026.6.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4"}, + {file = "rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa"}, + {file = "rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc"}, + {file = "rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822"}, + {file = "rpds_py-2026.6.3-cp312-cp312-win32.whl", hash = "sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed"}, + {file = "rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f"}, + {file = "rpds_py-2026.6.3-cp312-cp312-win_arm64.whl", hash = "sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96"}, + {file = "rpds_py-2026.6.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223"}, + {file = "rpds_py-2026.6.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885"}, + {file = "rpds_py-2026.6.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4"}, + {file = "rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7"}, + {file = "rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d"}, + {file = "rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97"}, + {file = "rpds_py-2026.6.3-cp313-cp313-win32.whl", hash = "sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0"}, + {file = "rpds_py-2026.6.3-cp313-cp313-win_amd64.whl", hash = "sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80"}, + {file = "rpds_py-2026.6.3-cp313-cp313-win_arm64.whl", hash = "sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb"}, + {file = "rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e"}, + {file = "rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc"}, + {file = "rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77"}, + {file = "rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698"}, + {file = "rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd"}, + {file = "rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d"}, + {file = "rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8"}, + {file = "rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5"}, + {file = "rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e"}, + {file = "rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2"}, + {file = "rpds_py-2026.6.3-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13"}, + {file = "rpds_py-2026.6.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a"}, + {file = "rpds_py-2026.6.3-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868"}, + {file = "rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187"}, + {file = "rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107"}, + {file = "rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba"}, + {file = "rpds_py-2026.6.3-cp315-cp315-win32.whl", hash = "sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369"}, + {file = "rpds_py-2026.6.3-cp315-cp315-win_amd64.whl", hash = "sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146"}, + {file = "rpds_py-2026.6.3-cp315-cp315-win_arm64.whl", hash = "sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-win32.whl", hash = "sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577"}, + {file = "rpds_py-2026.6.3-cp315-cp315t-win_amd64.whl", hash = "sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:4cf2d36a2357e4d07bb5a4f98801265327b48256867816cfd2ceb001e9754a8f"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:30c6dc199b24a5e3e81d50da0f00858c5bbdb2617a750395687f4339c5818171"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9891e594296ab9dada6551c8e7b387b2721f27a67eecd528412e8906247a7b90"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b5c2dc92304aa48a4a60443b548bb12f12e119d4b72f314015e67b9e1be97fca"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:127e08c0642d880cf32ca47ec2a4a77b901f7e2dd1ad9762adb13955d72ffcc9"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8bb68f03f395eb793220b45c097bd4d8c32944393da0fad8b999efac0868fc8c"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a3450b693fde92133e9f51060568a4c31fcca76d5e53bbd611e689ca446517e9"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:5e8d07bddee435a2ff6f1920e18feff28d0bc4533e42f4bf6927fbd073312c41"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3a83ae6c67b7676b9878378547ca8e93ed77a580037bcbcd1d32f739e1e6089c"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:2bfd04c19ddbd6640de0b51894d764bd2758854d5b75bd102d2ef10cb9c293a9"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:ca6546b66be9dc4738b1b043d5ebd5488c66c578c5ff0fd0e8065313fe3afb76"}, + {file = "rpds_py-2026.6.3-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:8e65860d238379ed982fd9ba690579b5e95af2f4840f99c772816dbe573cb826"}, + {file = "rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4"}, +] + [[package]] name = "six" version = "1.16.0" @@ -1157,11 +1349,12 @@ version = "4.12.2" description = "Backported and Experimental Type Hints for Python 3.8+" optional = false python-versions = ">=3.8" -groups = ["main"] +groups = ["main", "dev"] files = [ {file = "typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d"}, {file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"}, ] +markers = {dev = "python_version == \"3.12\""} [[package]] name = "urllib3" @@ -1199,4 +1392,4 @@ image = ["pillow", "pypdf"] [metadata] lock-version = "2.1" python-versions = "^3.12" -content-hash = "470c85a31a0d5774ba936878e57e33f9fafe946cca97490abe464cef6d307fd2" +content-hash = "2107dee660a3b77ab7fdd3fefe5c0fce6e3139ce25e41821c0f22d467e48dd8e" diff --git a/pyproject.toml b/pyproject.toml index f34adaf..1371ebb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "vcon" -version = "0.9.6" +version = "0.10.0" description = "The vCon library - Complete vCon 0.4.0 specification implementation" authors = ["Thomas McCarthy-Howe "] license = "MIT" @@ -31,6 +31,7 @@ mutagen = "^1.47.0" sphinx = "<7.0.0" sphinx-rtd-theme = "^3.0.2" flake8 = "^7.1.2" +jsonschema = "^4.23.0" [build-system] requires = ["poetry-core"] diff --git a/scripts/check_version.py b/scripts/check_version.py new file mode 100644 index 0000000..88d5a43 --- /dev/null +++ b/scripts/check_version.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Version-consistency guard. + +Compares `pyproject.toml`'s `[tool.poetry].version` against: + +1. The newest numbered `## [x.y.z]` heading in `CHANGELOG.md`. +2. `setup.py`'s hardcoded `version="..."` string, if present. + +Run with no arguments to check consistency (used in CI on every push/PR). +Run with `--tag ` to additionally check a release tag (e.g. `v0.10.0` +or `refs/tags/v0.10.0`) against the pyproject version; used by the publish +workflow immediately before publishing, so a release cut from the wrong +commit fails loudly instead of shipping. + +Exit code is non-zero, with a message on stderr, on any mismatch. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +PYPROJECT = REPO_ROOT / "pyproject.toml" +CHANGELOG = REPO_ROOT / "CHANGELOG.md" +SETUP_PY = REPO_ROOT / "setup.py" + + +def _read_pyproject_version() -> str: + text = PYPROJECT.read_text() + # Only match within the [tool.poetry] table's own version key, which is + # the first `version = "..."` line in the file for this project's + # pyproject.toml layout. + match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', text) + if not match: + raise SystemExit(f"Could not find a version in {PYPROJECT}") + return match.group(1) + + +def _read_changelog_version() -> str: + text = CHANGELOG.read_text() + match = re.search(r"(?m)^##\s*\[(\d+\.\d+\.\d+)\]", text) + if not match: + raise SystemExit(f"Could not find a numbered '## [x.y.z]' heading in {CHANGELOG}") + return match.group(1) + + +def _read_setup_py_version() -> str | None: + if not SETUP_PY.exists(): + return None + text = SETUP_PY.read_text() + match = re.search(r'(?m)^\s*version\s*=\s*"([^"]+)"', text) + return match.group(1) if match else None + + +def _normalize_tag(tag: str) -> str: + tag = tag.strip() + if tag.startswith("refs/tags/"): + tag = tag[len("refs/tags/"):] + if tag.startswith("v"): + tag = tag[1:] + return tag + + +def main(argv: list[str]) -> int: + pyproject_version = _read_pyproject_version() + changelog_version = _read_changelog_version() + setup_py_version = _read_setup_py_version() + + errors = [] + + if pyproject_version != changelog_version: + errors.append( + f"pyproject.toml version ({pyproject_version}) does not match the " + f"newest CHANGELOG.md heading ({changelog_version})." + ) + + if setup_py_version is not None and setup_py_version != pyproject_version: + errors.append( + f"setup.py version ({setup_py_version}) does not match " + f"pyproject.toml version ({pyproject_version})." + ) + + if "--tag" in argv: + tag_arg = argv[argv.index("--tag") + 1] + tag_version = _normalize_tag(tag_arg) + if tag_version != pyproject_version: + errors.append( + f"Release tag ({tag_arg} -> {tag_version}) does not match " + f"pyproject.toml version ({pyproject_version}). Refusing to publish." + ) + + if errors: + for e in errors: + print(f"::error::{e}", file=sys.stderr) + return 1 + + print( + f"Version check OK: pyproject.toml={pyproject_version}, " + f"CHANGELOG.md={changelog_version}" + + (f", setup.py={setup_py_version}" if setup_py_version else "") + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/setup.py b/setup.py index 5f2d8f1..cc59f55 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name="vcon", - version="0.9.6", + version="0.10.0", author="Thomas McCarthy-Howe", author_email="ghostofbasho@gmail.com", description="A package for working with vCon containers", diff --git a/src/vcon/body.py b/src/vcon/body.py new file mode 100644 index 0000000..76c120a --- /dev/null +++ b/src/vcon/body.py @@ -0,0 +1,57 @@ +"""Helpers for decoding vCon attachment/analysis/dialog bodies. + +Under ``draft-ietf-vcon-vcon-core-04`` section 2.3.2, when ``encoding`` is +``"json"`` the ``body`` field is the JSON *value* itself (object, array, +string, number, bool, or ``null``) rather than a ``json.dumps``-serialized +string. Earlier drafts (and adapters/generators written against them, plus +some helpers in this library prior to 0.10.0) instead stored the JSON +representation of the value as a string body. + +``decode_body`` lets every reader in this library -- and callers of it -- +accept either shape without special-casing each call site. It is exported +both as a module-level function and as ``Vcon.decoded_body`` for +discoverability. +""" + +from typing import Any, Dict, Optional +import json + +__all__ = ["decode_body"] + + +def decode_body(entry: Optional[Dict[str, Any]]) -> Any: + """Return the decoded ``body`` of an attachment, analysis, or dialog entry. + + If ``encoding`` is ``"json"`` (or absent -- structured bodies were most + commonly written without an explicit encoding under -02 conventions) and + ``body`` is a string, the string is parsed as JSON and the resulting + value is returned. This accepts both: + + - vCons written under -02 conventions (or by this library prior to + 0.10.0), where a JSON body was serialized to a string, and + - -04-conformant vCons, where ``body`` is already the decoded value. + + Any other shape -- an already-decoded value, a ``base64url``/``none`` + encoded body, or a string that fails to parse as JSON -- is returned + unchanged. + + :param entry: an attachment, analysis, or dialog dict, or ``None`` + :type entry: dict or None + :return: the decoded body, or ``None`` if there is no body to decode + :rtype: Any + """ + if not entry: + return None + + body = entry.get("body") + if body is None: + return None + + encoding = entry.get("encoding") + if isinstance(body, str) and encoding in (None, "json"): + try: + return json.loads(body) + except (ValueError, TypeError): + return body + + return body diff --git a/src/vcon/dialog.py b/src/vcon/dialog.py index 048913e..71121b5 100644 --- a/src/vcon/dialog.py +++ b/src/vcon/dialog.py @@ -54,6 +54,41 @@ def _b64url_no_padding(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") +def b64url_encode(data: bytes) -> str: + """Base64url-encode ``data`` without padding. + + ``draft-ietf-vcon-vcon-core-04`` follows the JWS/RFC 7515 base64url + convention: no trailing ``=`` padding. Use this (instead of calling + ``base64.urlsafe_b64encode`` directly) whenever the library writes an + inline ``base64url``-encoded dialog or attachment body. + + :param data: the raw bytes to encode + :type data: bytes + :return: the unpadded base64url-encoded string + :rtype: str + """ + return _b64url_no_padding(data) + + +def b64url_decode(value: Union[str, bytes]) -> bytes: + """Base64url-decode ``value``, accepting padded or unpadded input. + + ``base64.urlsafe_b64decode`` requires exact padding, which rejects the + unpadded strings this library (and -04-conformant producers) now emits. + This re-pads before decoding so both padded (legacy) and unpadded + (spec-conformant) base64url bodies decode correctly. + + :param value: the base64url string (or bytes) to decode + :type value: str or bytes + :return: the decoded raw bytes + :rtype: bytes + """ + if isinstance(value, str): + value = value.encode("ascii") + padded = value + b"=" * (-len(value) % 4) + return base64.urlsafe_b64decode(padded) + + def compute_content_hash( data: bytes, algorithm: str = DEFAULT_CONTENT_HASH_ALGORITHM ) -> str: @@ -395,7 +430,14 @@ def to_dict(self): party_history.to_dict() for party_history in self.party_history ] - return {k: v for k, v in dialog_dict.items() if v is not None} + # 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 == {}) + } def add_external_data(self, url: str, filename: str, mediatype: str) -> None: """ @@ -591,7 +633,7 @@ def add_video_data(self, video_data, filename=None, mediatype=None, inline=True, # Add inline data if isinstance(video_data, bytes): # Base64 encode the binary data - encoded_data = base64.urlsafe_b64encode(video_data).decode() + encoded_data = b64url_encode(video_data) self.add_inline_data(encoded_data, filename, mediatype) else: # Assume it's already base64 encoded @@ -634,7 +676,7 @@ def extract_video_metadata(self, video_path=None) -> dict: if self.is_inline_data(): # Decode base64 content to temporary file temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=f".{self.get_video_format_from_mediatype()}") - video_data = base64.urlsafe_b64decode(self.body.encode()) + video_data = b64url_decode(self.body) temp_file.write(video_data) temp_file.close() video_path = temp_file.name @@ -755,7 +797,7 @@ def generate_thumbnail(self, timestamp=0.0, width=320, height=240, quality=90) - # Setup source video file if self.is_inline_data(): temp_video = tempfile.NamedTemporaryFile(delete=False, suffix=f".{self.get_video_format_from_mediatype()}") - video_data = base64.urlsafe_b64decode(self.body.encode()) + video_data = b64url_decode(self.body) temp_video.write(video_data) temp_video.close() video_path = temp_video.name @@ -960,7 +1002,7 @@ def transcode_video(self, target_format, codec=None, bit_rate=None, width=None, # Get source video if self.is_inline_data(): temp_input = tempfile.NamedTemporaryFile(delete=False, suffix=f".{self.get_video_format_from_mediatype()}") - video_data = base64.urlsafe_b64decode(self.body.encode()) + video_data = b64url_decode(self.body) temp_input.write(video_data) temp_input.close() input_path = temp_input.name @@ -1019,7 +1061,7 @@ def transcode_video(self, target_format, codec=None, bit_rate=None, width=None, # Use add_video_data to replace current content (maintaining inline/external status) if self.is_inline_data(): - encoded_data = base64.urlsafe_b64encode(new_video_data).decode() + encoded_data = b64url_encode(new_video_data) self.add_inline_data(encoded_data, new_filename, new_mediatype) # Update metadata to include transcoding info @@ -1116,7 +1158,7 @@ def add_image_data(self, image_path: str, mediatype: Optional[str] = None) -> No filename = os.path.basename(image_path) # Add as inline data - self.body = base64.urlsafe_b64encode(image_data).decode('utf-8') + self.body = b64url_encode(image_data) self.mediatype = mediatype self.filename = filename self.encoding = "base64url" @@ -1213,7 +1255,7 @@ def generate_thumbnail(self, max_size: Tuple[int, int] = (200, 200)) -> Optional # Get image data if hasattr(self, "body") and self.body: if self.encoding in ["base64url"]: - image_data = base64.urlsafe_b64decode(self.body) + image_data = b64url_decode(self.body) else: # If not base64 encoded, assume it's already raw data image_data = self.body.encode() if isinstance(self.body, str) else self.body @@ -1292,7 +1334,7 @@ def to_inline_data(self) -> None: # For binary content, use response.content instead of response.text raw_content = response.content # Base64url encode the body - self.body = base64.urlsafe_b64encode(raw_content).decode() + self.body = b64url_encode(raw_content) self.mediatype = response.headers.get("Content-Type") else: raise Exception(f"Failed to fetch external data: {response.status_code}") diff --git a/src/vcon/extensions/base.py b/src/vcon/extensions/base.py index 83472ba..02a5538 100644 --- a/src/vcon/extensions/base.py +++ b/src/vcon/extensions/base.py @@ -165,9 +165,11 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, data: Dict[str, Any]) -> 'ExtensionAttachment': """Create from dictionary representation.""" + from ..body import decode_body + return cls( attachment_purpose=data["purpose"], - body=data["body"], + body=decode_body(data), start=data.get("start"), party=data.get("party"), dialog=data.get("dialog"), diff --git a/src/vcon/extensions/lawful_basis/processing.py b/src/vcon/extensions/lawful_basis/processing.py index 54d0179..3e373e5 100644 --- a/src/vcon/extensions/lawful_basis/processing.py +++ b/src/vcon/extensions/lawful_basis/processing.py @@ -9,6 +9,7 @@ import logging from datetime import datetime, timezone from ..base import ExtensionProcessor, ProcessingResult +from ...body import decode_body from .attachment import ( LawfulBasisAttachment, ProofType, @@ -165,7 +166,7 @@ def evaluate_permission( permissions = [] for attachment_dict in applicable_attachments: try: - attachment = LawfulBasisAttachment.from_dict(attachment_dict["body"]) + attachment = LawfulBasisAttachment.from_dict(decode_body(attachment_dict)) permission = self._evaluate_attachment_permission(attachment, purpose) permissions.append(permission) except Exception as e: @@ -212,9 +213,11 @@ def _find_applicable_lawful_basis( if attachment_party is not None and attachment_party != party_index: continue - # Check if attachment has permission for the purpose - body = attachment.get("body", {}) - purpose_grants = body.get("purpose_grants", []) + # Check if attachment has permission for the purpose. Accept + # both the -04 shape (body already the decoded object) and a + # legacy JSON-string body. + body = decode_body(attachment) or {} + purpose_grants = body.get("purpose_grants", []) if isinstance(body, dict) else [] for grant in purpose_grants: if grant.get("purpose") == purpose: @@ -279,7 +282,7 @@ def process(self, vcon_dict: Dict[str, Any]) -> ProcessingResult: processed_attachments = [] for i, attachment in enumerate(lawful_basis_attachments): try: - attachment_obj = LawfulBasisAttachment.from_dict(attachment["body"]) + attachment_obj = LawfulBasisAttachment.from_dict(decode_body(attachment)) processed_attachments.append({ "index": i, "lawful_basis": attachment_obj.lawful_basis.value, diff --git a/src/vcon/extensions/lawful_basis/validation.py b/src/vcon/extensions/lawful_basis/validation.py index 22c6cf7..08068af 100644 --- a/src/vcon/extensions/lawful_basis/validation.py +++ b/src/vcon/extensions/lawful_basis/validation.py @@ -9,6 +9,7 @@ import logging from datetime import datetime, timezone from ..base import ExtensionValidator, ValidationResult +from ...body import decode_body from .attachment import ( LawfulBasisAttachment, LawfulBasisType, @@ -72,8 +73,9 @@ def validate_attachment(self, attachment: Dict[str, Any]) -> ValidationResult: if attachment.get("encoding") != "json": result.add_error("Lawful basis attachment must use 'json' encoding") - # Validate body structure - body = attachment.get("body") + # Validate body structure. Accept both the -04 shape (body already + # the decoded object) and a legacy JSON-string body. + body = decode_body(attachment) if not isinstance(body, dict): result.add_error("Lawful basis attachment body must be a dictionary") return result diff --git a/src/vcon/extensions/wtf/extension.py b/src/vcon/extensions/wtf/extension.py index c253f96..8d96dc2 100644 --- a/src/vcon/extensions/wtf/extension.py +++ b/src/vcon/extensions/wtf/extension.py @@ -8,6 +8,7 @@ from typing import Dict, Any, List, Optional import logging from ..base import ExtensionInfo, ExtensionType +from ...body import decode_body from .validation import WTFValidator from .processing import WTFProcessor from .attachment import WTFAttachment @@ -124,17 +125,17 @@ def export_transcription( format: str = "srt" ) -> str: """Export transcription in specified format.""" - wtf_attachment = WTFAttachment.from_dict(attachment["body"]) + wtf_attachment = WTFAttachment.from_dict(decode_body(attachment)) return self.processor.export_transcription(wtf_attachment, format) - + def analyze_transcription(self, attachment: Dict[str, Any]) -> Dict[str, Any]: """Perform analysis on a WTF transcription.""" - wtf_attachment = WTFAttachment.from_dict(attachment["body"]) + wtf_attachment = WTFAttachment.from_dict(decode_body(attachment)) return self.processor.analyze_transcription(wtf_attachment) - + def compare_transcriptions(self, attachments: List[Dict[str, Any]]) -> Dict[str, Any]: """Compare multiple transcriptions.""" wtf_attachments = [ - WTFAttachment.from_dict(att["body"]) for att in attachments + WTFAttachment.from_dict(decode_body(att)) for att in attachments ] return self.processor.compare_transcriptions(wtf_attachments) diff --git a/src/vcon/extensions/wtf/processing.py b/src/vcon/extensions/wtf/processing.py index f1671f5..81293db 100644 --- a/src/vcon/extensions/wtf/processing.py +++ b/src/vcon/extensions/wtf/processing.py @@ -8,6 +8,7 @@ from typing import Dict, List, Any, Optional, Union import logging from ..base import ExtensionProcessor, ProcessingResult +from ...body import decode_body from .attachment import WTFAttachment, Transcript, Segment, Word, Speaker, Quality logger = logging.getLogger(__name__) @@ -59,7 +60,7 @@ def process(self, vcon_dict: Dict[str, Any]) -> ProcessingResult: processed_attachments = [] for i, attachment in enumerate(wtf_attachments): try: - wtf_obj = WTFAttachment.from_dict(attachment["body"]) + wtf_obj = WTFAttachment.from_dict(decode_body(attachment)) # Calculate statistics stats = self._calculate_statistics(wtf_obj) diff --git a/src/vcon/extensions/wtf/validation.py b/src/vcon/extensions/wtf/validation.py index 9c30710..9136d41 100644 --- a/src/vcon/extensions/wtf/validation.py +++ b/src/vcon/extensions/wtf/validation.py @@ -8,6 +8,7 @@ from typing import Dict, List, Any, Optional import logging from ..base import ExtensionValidator, ValidationResult +from ...body import decode_body from .attachment import WTFAttachment, WTFProvider logger = logging.getLogger(__name__) @@ -33,8 +34,9 @@ def validate_attachment(self, attachment: Dict[str, Any]) -> ValidationResult: if attachment.get("encoding") != "json": result.add_error("WTF transcription attachment must use 'json' encoding") - # Validate body structure - body = attachment.get("body") + # Validate body structure. Accept both the -04 shape (body already + # the decoded object) and a legacy JSON-string body. + body = decode_body(attachment) if not isinstance(body, dict): result.add_error("WTF transcription attachment body must be a dictionary") return result diff --git a/src/vcon/vcon.py b/src/vcon/vcon.py index 9cca352..709d761 100644 --- a/src/vcon/vcon.py +++ b/src/vcon/vcon.py @@ -18,7 +18,8 @@ import requests import logging from .party import Party -from .dialog import Dialog +from .dialog import Dialog, b64url_encode +from .body import decode_body # Set up logger logger = logging.getLogger(__name__) @@ -120,6 +121,15 @@ def __init__( if encoding not in self.VALID_ENCODINGS: logger.error(f"Invalid encoding attempted: {encoding}") 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. + if mediatype is None and encoding == "json": + mediatype = "application/json" + self.purpose = purpose self.body = body self.encoding = encoding @@ -128,8 +138,8 @@ def __init__( self.url = url self.content_hash = content_hash self.start = start - self.party = party - self.dialog = dialog + self.party = party if party is not None else 0 + self.dialog = dialog if dialog is not None else 0 logger.debug(f"Created new attachment of purpose {purpose} with {encoding} encoding") def to_dict(self) -> Dict[str, Any]: @@ -189,7 +199,7 @@ def from_image(cls, image_path: str, purpose: str = "image") -> 'Attachment': # Create and return attachment return cls( purpose=purpose, - body=base64.urlsafe_b64encode(image_data).decode('utf-8'), + body=b64url_encode(image_data), encoding="base64url", mediatype=mimetype, filename=filename, @@ -516,9 +526,16 @@ def get_tag(self, tag_name: str) -> Optional[str]: if not tags_attachment: logger.debug("No tags attachment found") return None - + + # Accept both the -04 shape (body is already the list) and legacy + # vCons where the tags body was written as a JSON-encoded string. + tags = decode_body(tags_attachment) + if not isinstance(tags, list): + logger.debug("Tags attachment body is not a list") + return None + tag = next( - (t for t in tags_attachment["body"] if t.startswith(f"{tag_name}:")), None + (t for t in tags if isinstance(t, str) and t.startswith(f"{tag_name}:")), None ) if not tag: logger.debug(f"Tag {tag_name} not found") @@ -552,10 +569,22 @@ def add_tag(self, tag_name: str, tag_value: str) -> None: "purpose": "tags", "body": [], "encoding": "json", + "mediatype": "application/json", + "start": self.vcon_dict.get("created_at"), "party": 0, "dialog": 0, } self.vcon_dict["attachments"].append(tags_attachment) + else: + # Normalize a legacy (pre-0.10.0 / -02 convention) JSON-string + # body to the -04 list-valued body in place, preserving + # existing tags. + current_tags = decode_body(tags_attachment) + if not isinstance(current_tags, list): + current_tags = [] + tags_attachment["body"] = current_tags + tags_attachment.setdefault("mediatype", "application/json") + tags_attachment.setdefault("start", self.vcon_dict.get("created_at")) tags_attachment["body"].append(f"{tag_name}:{tag_value}") logger.info(f"Added tag {tag_name}:{tag_value}") @@ -702,13 +731,18 @@ def add_lawful_basis_attachment( purpose_grants=purpose_grants, **kwargs ) - - # Add party and dialog references if provided - if party_index is not None: - attachment["party"] = party_index - if dialog_index is not None: - attachment["dialog"] = dialog_index - + + # 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 + + # Fill in mediatype/start, also required by the schema, unless + # already set via **kwargs. + attachment.setdefault("mediatype", "application/json") + attachment.setdefault("start", self.vcon_dict.get("created_at")) + self.vcon_dict["attachments"].append(attachment) # Add extension to extensions list if not already present @@ -761,13 +795,18 @@ def add_wtf_transcription_attachment( metadata=metadata, **kwargs ) - - # Add party and dialog references if provided - if party_index is not None: - attachment["party"] = party_index - if dialog_index is not None: - attachment["dialog"] = dialog_index - + + # 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 + + # Fill in mediatype/start, also required by the schema, unless + # already set via **kwargs. + attachment.setdefault("mediatype", "application/json") + attachment.setdefault("start", self.vcon_dict.get("created_at")) + self.vcon_dict["attachments"].append(attachment) # Add extension to extensions list if not already present @@ -962,6 +1001,30 @@ def process_extensions(self) -> Dict[str, Any]: logger.error(f"Error processing extensions: {str(e)}") return {"error": str(e)} + @staticmethod + def decoded_body(entry: Optional[Dict[str, Any]]) -> Any: + """ + Return the decoded ``body`` of an attachment, analysis, or dialog entry. + + Under ``draft-ietf-vcon-vcon-core-04``, a ``"json"``-encoded body is + the JSON value itself, not a ``json.dumps`` string. This accepts + both that shape and the JSON-string bodies written under -02 + conventions (or by this library prior to 0.10.0), so callers don't + need to special-case legacy vCons. + + Args: + entry: An attachment, analysis, or dialog dictionary + + Returns: + The decoded body, or None if there is no body + + Example: + >>> vcon = Vcon.build_new() + >>> vcon.add_tag("category", "meeting") + >>> Vcon.decoded_body(vcon.tags) # ["category:meeting"] + """ + return decode_body(entry) + def find_attachment_by_purpose(self, purpose: str) -> Optional[Dict[str, Any]]: """ Find an attachment in the vCon by its purpose. @@ -1034,6 +1097,11 @@ def add_attachment( """ logger.debug(f"Creating new attachment of purpose {purpose} with {encoding} encoding") + # The WG JSON schema requires start on every attachment; default to + # this vCon's created_at when the caller doesn't supply one. + if start is None: + start = self.vcon_dict.get("created_at") + attachment = Attachment( purpose=purpose, body=body, @@ -1080,6 +1148,11 @@ def add_image(self, image_path: str, purpose: str = "image") -> Attachment: >>> print(attachment.mediatype) # Prints "application/pdf" """ attachment = Attachment.from_image(image_path, purpose) + # The WG JSON schema requires start on every attachment; default to + # this vCon's created_at (party/dialog already default to 0 in + # Attachment.__init__). + if attachment.start is None: + attachment.start = self.vcon_dict.get("created_at") self.vcon_dict["attachments"].append(attachment.to_dict()) logger.info(f"Added new image attachment of purpose {purpose}") return attachment @@ -1646,6 +1719,7 @@ def uuid8_time(custom_c_62_bits: int) -> str: ns = time.time_ns() if _LAST_V8_TIMESTAMP is not None and ns <= _LAST_V8_TIMESTAMP: ns = _LAST_V8_TIMESTAMP + 1 + _LAST_V8_TIMESTAMP = ns timestamp_ms, timestamp_ns = divmod(ns, 10**6) subsec = uuid6._subsec_encode(timestamp_ns) diff --git a/tests/schema/SOURCE.md b/tests/schema/SOURCE.md new file mode 100644 index 0000000..2bec2ba --- /dev/null +++ b/tests/schema/SOURCE.md @@ -0,0 +1,16 @@ +# 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. + +- 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` + +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. diff --git a/tests/schema/vcon_json_schema.json b/tests/schema/vcon_json_schema.json new file mode 100644 index 0000000..9a323fb --- /dev/null +++ b/tests/schema/vcon_json_schema.json @@ -0,0 +1,1291 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://ietf.org/vcon/schemas/unsigned-vcon.json", + "title": "vCon - Unsigned Form", + "description": "JSON schema for the unsigned form of vCon (Conversational Data Container) as defined in RFCXXXX", + "type": "object", + "required": [ + "uuid", + "created_at" + ], + "properties": { + "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" + }, + "uuid": { + "type": "string", + "description": "Globally unique identifier for the vCon. SHOULD be a version 8 UUID", + "format": "uuid" + }, + "extensions": { + "type": "array", + "description": "List of names of all vCon extensions used by this vCon", + "items": { + "type": "string" + } + }, + "critical": { + "type": "array", + "description": "List of extension names that a consumer MUST support to safely process this vCon", + "items": { + "type": "string" + } + }, + "created_at": { + "type": "string", + "description": "Creation time of this vCon in RFC3339 format", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "description": "Last modified time of this vCon in RFC3339 format", + "format": "date-time" + }, + "subject": { + "type": "string", + "description": "Subject or topic of the conversation" + }, + "redacted": { + "type": "object", + "description": "Reference to the unredacted or less redacted vCon prior instance", + "required": [ + "type" + ], + "properties": { + "uuid": { + "type": "string", + "description": "UUID of the unredacted or less redacted vCon prior instance", + "format": "uuid" + }, + "type": { + "type": "string", + "description": "Type of redaction performed" + }, + "url": { + "type": "string", + "description": "HTTPS URL where the referenced vCon is stored", + "format": "uri" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of the external content using format: algorithm-base64url_encoded_hash" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + } + }, + "amended": { + "type": "object", + "description": "Reference to the prior vCon instance version that this vCon amends", + "properties": { + "uuid": { + "type": "string", + "description": "UUID of the prior vCon instance version", + "format": "uuid" + }, + "url": { + "type": "string", + "description": "HTTPS URL where the referenced vCon is stored", + "format": "uri" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of the external content (required if url is provided)" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "if": { + "not": { + "required": [ + "url" + ] + } + }, + "then": { + "required": [ + "uuid" + ], + "$comment": "uuid is optional only if an external reference is provided" + } + }, + "parties": { + "type": "array", + "description": "Array of Party Objects representing all parties involved in the conversation", + "items": { + "$ref": "#/definitions/Party" + } + }, + "dialog": { + "type": "array", + "description": "Array of Dialog Objects containing the captured conversation content", + "items": { + "$ref": "#/definitions/Dialog" + } + }, + "analysis": { + "type": "array", + "description": "Array of Analysis Objects containing analysis performed on the conversational data", + "items": { + "$ref": "#/definitions/Analysis" + } + }, + "attachments": { + "type": "array", + "description": "Array of Attachment Objects for ancillary documents related to the conversation", + "items": { + "$ref": "#/definitions/Attachment" + } + } + }, + "definitions": { + "Party": { + "type": "object", + "description": "Represents a party involved in the conversation", + "properties": { + "tel": { + "type": "string", + "description": "TEL URL (RFC3966) for the party" + }, + "sip": { + "type": "string", + "description": "SIP URL for the party" + }, + "stir": { + "type": "string", + "description": "STIR PASSporT in JWS Compact Serialization form" + }, + "mailto": { + "type": "string", + "description": "Email address for the party in any common form, including a bare address or a MAILTO URL" + }, + "name": { + "type": "string", + "description": "Name of the party" + }, + "did": { + "type": "string", + "description": "Decentralized Identifier (DID) URI for the party" + }, + "validation": { + "type": "string", + "description": "Label or token identifying the method of identity validation used" + }, + "gmlpos": { + "type": "string", + "description": "Geographic location in GML pos format (latitude longitude)" + }, + "civicaddress": { + "$ref": "#/definitions/Civicaddress" + }, + "uuid": { + "type": "string", + "description": "Free form unique identifier for the participant; not constrained to UUID syntax" + }, + "type": { + "type": "string", + "description": "Participant type" + }, + "org": { + "type": "string", + "description": "Organization to which the party belongs" + }, + "dept": { + "type": "string", + "description": "Department to which the party belongs" + } + } + }, + "Civicaddress": { + "type": "object", + "description": "Civic address information for a party's location", + "properties": { + "country": { + "type": "string" + }, + "a1": { + "type": "string", + "description": "National subdivision (state/province)" + }, + "a2": { + "type": "string", + "description": "County/parish/district" + }, + "a3": { + "type": "string", + "description": "City/township" + }, + "a4": { + "type": "string", + "description": "City division/borough" + }, + "a5": { + "type": "string", + "description": "Neighborhood/block" + }, + "a6": { + "type": "string", + "description": "Street" + }, + "prd": { + "type": "string", + "description": "Leading street direction" + }, + "pod": { + "type": "string", + "description": "Trailing street suffix" + }, + "sts": { + "type": "string", + "description": "Street suffix" + }, + "hno": { + "type": "string", + "description": "House number" + }, + "hns": { + "type": "string", + "description": "House number suffix" + }, + "lmk": { + "type": "string", + "description": "Landmark" + }, + "loc": { + "type": "string", + "description": "Additional location info" + }, + "flr": { + "type": "string", + "description": "Floor" + }, + "nam": { + "type": "string", + "description": "Name/occupant" + }, + "pc": { + "type": "string", + "description": "Postal code" + } + } + }, + "Dialog": { + "type": "object", + "description": "Represents a segment of captured conversation", + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "recording", + "text", + "transfer", + "incomplete", + "recording-set" + ], + "description": "Type of dialog" + }, + "start": { + "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" + }, + "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 parties in the parties array; SHOULD be present for recording, recording-set and text types; MUST NOT be present for transfer type" + }, + "originator": { + "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" + }, + "recording_set": { + "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" + }, + "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" + }, + "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" + }, + "party_history": { + "type": "array", + "items": { + "$ref": "#/definitions/PartyHistory" + }, + "description": "History of party join/drop/hold/mute 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)" + }, + "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" + }, + "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" + }, + "target_dialog": { + "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" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "allOf": [ + { + "if": { + "properties": { + "type": { + "const": "incomplete" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "disposition" + ] + } + }, + { + "if": { + "properties": { + "type": { + "const": "recording-set" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "recordings" + ] + } + }, + { + "if": { + "properties": { + "type": { + "const": "transfer" + } + }, + "required": [ + "type" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "parties" + ] + }, + { + "required": [ + "originator" + ] + }, + { + "required": [ + "session_id" + ] + }, + { + "required": [ + "party_history" + ] + }, + { + "required": [ + "message_id" + ] + }, + { + "required": [ + "recordings" + ] + }, + { + "required": [ + "recording_set" + ] + }, + { + "required": [ + "mediatype" + ] + }, + { + "required": [ + "filename" + ] + }, + { + "required": [ + "body" + ] + }, + { + "required": [ + "encoding" + ] + }, + { + "required": [ + "url" + ] + }, + { + "required": [ + "content_hash" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "recording-set" + } + }, + "required": [ + "type" + ] + }, + "then": { + "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" + ] + }, + { + "required": [ + "target_dialog" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "incomplete" + } + }, + "required": [ + "type" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "message_id" + ] + }, + { + "required": [ + "recordings" + ] + }, + { + "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" + ] + }, + { + "required": [ + "target_dialog" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "recording" + } + }, + "required": [ + "type" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "recordings" + ] + }, + { + "required": [ + "transferee" + ] + }, + { + "required": [ + "transferor" + ] + }, + { + "required": [ + "transfer_target" + ] + }, + { + "required": [ + "original" + ] + }, + { + "required": [ + "consultation" + ] + }, + { + "required": [ + "target_dialog" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "text" + } + }, + "required": [ + "type" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "recordings" + ] + }, + { + "required": [ + "recording_set" + ] + }, + { + "required": [ + "transferee" + ] + }, + { + "required": [ + "transferor" + ] + }, + { + "required": [ + "transfer_target" + ] + }, + { + "required": [ + "original" + ] + }, + { + "required": [ + "consultation" + ] + }, + { + "required": [ + "target_dialog" + ] + } + ] + } + } + }, + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "encoding" + ] + } + }, + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "mediatype" + ] + } + } + ] + }, + "SessionId": { + "type": "object", + "description": "Session identifier with local and remote UUIDs", + "properties": { + "local": { + "type": "string", + "description": "Local UUID for the session" + }, + "remote": { + "type": "string", + "description": "Remote UUID for the session" + } + } + }, + "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" + ], + "properties": { + "purpose": { + "type": "string", + "description": "text description of what the attachment is for" + }, + "start": { + "type": "string", + "format": "date-time", + "description": "Time the attachment was sent/exchanged in RFC3339 format" + }, + "party": { + "type": "integer", + "minimum": 0, + "description": "Index of the party that contributed the attachment" + }, + "dialog": { + "type": "integer", + "minimum": 0, + "description": "Index of the dialog this attachment is part of" + }, + "mediatype": { + "type": "string", + "description": "Media type of the attachment content; MUST be present for inline content; not required when Attachment Content is absent" + }, + "filename": { + "type": "string", + "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." + }, + "encoding": { + "type": "string", + "enum": [ + "base64url", + "json", + "none" + ], + "description": "Encoding type for inline content" + }, + "url": { + "type": "string", + "format": "uri", + "description": "HTTPS URL for externally referenced attachment" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of external content" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "allOf": [ + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "encoding" + ] + } + }, + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "mediatype" + ] + } + } + ] + }, + "Analysis": { + "type": "object", + "description": "Represents analysis performed on the conversational data", + "required": [ + "type", + "vendor" + ], + "properties": { + "type": { + "type": "string", + "description": "Semantic type of analysis (e.g., report, sentiment, summary, transcript, translation, tts)" + }, + "dialog": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of dialog objects this analysis is based on" + }, + "attachment": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of attachment objects this analysis is based on" + }, + "mediatype": { + "type": "string", + "description": "Media type of the analysis content; SHOULD be provided for inline content and for external content without an HTTPS Content-Type header; when no media type is defined for the data format, the vendor, product and schema parameters SHOULD identify the format instead" + }, + "filename": { + "type": "string", + "description": "Original filename of the analysis data" + }, + "vendor": { + "type": "string", + "description": "Vendor or product name that generated the analysis" + }, + "product": { + "type": "string", + "description": "Product name to differentiate from other vendor products" + }, + "schema": { + "type": "string", + "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." + }, + "encoding": { + "type": "string", + "enum": [ + "base64url", + "json", + "none" + ], + "description": "Encoding type for inline content" + }, + "url": { + "type": "string", + "format": "uri", + "description": "HTTPS URL for externally referenced analysis" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of external content" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "allOf": [ + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "encoding" + ] + } + } + ] + } + }, + "not": { + "required": [ + "redacted", + "amended" + ], + "$comment": "The redacted and amended 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." +} + diff --git a/tests/test_body_decode.py b/tests/test_body_decode.py new file mode 100644 index 0000000..c4e372d --- /dev/null +++ b/tests/test_body_decode.py @@ -0,0 +1,107 @@ +"""Tests for vcon.body.decode_body and its use across reader call sites. + +draft-ietf-vcon-vcon-core-04 section 2.3.2 makes a "json"-encoded body the +JSON value itself, not a json.dumps string. These tests confirm readers +accept both that shape and the legacy JSON-string shape written under -02 +conventions (and by this library prior to 0.10.0). +""" + +import json + +import pytest + +from vcon import Vcon +from vcon.body import decode_body + + +def test_decode_body_passthrough_for_already_decoded_value(): + assert decode_body({"body": ["a", "b"], "encoding": "json"}) == ["a", "b"] + assert decode_body({"body": {"k": "v"}, "encoding": "json"}) == {"k": "v"} + + +def test_decode_body_parses_legacy_json_string(): + entry = {"body": json.dumps(["a", "b"]), "encoding": "json"} + assert decode_body(entry) == ["a", "b"] + + +def test_decode_body_parses_string_with_no_encoding_set(): + entry = {"body": json.dumps({"k": "v"})} + assert decode_body(entry) == {"k": "v"} + + +def test_decode_body_leaves_base64url_and_none_bodies_as_strings(): + assert decode_body({"body": "abcXYZ", "encoding": "base64url"}) == "abcXYZ" + assert decode_body({"body": "plain text", "encoding": "none"}) == "plain text" + + +def test_decode_body_leaves_unparseable_string_unchanged(): + entry = {"body": "not json", "encoding": "json"} + assert decode_body(entry) == "not json" + + +def test_decode_body_handles_missing_or_empty_entry(): + assert decode_body(None) is None + assert decode_body({}) is None + assert decode_body({"encoding": "json"}) is None + + +def test_vcon_decoded_body_delegates_to_module_function(): + entry = {"body": json.dumps([1, 2, 3]), "encoding": "json"} + assert Vcon.decoded_body(entry) == [1, 2, 3] + + +def test_get_tag_reads_legacy_string_tags_body_without_add_tag(): + """get_tag() must work even on a raw legacy vCon it never wrote itself.""" + vcon = Vcon.build_new() + vcon.vcon_dict["attachments"].append( + { + "purpose": "tags", + "body": json.dumps(["category:legacy"]), + "encoding": "json", + "party": 0, + "dialog": 0, + } + ) + assert vcon.get_tag("category") == "legacy" + assert vcon.get_tag("missing") is None + + +def test_lawful_basis_validator_accepts_legacy_string_body(): + from vcon.extensions.lawful_basis.validation import LawfulBasisValidator + + body = { + "lawful_basis": "consent", + "expiration": "2030-01-01T00:00:00+00:00", + "purpose_grants": [ + {"purpose": "recording", "granted": True, "granted_at": "2025-01-01T00:00:00+00:00"} + ], + } + attachment = { + "purpose": "lawful_basis", + "encoding": "json", + "body": json.dumps(body), + } + result = LawfulBasisValidator().validate_attachment(attachment) + assert result.is_valid, result.errors + + +def test_wtf_validator_accepts_legacy_string_body(): + from vcon.extensions.wtf.validation import WTFValidator + + body = { + "transcript": {"text": "hello", "language": "en", "duration": 1.0, "confidence": 0.9}, + "segments": [{"id": 0, "start": 0.0, "end": 1.0, "text": "hello", "confidence": 0.9}], + "metadata": { + "created_at": "2025-01-01T00:00:00Z", + "processed_at": "2025-01-01T00:00:01Z", + "provider": "whisper", + "model": "whisper-1", + }, + } + attachment = { + "purpose": "wtf_transcription", + "encoding": "json", + "body": json.dumps(body), + } + result = WTFValidator().validate_attachment(attachment) + assert result.is_valid, result.errors diff --git a/tests/test_dialog.py b/tests/test_dialog.py index cde858c..5897e46 100644 --- a/tests/test_dialog.py +++ b/tests/test_dialog.py @@ -3,6 +3,7 @@ Dialog, compute_content_hash, parse_content_hash_algorithm, + b64url_decode, ) import hashlib import base64 @@ -407,8 +408,11 @@ def test_to_inline_data_binary(self): assert dialog.encoding == "base64url" assert dialog.content_hash is not None - # Decode the base64url body and verify it matches original content - decoded_body = base64.urlsafe_b64decode(dialog.body.encode()) + # Decode the base64url body and verify it matches original content. + # -04 base64url bodies are unpadded (RFC 7515-style); b64url_decode + # tolerates both padded and unpadded input. + assert "=" not in dialog.body + decoded_body = b64url_decode(dialog.body) assert decoded_body == fake_binary_data # Verify the content hash matches the content (spec-compliant sha512) diff --git a/tests/test_dialog_more.py b/tests/test_dialog_more.py index 4639b23..229104a 100644 --- a/tests/test_dialog_more.py +++ b/tests/test_dialog_more.py @@ -5,7 +5,7 @@ import pytest -from src.vcon.dialog import Dialog +from src.vcon.dialog import Dialog, b64url_decode def test_is_audio_image_pdf_and_frame_rate(): @@ -61,4 +61,7 @@ def fake_guess_type(path): assert dialog.mediatype == "image/jpeg" assert dialog.filename == "image.jpg" assert dialog.content_hash - assert base64.urlsafe_b64decode(dialog.body.encode()) == b"jpgdata" + # -04 base64url bodies are unpadded (RFC 7515-style); b64url_decode + # tolerates both padded and unpadded input. + assert "=" not in dialog.body + assert b64url_decode(dialog.body) == b"jpgdata" diff --git a/tests/test_schema_compliance.py b/tests/test_schema_compliance.py new file mode 100644 index 0000000..5aac324 --- /dev/null +++ b/tests/test_schema_compliance.py @@ -0,0 +1,124 @@ +"""Validate library output against the vCon working group's JSON schema. + +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 +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. +""" + +import json +from pathlib import Path + +import pytest + +jsonschema = pytest.importorskip("jsonschema") + +from vcon import Vcon +from vcon.party import Party +from vcon.dialog import Dialog, b64url_encode + +SCHEMA_PATH = Path(__file__).parent / "schema" / "vcon_json_schema.json" + + +def _load_schema(): + return json.loads(SCHEMA_PATH.read_text()) + + +def test_vcon_built_with_public_helpers_validates_against_wg_schema(): + schema = _load_schema() + + vcon = Vcon.build_new() + vcon.add_party(Party(name="Alice", role="caller")) + vcon.add_party(Party(name="Bob", role="agent")) + + # Dialog without inline audio (plain text). + text_dialog = Dialog( + type="text", + start=vcon.created_at, + parties=[0, 1], + body="Hello, how can I help?", + encoding="none", + mediatype="text/plain", + ) + vcon.add_dialog(text_dialog) + + # Dialog with inline audio, base64url-encoded per -04 (unpadded). + audio_bytes = b"RIFF\x00\x00\x00\x00WAVEfmt fake audio payload" + audio_dialog = Dialog( + type="recording", + start=vcon.created_at, + parties=[0, 1], + body=b64url_encode(audio_bytes), + encoding="base64url", + mediatype="audio/x-wav", + ) + vcon.add_dialog(audio_dialog) + + vcon.add_tag("category", "support") + vcon.add_tag("priority", "high") + + vcon.add_lawful_basis_attachment( + lawful_basis="consent", + expiration="2030-01-01T00:00:00Z", + purpose_grants=[ + {"purpose": "recording", "granted": True, "granted_at": vcon.created_at} + ], + party_index=0, + dialog_index=1, + ) + + vcon.add_attachment( + purpose="notes", + body={"summary": "Customer called about billing."}, + encoding="json", + party=1, + dialog=0, + ) + + vcon_dict = vcon.to_dict() + + # No post-processing: validate exactly what the library produced. + jsonschema.validate(instance=vcon_dict, schema=schema) + + # Also confirm the library's own validator is happy with the same + # output, and that content is what we expect. + is_valid, errors = vcon.is_valid() + assert is_valid, errors + assert vcon.get_tag("category") == "support" + assert vcon.get_tag("priority") == "high" + + +def test_legacy_string_tags_body_still_validates_after_add_tag(): + """A vCon with a legacy (pre-0.10.0) JSON-string tags body should, once + add_tag() normalizes it back to a list, validate against the schema.""" + schema = _load_schema() + + vcon = Vcon.build_new() + vcon.add_party(Party(name="Alice")) + + # Simulate a vCon written under -02 conventions / by an older release: + # the tags attachment body is a JSON-encoded string, not a list. + vcon.vcon_dict["attachments"].append( + { + "purpose": "tags", + "body": json.dumps(["existing:tag"]), + "encoding": "json", + "mediatype": "application/json", + "start": vcon.created_at, + "party": 0, + "dialog": 0, + } + ) + + assert vcon.get_tag("existing") == "tag" + + vcon.add_tag("new", "value") + + tags_attachment = vcon.find_attachment_by_purpose("tags") + assert tags_attachment["body"] == ["existing:tag", "new:value"] + assert vcon.get_tag("existing") == "tag" + assert vcon.get_tag("new") == "value" + + jsonschema.validate(instance=vcon.to_dict(), schema=schema) diff --git a/tests/test_vcon.py b/tests/test_vcon.py index ff0486e..30a1f65 100644 --- a/tests/test_vcon.py +++ b/tests/test_vcon.py @@ -183,10 +183,17 @@ 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. assert vcon.vcon_dict["attachments"][0] == { "purpose": "test_purpose", "body": "test_body", "encoding": "none", + "start": vcon.created_at, + "party": 0, + "dialog": 0, } assert isinstance(attachment, Attachment) @@ -242,6 +249,9 @@ def test_find_attachment_by_purpose() -> None: "purpose": "test_purpose", "body": {"key": "value"}, "encoding": "none", + "start": vcon.created_at, + "party": 0, + "dialog": 0, } assert vcon.find_attachment_by_purpose("nonexistent_purpose") is None