diff --git a/packages/modpoll-wot/AGENTS.md b/packages/modpoll-wot/AGENTS.md index d17a8fc..7381521 100644 --- a/packages/modpoll-wot/AGENTS.md +++ b/packages/modpoll-wot/AGENTS.md @@ -1,6 +1,6 @@ # modpoll-wot repository conventions -- Review the working tree and current branch before editing. Integrate changes into `main` through a reviewed pull request with passing CI. +- Review the working tree and current branch before editing. This package lives in the modpoll repository's uv workspace; integrate changes into `v2` through a pull request with passing CI. - This repository owns the shared TM/TD executable profile, its bundled schemas, and the offline CLI. Modpoll, Modsim, Open Modbus Catalog, and ModioHub consume published releases only. - Run `mise run check` before opening a pull request. - Released versions and tags are immutable. Release the producer first, then update consumer pins in their own repositories. See [README](README.md#releases). diff --git a/packages/modpoll-wot/modpoll_wot/__init__.py b/packages/modpoll-wot/modpoll_wot/__init__.py index 4321a44..4126109 100644 --- a/packages/modpoll-wot/modpoll_wot/__init__.py +++ b/packages/modpoll-wot/modpoll_wot/__init__.py @@ -24,7 +24,10 @@ server_url, ) from .verification import ( + REPORT_VERSION, ReportError, + identity_constants, + identity_result, model_fingerprint, point_fingerprints, validate_report, @@ -52,7 +55,10 @@ "load_simulation_data", "scaled_raw", "parse_parameters", + "REPORT_VERSION", "ReportError", + "identity_constants", + "identity_result", "model_fingerprint", "point_fingerprints", "validate_report", diff --git a/packages/modpoll-wot/modpoll_wot/schemas/SOURCES.md b/packages/modpoll-wot/modpoll_wot/schemas/SOURCES.md index 2b16cb9..a5f04fd 100644 --- a/packages/modpoll-wot/modpoll_wot/schemas/SOURCES.md +++ b/packages/modpoll-wot/modpoll_wot/schemas/SOURCES.md @@ -17,7 +17,7 @@ Upstream repository and licensing: https://github.com/w3c/wot-thing-description This binding is a work in progress, not a W3C Recommendation. acquisition-0.2.json is the executable project schema. -verification-report-3.json and verification-report-4.json are the project's hardware verification report schemas. In schema 4 the product is optional: the receiving service resolves it from the model fingerprint, while older reports may still carry it. +verification-report-3.json, verification-report-4.json and verification-report-5.json are the project's hardware verification report schemas. In schema 4 the product is optional: the receiving service resolves it from the model fingerprint, while older reports may still carry it. Schema 5 adds the optional per-point identity result for points whose DataSchema declares const. simulation-data-1.json is the project's simulation data schema. Profile 0.1 is not bundled or executable in current development source. The Modbus schema's TD reference resolves only to bundled TD 1.1; other remote resolution remains disabled. diff --git a/packages/modpoll-wot/modpoll_wot/schemas/verification-report-5.json b/packages/modpoll-wot/modpoll_wot/schemas/verification-report-5.json new file mode 100644 index 0000000..dd15b16 --- /dev/null +++ b/packages/modpoll-wot/modpoll_wot/schemas/verification-report-5.json @@ -0,0 +1,269 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/top-maker/modpoll-wot/schemas/verification-report-5.json", + "title": "Modbus hardware verification report", + "description": "One reading of a Thing Model on a physical device, without endpoints, serial numbers or raw values. The receiving service resolves the catalog product from the model fingerprint; a report may still carry product. A successfully read point whose DataSchema declares const records whether the value read matched it.", + "type": "object", + "additionalProperties": false, + "required": [ + "reportVersion", + "model", + "tool", + "transport", + "date", + "points" + ], + "properties": { + "reportVersion": { + "const": 5 + }, + "product": { + "$ref": "#/$defs/productId" + }, + "model": { + "type": "object", + "additionalProperties": false, + "required": [ + "sha256", + "fingerprint", + "source" + ], + "properties": { + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "fingerprint": { + "type": "string", + "pattern": "^mf1:[0-9a-f]{64}$" + }, + "source": { + "enum": [ + "catalog", + "workspace", + "local" + ] + }, + "ref": { + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + "allOf": [ + { + "if": { + "properties": { + "source": { + "const": "catalog" + } + } + }, + "then": { + "required": [ + "ref" + ], + "properties": { + "ref": { + "pattern": "^[0-9a-f]{40}$" + } + } + } + }, + { + "if": { + "properties": { + "source": { + "const": "workspace" + } + } + }, + "then": { + "required": [ + "ref" + ] + } + }, + { + "if": { + "properties": { + "source": { + "const": "local" + } + } + }, + "then": { + "not": { + "required": [ + "ref" + ] + } + } + } + ] + }, + "tool": { + "type": "object", + "additionalProperties": false, + "required": [ + "name", + "version", + "interpreter" + ], + "properties": { + "name": { + "$ref": "#/$defs/slug" + }, + "version": { + "$ref": "#/$defs/version" + }, + "interpreter": { + "$ref": "#/$defs/version" + } + } + }, + "transport": { + "enum": [ + "tcp", + "rtu" + ] + }, + "date": { + "type": "string", + "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$" + }, + "environment": { + "type": "object", + "additionalProperties": false, + "properties": { + "chassis": { + "$ref": "#/$defs/productId" + }, + "firmware": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "configuration": { + "type": "string", + "minLength": 1, + "maxLength": 200 + } + } + }, + "points": { + "type": "array", + "minItems": 1, + "maxItems": 1000, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "property", + "fingerprint", + "read", + "expected" + ], + "properties": { + "property": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "fingerprint": { + "type": "string", + "pattern": "^pf1:[0-9a-f]{64}$" + }, + "read": { + "enum": [ + "ok", + "exception", + "no-response", + "not-tested" + ] + }, + "exceptionCode": { + "type": "integer", + "minimum": 1, + "maximum": 255 + }, + "expected": { + "enum": [ + "confirmed", + "rejected", + "unchecked" + ] + }, + "identity": { + "enum": [ + "match", + "mismatch" + ] + } + }, + "allOf": [ + { + "if": { + "properties": { + "read": { + "const": "exception" + } + } + }, + "then": { + "required": [ + "exceptionCode" + ] + }, + "else": { + "not": { + "required": [ + "exceptionCode" + ] + } + } + }, + { + "if": { + "properties": { + "read": { + "not": { + "const": "ok" + } + } + } + }, + "then": { + "properties": { + "expected": { + "const": "unchecked" + } + }, + "not": { + "required": [ + "identity" + ] + } + } + } + ] + } + } + }, + "$defs": { + "slug": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$", + "maxLength": 64 + }, + "productId": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*/[a-z0-9]+(?:-[a-z0-9]+)*$", + "maxLength": 129 + }, + "version": { + "type": "string", + "pattern": "^[0-9A-Za-z.+-]{1,64}$" + } + } +} diff --git a/packages/modpoll-wot/modpoll_wot/verification.py b/packages/modpoll-wot/modpoll_wot/verification.py index 2c2ae13..0dd0347 100644 --- a/packages/modpoll-wot/modpoll_wot/verification.py +++ b/packages/modpoll-wot/modpoll_wot/verification.py @@ -15,7 +15,10 @@ FINGERPRINT_VERSION = "pf1" MODEL_FINGERPRINT_VERSION = "mf1" -REPORT_VERSION = 3 +# The newest verification report schema; validate_report also accepts the older ones. +REPORT_VERSION = 5 +REPORT_VERSIONS = (3, 4, 5) +IDENTITY_RESULTS = ("match", "mismatch") # Form fields that decide which bytes are read and how they become a value. OPTIONAL_FIELDS = ( "modpoll:codec", @@ -109,6 +112,34 @@ def combine_fingerprints(fingerprints) -> str: return f"{MODEL_FINGERPRINT_VERSION}:{sha256(encoded).hexdigest()}" +def identity_constants(model) -> dict[str, object]: + """Return the expected value of each readable point whose DataSchema declares ``const``. + + These are identity points, such as a meter code or a module name: a tool + compares the value it reads with the constant and reports only whether + they match. ``const`` does not contribute to point or model fingerprints. + """ + try: + _, effective = instantiate(_document(model)) + except (TypeError, RecursionError) as exc: + raise AcquisitionError(str(exc)) from exc + return { + name: prop["const"] + for name, prop in effective["properties"].items() + if "const" in prop and canonical_point(prop) is not None + } + + +def identity_result(expected, value) -> str: + """Compare a decoded value with an identity point's ``const``: ``match`` or ``mismatch``. + + Equality follows JSON Schema ``const``: numbers compare by value (137 equals + 137.0), booleans never equal numbers, and strings compare exactly. + """ + valid = Draft202012Validator({"const": expected}).is_valid(value) + return "match" if valid else "mismatch" + + def model_fingerprint(model) -> str: """Return the fingerprint of the set of readable point mappings of a model. @@ -121,7 +152,7 @@ def model_fingerprint(model) -> str: @lru_cache(maxsize=1) def _report_validators(): validators = {} - for version in (3, 4): + for version in REPORT_VERSIONS: schema = json.loads( files("modpoll_wot") .joinpath("schemas", f"verification-report-{version}.json") @@ -133,7 +164,11 @@ def _report_validators(): def validate_report(report, *, model: bytes | None = None): - """Validate a verification report (schema 3 or 4), optionally against its exact TM bytes.""" + """Validate a verification report (schema 3, 4 or 5), optionally against its exact TM bytes. + + With the model, a schema 5 report must carry ``identity`` exactly for the + successfully read points whose DataSchema declares ``const``. + """ version = report.get("reportVersion") if isinstance(report, dict) else None validator = _report_validators().get(version) if validator is None: @@ -167,3 +202,16 @@ def validate_report(report, *, model: bytes | None = None): ) if actual != point["fingerprint"]: raise ReportError(f"/points/{index}/fingerprint: does not match the model") + if report["reportVersion"] < 5: + return + constants = identity_constants(model) + for index, point in enumerate(report["points"]): + declared = point["property"] in constants + if "identity" in point and not declared: + raise ReportError( + f"/points/{index}/identity: {point['property']} declares no const" + ) + if declared and point["read"] == "ok" and "identity" not in point: + raise ReportError( + f"/points/{index}: identity is required for a read of a const point" + ) diff --git a/packages/modpoll-wot/profile.md b/packages/modpoll-wot/profile.md index 162a9c8..d05e5dd 100644 --- a/packages/modpoll-wot/profile.md +++ b/packages/modpoll-wot/profile.md @@ -218,8 +218,8 @@ requires a new prefix. ## Verification reports A verification report records one reading of a Thing Model on a physical device. Its schema is -[schemas/verification-report-4.json](modpoll_wot/schemas/verification-report-4.json) -(JSON Schema 2020-12; schema 3 remains valid). A report carries: +[schemas/verification-report-5.json](modpoll_wot/schemas/verification-report-5.json) +(JSON Schema 2020-12; schemas 3 and 4 remain valid). A report carries: - Optional `product`: the catalog product ID `/`. The receiving service resolves the product from the model fingerprint, so tools do not need to know it; @@ -236,6 +236,23 @@ A verification report records one reading of a Thing Model on a physical device. `exception` with its exception code, `no-response` or `not-tested`) and the user's judgment of the value (`confirmed`, `rejected` or `unchecked`). Only a successful read can be judged. +- `identity` on an identity point (schema 5): `match` or `mismatch`, see below. + +### Identity points + +An identity point is a readable property whose DataSchema declares `const`: the +value the document gives for this product, such as a meter code or a module +name. `identity_constants(model)` lists them. A tool compares the value it reads +with the constant on the local computer and reports only the result, so the +value itself still never leaves the computer. `identity_result(const, value)` +applies JSON Schema `const` equality: numbers compare by value (`137` equals +`137.0`), booleans never equal numbers, and strings compare exactly, so a value +with a multiplier or a float raw type should not be an identity point. +In a schema 5 report every successfully read identity point carries `identity`, +and no other point does; a failed read carries none. A report with a `mismatch` +was read on different hardware, so receiving services do not count it. +`const` does not contribute to point or model fingerprints: marking an identity +point later keeps every fingerprint and every earlier report valid. A report is a full read when its points cover every readable property of the model and every read is `ok`, so that executing the whole @@ -250,7 +267,8 @@ markers and account data belong to the receiving service, not the report. `validate_report(report, model=tm_bytes)` and `modpoll-wot validate-report REPORT [--model TM]` check the schema and unique properties. With the model, they also check its hash and model fingerprint, and that -every point names a readable property with a matching fingerprint. +every point names a readable property with a matching fingerprint, and for +schema 5 that `identity` appears exactly on the successfully read identity points. ## Tool sessions and Workspace references diff --git a/packages/modpoll-wot/tests/test_verification.py b/packages/modpoll-wot/tests/test_verification.py index 5437a20..0cc3070 100644 --- a/packages/modpoll-wot/tests/test_verification.py +++ b/packages/modpoll-wot/tests/test_verification.py @@ -10,8 +10,11 @@ import pytest from modpoll_wot import ( + REPORT_VERSION, ReportError, export_td, + identity_constants, + identity_result, model_fingerprint, point_fingerprints, validate_report, @@ -43,8 +46,7 @@ def test_shared_vectors_pin_the_canonical_encoding(vector_file): assert canonical == expected["canonical"] assert fingerprint(point) == expected["fingerprint"] assert ( - expected["fingerprint"] - == "pf1:" + sha256(canonical.encode()).hexdigest() + expected["fingerprint"] == "pf1:" + sha256(canonical.encode()).hexdigest() ) payload = (FIXTURES / vectors["model"]).read_bytes() assert vectors["points"].keys() == point_fingerprints(payload).keys() @@ -92,7 +94,9 @@ def test_mapping_changes_split_fingerprints(field, value): source["properties"]["signed"]["forms"][0][field] = value if field == "modv:type": source["properties"]["signed"]["minimum"] = 0 - assert point_fingerprints(source)["signed"] != point_fingerprints(numeric())["signed"] + assert ( + point_fingerprints(source)["signed"] != point_fingerprints(numeric())["signed"] + ) assert model_fingerprint(source) != model_fingerprint(numeric()) @@ -285,7 +289,7 @@ def test_version_3_reports_with_product_still_validate(): def test_unknown_report_version_is_rejected(): report = report_for(NUMERIC.read_bytes()) - report["reportVersion"] = 5 + report["reportVersion"] = 6 with pytest.raises(ReportError, match="unsupported report version"): validate_report(report) @@ -316,3 +320,89 @@ def test_the_public_interface_is_the_package_top_level(): for name in ("MAX_BYTES", "load_document", "type_width"): assert name in modpoll_wot.__all__ assert (Path(modpoll_wot.__file__).parent / "py.typed").is_file() + + +# VER-01: identity points declare their documented value with const; the report records whether it matched. +def identity_model(): + source = numeric() + source["properties"]["counter"]["const"] = 7 + return json.dumps(source).encode() + + +def identity_report(payload, **counter): + report = report_for(payload) + report["reportVersion"] = 5 + report["points"][0].update(counter) + return report + + +def test_const_marks_identity_points_without_changing_fingerprints(): + payload = identity_model() + assert identity_constants(payload) == {"counter": 7} + assert identity_constants(NUMERIC.read_bytes()) == {} + assert point_fingerprints(payload) == point_fingerprints(NUMERIC.read_bytes()) + assert model_fingerprint(payload) == model_fingerprint(NUMERIC.read_bytes()) + + +def test_write_only_points_are_not_identity_points(): + source = numeric() + prop = source["properties"]["counter"] + prop.pop("readOnly") + prop["writeOnly"] = True + prop["forms"][0]["op"] = "writeproperty" + prop["const"] = 7 + assert identity_constants(source) == {} + + +@pytest.mark.parametrize( + ("expected", "value", "result"), + [ + (137, 137, "match"), + (137, 137.0, "match"), + (137, 132, "mismatch"), + (1, True, "mismatch"), + (True, True, "match"), + ("ADAM-5017UH", "ADAM-5017UH", "match"), + ("ADAM-5017UH", "ADAM-5017UH ", "mismatch"), + (137, None, "mismatch"), + ], +) +def test_identity_result_follows_json_schema_const(expected, value, result): + assert identity_result(expected, value) == result + + +def test_a_version_5_report_carries_identity_for_read_const_points(): + payload = identity_model() + assert REPORT_VERSION == 5 + for identity in ("match", "mismatch"): + validate_report(identity_report(payload, identity=identity), model=payload) + + with pytest.raises(ReportError, match="identity is required"): + validate_report(identity_report(payload), model=payload) + with pytest.raises(ReportError, match="counter declares no const"): + validate_report( + identity_report(NUMERIC.read_bytes(), identity="match"), + model=NUMERIC.read_bytes(), + ) + + +def test_identity_is_only_a_result_of_a_successful_read(): + payload = identity_model() + failed = identity_report( + payload, read="no-response", expected="unchecked", identity="match" + ) + with pytest.raises(ReportError): + validate_report(failed) + del failed["points"][0]["identity"] + validate_report(failed, model=payload) + with pytest.raises(ReportError): + validate_report(identity_report(payload, identity="unknown")) + + +def test_identity_needs_report_version_5(): + report = report_for(identity_model()) + report["points"][0]["identity"] = "match" + with pytest.raises(ReportError, match="Additional properties"): + validate_report(report) + del report["points"][0]["identity"] + validate_report(report, model=identity_model())