diff --git a/docs/GAMEPLAY_EVIDENCE.md b/docs/GAMEPLAY_EVIDENCE.md new file mode 100644 index 0000000..c8de20e --- /dev/null +++ b/docs/GAMEPLAY_EVIDENCE.md @@ -0,0 +1,34 @@ +# Gameplay Evidence Exchange v0.1 + +`mcproof.gameplay_evidence` implements the closed interchange envelope in [`schema/gameplay-evidence-v0.1.schema.json`](../schema/gameplay-evidence-v0.1.schema.json). It uses only the Python standard library. + +```python +from mcproof.gameplay_evidence import load_gameplay_artifact, verify_gameplay_artifact + +artifact = load_gameplay_artifact(received_text) # rejects duplicate JSON keys +report = verify_gameplay_artifact(artifact) +if not report["valid"]: + raise ValueError(report["errors"]) +print(report["source_badges"]) +print(report["admitted_badges"]) +``` + +`canonical_json_bytes` emits sorted, compact, ASCII-escaped UTF-8 JSON. `sha256_json` hashes those bytes. + +The verifier recomputes the artifact self-digest, exact source UTF-8 digest, four payload commitments, and three payload commitments on every check. It rejects unknown or missing envelope keys, duplicate keys during loading, every floating-point value, integers outside signed 64 bits, non-string object keys, malformed or all-zero SHA-256 fields, and non-boolean negative-control results. + +## Badge boundary + +`source_badges` summarizes the producer's checks. Higher source badges require the explicit passing checks and a passing negative control stated in the contract. `LIVE_CONFIRMED` also needs passing model replay or model proof over the same payload commitments. `MODEL_PROVEN` and `LIVE_CONFIRMED` remain independent. Any recorded `FAIL` is an unresolved aggregation veto, so a second `PASS` cannot hide it. Missing checks or negative controls do not promote an artifact. + +`admitted_badges` contains only `OBSERVED`: this dependency-free module validates structure and commitments but does not independently rerun domain checks. Higher admissions belong to a trusted domain verifier bound to the exact artifact, check, and negative-control digests. `derive_evidence_badges` returns only the admitted list. + +`source_labels` is preserved as source data and ignored by source badge derivation. In particular, `VERIFIED`, `MODEL_PROVEN`, or `LIVE_CONFIRMED` supplied as labels cannot promote evidence. Invalid artifacts always return empty source and admitted lists. + +## What validation does not establish + +A `valid` report establishes structural and digest consistency only. It does **not** parse or execute `source.raw`, rerun replay/proof/live checkers, validate SimGrammar YAML, establish that negative-control prose genuinely documents rejection, or resolve domain semantics. + +A trusted domain adapter must do those checks separately. Source check records, checker pins, controls, limitations, and labels remain claims bound by the envelope, not independently reproduced findings. + +The JSON Schema closes the envelope and expresses field types, formats, and recursive JSON-safe values where practical. JSON Schema alone cannot reject duplicate input keys, compare digests, hash exact source bytes, derive badges, or consistently distinguish lexical floats such as `1.0` from integers across implementations. The runtime verifier rejects every float and is authoritative for those rules. diff --git a/schema/gameplay-evidence-v0.1.schema.json b/schema/gameplay-evidence-v0.1.schema.json new file mode 100644 index 0000000..8919b23 --- /dev/null +++ b/schema/gameplay-evidence-v0.1.schema.json @@ -0,0 +1,219 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://proven-commons.github.io/mcproof/schema/gameplay-evidence-v0.1.schema.json", + "title": "Gameplay Evidence Exchange v0.1", + "description": "Closed evidence envelope. Digest equality, duplicate-key rejection, exact source UTF-8 hashing, and badge derivation require the runtime validator.", + "type": "object", + "required": [ + "schema", + "artifact_sha256", + "producer", + "claim", + "mechanics", + "payload", + "evidence", + "source" + ], + "additionalProperties": false, + "properties": { + "schema": {"const": "gameplay-evidence/v0.1"}, + "artifact_sha256": {"$ref": "#/definitions/sha256"}, + "producer": { + "type": "object", + "required": ["repository", "revision", "adapter"], + "additionalProperties": false, + "properties": { + "repository": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$" + }, + "revision": {"$ref": "#/definitions/commit"}, + "adapter": {"$ref": "#/definitions/nonemptyText"} + } + }, + "claim": { + "type": "object", + "required": ["id", "kind", "statement"], + "additionalProperties": false, + "properties": { + "id": {"$ref": "#/definitions/identifier"}, + "kind": { + "type": "string", + "enum": ["route", "state_transition", "goal", "counterexample", "observation"] + }, + "statement": {"$ref": "#/definitions/nonemptyText"} + } + }, + "mechanics": { + "type": "array", + "items": {"$ref": "#/definitions/mechanic"} + }, + "payload": { + "type": "object", + "required": [ + "domain", + "model", + "model_sha256", + "initial_state", + "initial_state_sha256", + "actions", + "actions_sha256", + "trajectory", + "trajectory_sha256", + "outcome" + ], + "additionalProperties": false, + "properties": { + "domain": {"$ref": "#/definitions/identifier"}, + "model": {"$ref": "#/definitions/jsonValue"}, + "model_sha256": {"$ref": "#/definitions/sha256"}, + "initial_state": {"$ref": "#/definitions/jsonValue"}, + "initial_state_sha256": {"$ref": "#/definitions/sha256"}, + "actions": { + "type": "array", + "items": {"$ref": "#/definitions/jsonValue"} + }, + "actions_sha256": {"$ref": "#/definitions/sha256"}, + "trajectory": { + "type": "array", + "items": {"$ref": "#/definitions/jsonValue"} + }, + "trajectory_sha256": {"$ref": "#/definitions/sha256"}, + "outcome": { + "type": "object", + "additionalProperties": {"$ref": "#/definitions/jsonValue"} + } + } + }, + "evidence": { + "type": "object", + "required": ["checks", "negative_controls", "limitations"], + "additionalProperties": false, + "properties": { + "checks": { + "type": "array", + "items": {"$ref": "#/definitions/check"} + }, + "negative_controls": { + "type": "array", + "items": {"$ref": "#/definitions/negativeControl"} + }, + "limitations": { + "type": "array", + "minItems": 1, + "items": {"$ref": "#/definitions/nonemptyText"} + } + } + }, + "source": { + "type": "object", + "required": ["media_type", "raw_sha256", "raw"], + "additionalProperties": false, + "properties": { + "media_type": {"$ref": "#/definitions/nonemptyText"}, + "raw_sha256": {"$ref": "#/definitions/sha256"}, + "raw": {"type": "string"} + } + } + }, + "definitions": { + "sha256": { + "type": "string", + "pattern": "^(?!0{64}$)[0-9a-f]{64}$" + }, + "commit": { + "type": "string", + "pattern": "^[0-9a-f]{40}$" + }, + "identifier": { + "type": "string", + "pattern": "^[A-Za-z0-9_.:-]+$" + }, + "nonemptyText": { + "type": "string", + "pattern": "\\S" + }, + "jsonValue": { + "anyOf": [ + {"type": "null"}, + {"type": "boolean"}, + {"type": "string"}, + { + "type": "integer", + "minimum": -9223372036854775808, + "maximum": 9223372036854775807 + }, + { + "type": "array", + "items": {"$ref": "#/definitions/jsonValue"} + }, + { + "type": "object", + "additionalProperties": {"$ref": "#/definitions/jsonValue"} + } + ] + }, + "mechanic": { + "type": "object", + "required": ["id", "path", "source_revision", "raw_sha256"], + "additionalProperties": false, + "properties": { + "id": {"$ref": "#/definitions/identifier"}, + "path": { + "type": "string", + "pattern": "^(?!/)(?!.*//)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*\\\\)[^\\x00]+\\.(?:[yY][aA][mM][lL]|[yY][mM][lL])$" + }, + "source_revision": {"$ref": "#/definitions/commit"}, + "raw_sha256": {"$ref": "#/definitions/sha256"} + } + }, + "check": { + "type": "object", + "required": [ + "kind", + "status", + "checker", + "source_labels", + "initial_state_sha256", + "actions_sha256", + "trajectory_sha256" + ], + "additionalProperties": false, + "properties": { + "kind": { + "type": "string", + "enum": ["model_replay", "model_proof", "live_execution"] + }, + "status": {"type": "string", "enum": ["PASS", "FAIL"]}, + "checker": { + "type": "object", + "required": ["name", "revision", "artifact_sha256"], + "additionalProperties": false, + "properties": { + "name": {"$ref": "#/definitions/nonemptyText"}, + "revision": {"$ref": "#/definitions/nonemptyText"}, + "artifact_sha256": {"$ref": "#/definitions/sha256"} + } + }, + "source_labels": { + "type": "array", + "items": {"$ref": "#/definitions/nonemptyText"} + }, + "initial_state_sha256": {"$ref": "#/definitions/sha256"}, + "actions_sha256": {"$ref": "#/definitions/sha256"}, + "trajectory_sha256": {"$ref": "#/definitions/sha256"} + } + }, + "negativeControl": { + "type": "object", + "required": ["name", "mutation", "observed", "passed"], + "additionalProperties": false, + "properties": { + "name": {"$ref": "#/definitions/nonemptyText"}, + "mutation": {"$ref": "#/definitions/nonemptyText"}, + "observed": {"$ref": "#/definitions/nonemptyText"}, + "passed": {"type": "boolean"} + } + } + } +} diff --git a/src/mcproof/gameplay_evidence.py b/src/mcproof/gameplay_evidence.py new file mode 100644 index 0000000..7792bba --- /dev/null +++ b/src/mcproof/gameplay_evidence.py @@ -0,0 +1,436 @@ +"""Strict, dependency-free Gameplay Evidence Exchange v0.1 validation. + +Validation establishes only envelope structure and digest consistency. It does +not parse ``source.raw`` or rerun any checker named by the artifact. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from typing import Any + +SCHEMA_ID = "gameplay-evidence/v0.1" +INT64_MIN = -(2**63) +INT64_MAX = 2**63 - 1 +ZERO_SHA256 = "0" * 64 + +TOP_LEVEL_KEYS = frozenset( + {"schema", "artifact_sha256", "producer", "claim", "mechanics", "payload", "evidence", "source"} +) +PRODUCER_KEYS = frozenset({"repository", "revision", "adapter"}) +CLAIM_KEYS = frozenset({"id", "kind", "statement"}) +MECHANIC_KEYS = frozenset({"id", "path", "source_revision", "raw_sha256"}) +PAYLOAD_KEYS = frozenset( + { + "domain", + "model", + "model_sha256", + "initial_state", + "initial_state_sha256", + "actions", + "actions_sha256", + "trajectory", + "trajectory_sha256", + "outcome", + } +) +EVIDENCE_KEYS = frozenset({"checks", "negative_controls", "limitations"}) +CHECK_KEYS = frozenset( + { + "kind", + "status", + "checker", + "source_labels", + "initial_state_sha256", + "actions_sha256", + "trajectory_sha256", + } +) +CHECKER_KEYS = frozenset({"name", "revision", "artifact_sha256"}) +NEGATIVE_CONTROL_KEYS = frozenset({"name", "mutation", "observed", "passed"}) +SOURCE_KEYS = frozenset({"media_type", "raw_sha256", "raw"}) + +SHA256_RE = re.compile(r"[0-9a-f]{64}") +COMMIT_RE = re.compile(r"[0-9a-f]{40}") +IDENTIFIER_RE = re.compile(r"[A-Za-z0-9_.:-]+") +REPOSITORY_RE = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") +CLAIM_KINDS = frozenset({"route", "state_transition", "goal", "counterexample", "observation"}) +CHECK_KINDS = frozenset({"model_replay", "model_proof", "live_execution"}) +BADGE_ORDER = ("OBSERVED", "REPLAYED", "MODEL_PROVEN", "LIVE_CONFIRMED") + + +def _validate_canonical_value(value: Any, path: str, active: set[int]) -> None: + """Reject values whose JSON encoding would be lossy or outside the contract.""" + if value is None or isinstance(value, (str, bool)): + return + if isinstance(value, int): + if not INT64_MIN <= value <= INT64_MAX: + raise ValueError(f"{path}: integer outside signed 64-bit range") + return + if isinstance(value, float): + raise ValueError(f"{path}: floating-point values are not canonical JSON") + if isinstance(value, (dict, list)): + identity = id(value) + if identity in active: + raise ValueError(f"{path}: cyclic value is not JSON") + active.add(identity) + try: + if isinstance(value, dict): + for key, child in value.items(): + if not isinstance(key, str): + raise TypeError(f"{path}: JSON object keys must be strings") + _validate_canonical_value(child, f"{path}.{key}", active) + else: + for index, child in enumerate(value): + _validate_canonical_value(child, f"{path}[{index}]", active) + finally: + active.remove(identity) + return + raise TypeError(f"{path}: unsupported JSON value type {type(value).__name__}") + + +def canonical_json_bytes(value: Any) -> bytes: + """Return the contract's canonical UTF-8 JSON representation. + + Object keys must be strings and integers must fit in signed 64 bits. Every + floating-point value is rejected, including finite integer-valued floats. + """ + _validate_canonical_value(value, "$", set()) + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8") + + +def sha256_json(value: Any) -> str: + """Hash the canonical JSON bytes of *value* with SHA-256.""" + return hashlib.sha256(canonical_json_bytes(value)).hexdigest() + + +def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate JSON object key: {key!r}") + result[key] = value + return result + + +def _reject_json_constant(token: str) -> None: + raise ValueError(f"non-finite JSON number is forbidden: {token}") + + +def load_gameplay_artifact(text: str) -> Any: + """Parse JSON while rejecting duplicate keys and non-finite numbers. + + This function deliberately does not parse the nested ``source.raw`` string. + Call :func:`verify_gameplay_artifact` on the returned value before using it. + """ + if not isinstance(text, str): + raise TypeError("gameplay artifact input must be text") + return json.loads( + text, + object_pairs_hook=_reject_duplicate_keys, + parse_constant=_reject_json_constant, + ) + + +def _error(errors: list[str], path: str, message: str) -> None: + errors.append(f"{path}: {message}") + + +def _exact_keys(value: Any, expected: frozenset[str], path: str, errors: list[str]) -> bool: + if not isinstance(value, dict): + _error(errors, path, "must be an object") + return False + missing = sorted(expected - value.keys()) + unknown = sorted(value.keys() - expected, key=repr) + if missing: + _error(errors, path, f"missing keys: {', '.join(missing)}") + if unknown: + rendered = ", ".join(key if isinstance(key, str) else repr(key) for key in unknown) + _error(errors, path, f"unknown keys: {rendered}") + return not missing and not unknown + + +def _nonempty_text(value: Any, path: str, errors: list[str]) -> bool: + if not isinstance(value, str) or not value.strip(): + _error(errors, path, "must be nonempty text") + return False + return True + + +def _identifier(value: Any, path: str, errors: list[str]) -> bool: + if not isinstance(value, str) or IDENTIFIER_RE.fullmatch(value) is None: + _error(errors, path, "must be a nonempty ASCII identifier") + return False + return True + + +def _digest(value: Any, path: str, errors: list[str]) -> bool: + if not isinstance(value, str) or SHA256_RE.fullmatch(value) is None: + _error(errors, path, "must be 64 lowercase hexadecimal characters") + return False + if value == ZERO_SHA256: + _error(errors, path, "all-zero SHA-256 is forbidden") + return False + return True + + +def _commit(value: Any, path: str, errors: list[str]) -> bool: + if not isinstance(value, str) or COMMIT_RE.fullmatch(value) is None: + _error(errors, path, "must be a 40-character lowercase hexadecimal commit") + return False + return True + + +def _yaml_path(value: Any, path: str, errors: list[str]) -> bool: + if not isinstance(value, str) or not value: + _error(errors, path, "must be a nonempty repository-relative YAML path") + return False + segments = value.split("/") + if ( + value.startswith(("/", "\\")) + or "\\" in value + or "\x00" in value + or any(segment in {"", ".", ".."} for segment in segments) + or segments[-1].lower().endswith((".yaml", ".yml")) is False + ): + _error(errors, path, "must be a nonempty repository-relative YAML path without traversal") + return False + return True + + +def _strict_json_tree(value: Any, path: str, errors: list[str], active: set[int]) -> None: + """Validate JSON-safe artifact data, rejecting every float and unsafe int.""" + if value is None or isinstance(value, (str, bool)): + return + if isinstance(value, int): + if not INT64_MIN <= value <= INT64_MAX: + _error(errors, path, "integer outside signed 64-bit range") + return + if isinstance(value, float): + _error(errors, path, "floats are forbidden in gameplay artifacts") + return + if isinstance(value, (dict, list)): + identity = id(value) + if identity in active: + _error(errors, path, "cyclic values are forbidden") + return + active.add(identity) + try: + if isinstance(value, dict): + for key, child in value.items(): + if not isinstance(key, str): + _error(errors, path, "object keys must be strings") + continue + _strict_json_tree(child, f"{path}.{key}", errors, active) + else: + for index, child in enumerate(value): + _strict_json_tree(child, f"{path}[{index}]", errors, active) + finally: + active.remove(identity) + return + _error(errors, path, f"unsupported JSON value type {type(value).__name__}") + + +def _validate_structure(value: Any, errors: list[str]) -> None: + if not _exact_keys(value, TOP_LEVEL_KEYS, "$", errors): + if not isinstance(value, dict): + return + _strict_json_tree(value, "$", errors, set()) + + if value.get("schema") != SCHEMA_ID: + _error(errors, "$.schema", f"must be the literal {SCHEMA_ID!r}") + _digest(value.get("artifact_sha256"), "$.artifact_sha256", errors) + + producer = value.get("producer") + if _exact_keys(producer, PRODUCER_KEYS, "$.producer", errors): + repository = producer["repository"] + if not isinstance(repository, str) or REPOSITORY_RE.fullmatch(repository) is None: + _error(errors, "$.producer.repository", "must have owner/repository form") + _commit(producer["revision"], "$.producer.revision", errors) + _nonempty_text(producer["adapter"], "$.producer.adapter", errors) + + claim = value.get("claim") + if _exact_keys(claim, CLAIM_KEYS, "$.claim", errors): + _identifier(claim["id"], "$.claim.id", errors) + if not isinstance(claim["kind"], str) or claim["kind"] not in CLAIM_KINDS: + _error(errors, "$.claim.kind", "unknown claim kind") + _nonempty_text(claim["statement"], "$.claim.statement", errors) + + mechanics = value.get("mechanics") + if not isinstance(mechanics, list): + _error(errors, "$.mechanics", "must be an array") + else: + for index, mechanic in enumerate(mechanics): + path = f"$.mechanics[{index}]" + if _exact_keys(mechanic, MECHANIC_KEYS, path, errors): + _identifier(mechanic["id"], f"{path}.id", errors) + _yaml_path(mechanic["path"], f"{path}.path", errors) + _commit(mechanic["source_revision"], f"{path}.source_revision", errors) + _digest(mechanic["raw_sha256"], f"{path}.raw_sha256", errors) + + payload = value.get("payload") + if _exact_keys(payload, PAYLOAD_KEYS, "$.payload", errors): + _identifier(payload["domain"], "$.payload.domain", errors) + for name in ("model", "initial_state", "actions", "trajectory"): + _digest(payload[f"{name}_sha256"], f"$.payload.{name}_sha256", errors) + if not isinstance(payload["actions"], list): + _error(errors, "$.payload.actions", "must be an array") + if not isinstance(payload["trajectory"], list): + _error(errors, "$.payload.trajectory", "must be an array") + if not isinstance(payload["outcome"], dict): + _error(errors, "$.payload.outcome", "must be an object") + + evidence = value.get("evidence") + if _exact_keys(evidence, EVIDENCE_KEYS, "$.evidence", errors): + checks = evidence["checks"] + if not isinstance(checks, list): + _error(errors, "$.evidence.checks", "must be an array") + else: + for index, check in enumerate(checks): + path = f"$.evidence.checks[{index}]" + if not _exact_keys(check, CHECK_KEYS, path, errors): + continue + if not isinstance(check["kind"], str) or check["kind"] not in CHECK_KINDS: + _error(errors, f"{path}.kind", "unknown check kind") + if not isinstance(check["status"], str) or check["status"] not in {"PASS", "FAIL"}: + _error(errors, f"{path}.status", "must be PASS or FAIL") + checker = check["checker"] + if _exact_keys(checker, CHECKER_KEYS, f"{path}.checker", errors): + _nonempty_text(checker["name"], f"{path}.checker.name", errors) + _nonempty_text(checker["revision"], f"{path}.checker.revision", errors) + _digest(checker["artifact_sha256"], f"{path}.checker.artifact_sha256", errors) + labels = check["source_labels"] + if not isinstance(labels, list): + _error(errors, f"{path}.source_labels", "must be an array") + else: + for label_index, label in enumerate(labels): + _nonempty_text(label, f"{path}.source_labels[{label_index}]", errors) + for name in ("initial_state", "actions", "trajectory"): + _digest(check[f"{name}_sha256"], f"{path}.{name}_sha256", errors) + + controls = evidence["negative_controls"] + if not isinstance(controls, list): + _error(errors, "$.evidence.negative_controls", "must be an array") + else: + for index, control in enumerate(controls): + path = f"$.evidence.negative_controls[{index}]" + if _exact_keys(control, NEGATIVE_CONTROL_KEYS, path, errors): + for name in ("name", "mutation", "observed"): + _nonempty_text(control[name], f"{path}.{name}", errors) + if not isinstance(control["passed"], bool): + _error(errors, f"{path}.passed", "must be a real boolean") + + limitations = evidence["limitations"] + if not isinstance(limitations, list) or not limitations: + _error(errors, "$.evidence.limitations", "must be a nonempty array") + else: + for index, limitation in enumerate(limitations): + _nonempty_text(limitation, f"$.evidence.limitations[{index}]", errors) + + source = value.get("source") + if _exact_keys(source, SOURCE_KEYS, "$.source", errors): + _nonempty_text(source["media_type"], "$.source.media_type", errors) + _digest(source["raw_sha256"], "$.source.raw_sha256", errors) + if not isinstance(source["raw"], str): + _error(errors, "$.source.raw", "must be a string containing exact source text") + + +def _compare_digest(actual: str, expected: str, path: str, errors: list[str]) -> None: + if actual != expected: + _error(errors, path, f"digest mismatch: recorded {actual}, computed {expected}") + + +def _validate_commitments(value: dict[str, Any], errors: list[str]) -> None: + payload = value["payload"] + for name in ("model", "initial_state", "actions", "trajectory"): + _compare_digest( + payload[f"{name}_sha256"], + sha256_json(payload[name]), + f"$.payload.{name}_sha256", + errors, + ) + + for index, check in enumerate(value["evidence"]["checks"]): + for name in ("initial_state", "actions", "trajectory"): + _compare_digest( + check[f"{name}_sha256"], + payload[f"{name}_sha256"], + f"$.evidence.checks[{index}].{name}_sha256", + errors, + ) + + source = value["source"] + try: + raw_bytes = source["raw"].encode("utf-8") + except UnicodeEncodeError: + _error(errors, "$.source.raw", "must be encodable as exact UTF-8 bytes") + else: + _compare_digest( + source["raw_sha256"], + hashlib.sha256(raw_bytes).hexdigest(), + "$.source.raw_sha256", + errors, + ) + + unsigned = {key: child for key, child in value.items() if key != "artifact_sha256"} + _compare_digest( + value["artifact_sha256"], + sha256_json(unsigned), + "$.artifact_sha256", + errors, + ) + + +def _derive_source_badges(value: dict[str, Any]) -> list[str]: + """Summarize source assertions; any source FAIL is an unresolved veto.""" + badges = ["OBSERVED"] + checks = value["evidence"]["checks"] + if any(check["status"] == "FAIL" for check in checks): + return badges + if not any(control["passed"] for control in value["evidence"]["negative_controls"]): + return badges + + passing_kinds = {check["kind"] for check in checks if check["status"] == "PASS"} + if "model_replay" in passing_kinds: + badges.append("REPLAYED") + if "model_proof" in passing_kinds: + badges.append("MODEL_PROVEN") + if "live_execution" in passing_kinds and passing_kinds.intersection({"model_replay", "model_proof"}): + # Structural validation already required all three check commitments to + # equal the same payload commitments for every check. + badges.append("LIVE_CONFIRMED") + return [badge for badge in BADGE_ORDER if badge in badges] + + +def verify_gameplay_artifact(value: Any) -> dict[str, Any]: + """Return source assertions separately from this consumer's admissions. + + ``valid=True`` never means a source check was independently rerun. Structural + validation admits only ``OBSERVED``. Higher source badges remain assertions + until a domain-specific consumer independently verifies the exact artifact. + Invalid input has empty source and admitted badge lists. + """ + errors: list[str] = [] + _validate_structure(value, errors) + if not errors: + _validate_commitments(value, errors) + source_badges = _derive_source_badges(value) if not errors else [] + admitted_badges = ["OBSERVED"] if not errors else [] + return { + "valid": not errors, + "errors": errors, + "source_badges": source_badges, + "admitted_badges": admitted_badges, + } + + +def derive_evidence_badges(value: Any) -> list[str]: + """Return badges admitted by structural validation, or ``[]`` if invalid. + + This dependency-free validator does not rerun domain checks, so the only + possible admission is ``OBSERVED``. Source-asserted badges are available in + ``verify_gameplay_artifact(value)["source_badges"]``. + """ + return verify_gameplay_artifact(value)["admitted_badges"] diff --git a/tests/test_gameplay_evidence.py b/tests/test_gameplay_evidence.py new file mode 100644 index 0000000..d5af747 --- /dev/null +++ b/tests/test_gameplay_evidence.py @@ -0,0 +1,478 @@ +"""Adversarial unit tests for Gameplay Evidence Exchange v0.1.""" + +from __future__ import annotations + +import copy +import hashlib +import json +from pathlib import Path +import unittest + +from mcproof.gameplay_evidence import ( + INT64_MAX, + INT64_MIN, + canonical_json_bytes, + derive_evidence_badges, + load_gameplay_artifact, + sha256_json, + verify_gameplay_artifact, +) + + +def _check(kind: str, payload: dict, status: str = "PASS", labels: list[str] | None = None) -> dict: + return { + "kind": kind, + "status": status, + "checker": { + "name": f"{kind}-checker", + "revision": "c" * 40, + "artifact_sha256": sha256_json({"checker": kind, "revision": "c" * 40}), + }, + "source_labels": list(labels if labels is not None else ["VERIFIED", f"SOURCE_{kind}"]), + "initial_state_sha256": payload["initial_state_sha256"], + "actions_sha256": payload["actions_sha256"], + "trajectory_sha256": payload["trajectory_sha256"], + } + + +def _control(passed: bool = True) -> dict: + return { + "name": "drop-final-state", + "mutation": "Remove the final trajectory state", + "observed": "rejected: trajectory commitment mismatch", + "passed": passed, + } + + +def valid_artifact() -> dict: + """Build a deterministic observation with one replay and one control.""" + model = {"rules": "east increments position", "assumptions": ["deterministic"]} + initial_state = {"position": 0} + actions = ["east"] + trajectory = [{"position": 0}, {"position": 1}] + payload = { + "domain": "toy-grid", + "model": model, + "model_sha256": sha256_json(model), + "initial_state": initial_state, + "initial_state_sha256": sha256_json(initial_state), + "actions": actions, + "actions_sha256": sha256_json(actions), + "trajectory": trajectory, + "trajectory_sha256": sha256_json(trajectory), + "outcome": {"goal_reached": True}, + } + raw = '{\n "source_schema": "observation/v7",\n "label": "VERIFIED",\n "tick": 1\n}\n' + artifact = { + "schema": "gameplay-evidence/v0.1", + "producer": { + "repository": "Proven-Commons/mcproof", + "revision": "a" * 40, + "adapter": "mcproof.gameplay_evidence", + }, + "claim": { + "id": "route-1", + "kind": "route", + "statement": "Moving east reaches position one.", + }, + "mechanics": [ + { + "id": "grid-mechanics", + "path": "mechanics/grid.yaml", + "source_revision": "b" * 40, + "raw_sha256": hashlib.sha256(b"position: integer\n").hexdigest(), + } + ], + "payload": payload, + "evidence": { + "checks": [_check("model_replay", payload)], + "negative_controls": [_control()], + "limitations": ["The consumer has not independently rerun the source replay."], + }, + "source": { + "media_type": "application/json", + "raw_sha256": hashlib.sha256(raw.encode("utf-8")).hexdigest(), + "raw": raw, + }, + } + reseal(artifact) + return artifact + + +def reseal(artifact: dict) -> None: + artifact.pop("artifact_sha256", None) + artifact["artifact_sha256"] = sha256_json(artifact) + + +def node(artifact: dict, path: tuple[object, ...]): + current = artifact + for component in path: + current = current[component] + return current + + +class CanonicalJSONTests(unittest.TestCase): + def test_canonical_bytes_and_digest_are_deterministic(self) -> None: + value = {"b": [1, True, None], "a": "é"} + expected = b'{"a":"\\u00e9","b":[1,true,null]}' + self.assertEqual(canonical_json_bytes(value), expected) + self.assertEqual(sha256_json(value), hashlib.sha256(expected).hexdigest()) + self.assertEqual(canonical_json_bytes(value), canonical_json_bytes(copy.deepcopy(value))) + + def test_canonical_rejects_non_string_keys_cycles_and_unsupported_types(self) -> None: + with self.assertRaises(TypeError): + canonical_json_bytes({1: "not a string key"}) + with self.assertRaises(TypeError): + canonical_json_bytes((1, 2)) + cyclic: list = [] + cyclic.append(cyclic) + with self.assertRaises(ValueError): + canonical_json_bytes(cyclic) + + def test_canonical_rejects_every_float(self) -> None: + for value in (1.0, 1.5, float("nan"), float("inf"), float("-inf")): + with self.subTest(value=value), self.assertRaises(ValueError): + canonical_json_bytes(value) + + def test_canonical_enforces_signed_64_bit_boundaries(self) -> None: + self.assertEqual(canonical_json_bytes(INT64_MIN), str(INT64_MIN).encode()) + self.assertEqual(canonical_json_bytes(INT64_MAX), str(INT64_MAX).encode()) + for value in (INT64_MIN - 1, INT64_MAX + 1, float(INT64_MAX + 1)): + with self.subTest(value=value), self.assertRaises(ValueError): + canonical_json_bytes(value) + + +class StrictLoadingTests(unittest.TestCase): + def test_valid_round_trip_and_json_safe_report(self) -> None: + artifact = valid_artifact() + loaded = load_gameplay_artifact(canonical_json_bytes(artifact).decode("utf-8")) + report = verify_gameplay_artifact(loaded) + self.assertEqual( + report, + { + "valid": True, + "errors": [], + "source_badges": ["OBSERVED", "REPLAYED"], + "admitted_badges": ["OBSERVED"], + }, + ) + json.dumps(report, allow_nan=False) + + def test_duplicate_keys_are_rejected_at_every_depth(self) -> None: + samples = ( + '{"schema":"gameplay-evidence/v0.1","schema":"gameplay-evidence/v0.1"}', + '{"producer":{"repository":"o/r","repository":"x/y"}}', + '{"payload":{"outcome":{"x":1,"x":2}}}', + ) + for text in samples: + with self.subTest(text=text), self.assertRaisesRegex(ValueError, "duplicate"): + load_gameplay_artifact(text) + + def test_non_finite_json_constants_and_non_text_input_are_rejected(self) -> None: + for token in ("NaN", "Infinity", "-Infinity"): + with self.subTest(token=token), self.assertRaises(ValueError): + load_gameplay_artifact('{"x":' + token + "}") + with self.assertRaises(TypeError): + load_gameplay_artifact(b"{}") + + def test_loader_does_not_parse_raw_source(self) -> None: + artifact = valid_artifact() + # Duplicate keys and even malformed source documents remain opaque raw + # evidence during canonical envelope validation. + for raw in ('{"x":1,"x":1}', "not JSON at all"): + with self.subTest(raw=raw): + candidate = copy.deepcopy(artifact) + candidate["source"]["raw"] = raw + candidate["source"]["raw_sha256"] = hashlib.sha256(raw.encode()).hexdigest() + reseal(candidate) + self.assertTrue(verify_gameplay_artifact(candidate)["valid"]) + + +class ArtifactReportAssertions: + def assertInvalid(self, artifact, contains: str | None = None) -> dict: + report = verify_gameplay_artifact(artifact) + self.assertFalse(report["valid"], report) + self.assertEqual(report["source_badges"], []) + self.assertEqual(report["admitted_badges"], []) + self.assertTrue(report["errors"]) + if contains is not None: + self.assertIn(contains, "\n".join(report["errors"])) + json.dumps(report, allow_nan=False) + return report + + +class StructuralValidationTests(ArtifactReportAssertions, unittest.TestCase): + def test_non_object_and_wrong_schema_are_invalid(self) -> None: + for value in (None, [], "artifact", 1, True): + with self.subTest(value=value): + self.assertInvalid(value) + artifact = valid_artifact() + artifact["schema"] = "gameplay-evidence/v0.2" + self.assertInvalid(artifact, "schema") + + def test_every_closed_object_rejects_unknown_keys(self) -> None: + paths = ( + (), + ("producer",), + ("claim",), + ("mechanics", 0), + ("payload",), + ("evidence",), + ("evidence", "checks", 0), + ("evidence", "checks", 0, "checker"), + ("evidence", "negative_controls", 0), + ("source",), + ) + for path in paths: + with self.subTest(path=path): + artifact = valid_artifact() + node(artifact, path)["unexpected"] = "closed-envelope-bypass" + self.assertInvalid(artifact, "unknown keys") + + def test_missing_required_keys_are_invalid(self) -> None: + artifact = valid_artifact() + for key in artifact: + with self.subTest(key=key): + candidate = copy.deepcopy(artifact) + del candidate[key] + self.assertInvalid(candidate, "missing keys") + + def test_wrong_container_types_and_unhashable_enums_fail_closed(self) -> None: + mutations = ( + ("mechanics", {}, "mechanics"), + (("payload", "actions"), {}, "actions"), + (("payload", "trajectory"), {}, "trajectory"), + (("payload", "outcome"), [], "outcome"), + (("evidence", "checks"), {}, "checks"), + (("evidence", "negative_controls"), {}, "negative_controls"), + (("evidence", "limitations"), [], "limitations"), + (("claim", "kind"), [], "kind"), + (("evidence", "checks", 0, "status"), [], "status"), + ) + for item in mutations: + path, replacement, message = item + path = (path,) if isinstance(path, str) else path + with self.subTest(path=path): + artifact = valid_artifact() + parent = node(artifact, path[:-1]) + parent[path[-1]] = replacement + self.assertInvalid(artifact, message) + + def test_identifiers_repository_and_revisions_are_strict(self) -> None: + cases = [] + for bad in ("", "has space", "é", "slash/not-allowed"): + cases.append((("claim", "id"), bad)) + cases.append((("payload", "domain"), bad)) + for bad in ("owner-only", "owner/repo/extra", "owner repo/name", 1): + cases.append((("producer", "repository"), bad)) + for path in (("producer", "revision"), ("mechanics", 0, "source_revision")): + for bad in ("A" * 40, "a" * 39, "g" * 40, 1): + cases.append((path, bad)) + for path, bad in cases: + with self.subTest(path=path, bad=bad): + artifact = valid_artifact() + node(artifact, path[:-1])[path[-1]] = bad + self.assertInvalid(artifact) + + def test_mechanic_paths_are_repository_relative_yaml_only(self) -> None: + for bad in ("", "/abs.yaml", "../escape.yaml", "./local.yaml", "a//b.yaml", "a/../b.yaml", "a\\b.yaml", "rules.txt"): + with self.subTest(path=bad): + artifact = valid_artifact() + artifact["mechanics"][0]["path"] = bad + self.assertInvalid(artifact, "path") + + def test_nonempty_fields_and_source_labels_are_validated(self) -> None: + paths = ( + ("claim", "statement"), + ("producer", "adapter"), + ("evidence", "limitations", 0), + ("evidence", "checks", 0, "source_labels", 0), + ("evidence", "checks", 0, "checker", "name"), + ("evidence", "checks", 0, "checker", "revision"), + ("evidence", "negative_controls", 0, "observed"), + ("source", "media_type"), + ) + for path in paths: + for bad in ("", " \t\n", None): + with self.subTest(path=path, bad=bad): + artifact = valid_artifact() + node(artifact, path[:-1])[path[-1]] = bad + self.assertInvalid(artifact) + + def test_negative_control_passed_requires_real_boolean(self) -> None: + for bad in (1, 0, "true", None): + with self.subTest(value=bad): + artifact = valid_artifact() + artifact["evidence"]["negative_controls"][0]["passed"] = bad + self.assertInvalid(artifact, "real boolean") + + def test_all_floats_and_unsafe_integers_are_rejected_in_payload_data(self) -> None: + for bad in (1.0, 1.5, float("nan"), float("inf"), INT64_MIN - 1, INT64_MAX + 1): + with self.subTest(value=bad): + artifact = valid_artifact() + artifact["payload"]["initial_state"]["position"] = bad + self.assertInvalid(artifact) + + def test_non_string_keys_and_cycles_do_not_escape_or_crash_validation(self) -> None: + artifact = valid_artifact() + artifact["payload"]["model"][1] = "non-string key" + self.assertInvalid(artifact, "keys") + artifact = valid_artifact() + artifact["payload"]["initial_state"]["cycle"] = artifact["payload"]["initial_state"] + self.assertInvalid(artifact, "cyclic") + + +class DigestValidationTests(ArtifactReportAssertions, unittest.TestCase): + def test_every_sha256_field_rejects_malformed_uppercase_and_all_zero_values(self) -> None: + paths = ( + ("artifact_sha256",), + ("mechanics", 0, "raw_sha256"), + ("payload", "model_sha256"), + ("payload", "initial_state_sha256"), + ("payload", "actions_sha256"), + ("payload", "trajectory_sha256"), + ("source", "raw_sha256"), + ("evidence", "checks", 0, "checker", "artifact_sha256"), + ("evidence", "checks", 0, "initial_state_sha256"), + ("evidence", "checks", 0, "actions_sha256"), + ("evidence", "checks", 0, "trajectory_sha256"), + ) + for path in paths: + for bad in ("0" * 64, "A" * 64, "a" * 63, "g" * 64, True): + with self.subTest(path=path, bad=bad): + artifact = valid_artifact() + node(artifact, path[:-1])[path[-1]] = bad + self.assertInvalid(artifact) + + def test_self_digest_detects_otherwise_valid_tampering(self) -> None: + artifact = valid_artifact() + artifact["claim"]["statement"] = "A different claim with the old self digest." + self.assertInvalid(artifact, "$.artifact_sha256: digest mismatch") + + def test_source_digest_binds_exact_raw_utf8_bytes(self) -> None: + artifact = valid_artifact() + artifact["source"]["raw"] += " " + reseal(artifact) + self.assertInvalid(artifact, "$.source.raw_sha256: digest mismatch") + + def test_all_payload_digests_bind_their_canonical_values(self) -> None: + replacements = { + "model": {"rules": "different"}, + "initial_state": {"position": 99}, + "actions": ["west"], + "trajectory": [{"position": 0}], + } + for name, replacement in replacements.items(): + with self.subTest(name=name): + artifact = valid_artifact() + artifact["payload"][name] = replacement + reseal(artifact) + self.assertInvalid(artifact, f"$.payload.{name}_sha256: digest mismatch") + + def test_all_check_digests_must_match_payload_commitments(self) -> None: + for name in ("initial_state", "actions", "trajectory"): + with self.subTest(name=name): + artifact = valid_artifact() + artifact["evidence"]["checks"][0][f"{name}_sha256"] = sha256_json({"different": name}) + reseal(artifact) + self.assertInvalid(artifact, f"checks[0].{name}_sha256: digest mismatch") + + def test_source_raw_must_be_exact_utf8_encodable_text(self) -> None: + artifact = valid_artifact() + artifact["source"]["raw"] = "\ud800" + self.assertInvalid(artifact, "UTF-8") + + +class BadgeDerivationTests(ArtifactReportAssertions, unittest.TestCase): + def assertSourceBadges(self, artifact: dict, expected: list[str]) -> None: + report = verify_gameplay_artifact(artifact) + self.assertTrue(report["valid"], report["errors"]) + self.assertEqual(report["source_badges"], expected) + self.assertEqual(report["admitted_badges"], ["OBSERVED"]) + self.assertEqual(derive_evidence_badges(artifact), ["OBSERVED"]) + + def with_checks(self, kinds_and_statuses: list[tuple[str, str]], controls: bool = True) -> dict: + artifact = valid_artifact() + artifact["evidence"]["checks"] = [ + _check(kind, artifact["payload"], status=status) for kind, status in kinds_and_statuses + ] + artifact["evidence"]["negative_controls"] = [_control()] if controls else [] + reseal(artifact) + return artifact + + def test_observation_is_default_ceiling_without_checks_or_controls(self) -> None: + self.assertSourceBadges(self.with_checks([], controls=False), ["OBSERVED"]) + self.assertSourceBadges(self.with_checks([("model_replay", "FAIL")], controls=False), ["OBSERVED"]) + + def test_replay_and_model_proof_require_a_passing_control(self) -> None: + for kind, badge in (("model_replay", "REPLAYED"), ("model_proof", "MODEL_PROVEN")): + with self.subTest(kind=kind, controls=False): + self.assertSourceBadges(self.with_checks([(kind, "PASS")], controls=False), ["OBSERVED"]) + with self.subTest(kind=kind, passed=False): + artifact = self.with_checks([(kind, "PASS")]) + artifact["evidence"]["negative_controls"][0]["passed"] = False + reseal(artifact) + self.assertSourceBadges(artifact, ["OBSERVED"]) + + def test_model_proof_and_live_confirmation_are_separate(self) -> None: + self.assertSourceBadges(self.with_checks([("model_proof", "PASS")]), ["OBSERVED", "MODEL_PROVEN"]) + self.assertSourceBadges( + self.with_checks([("model_proof", "PASS"), ("live_execution", "PASS")]), + ["OBSERVED", "MODEL_PROVEN", "LIVE_CONFIRMED"], + ) + self.assertSourceBadges( + self.with_checks([("model_replay", "PASS"), ("live_execution", "PASS")]), + ["OBSERVED", "REPLAYED", "LIVE_CONFIRMED"], + ) + + def test_live_confirmation_cannot_ignore_missing_model_support(self) -> None: + self.assertSourceBadges(self.with_checks([("live_execution", "PASS")]), ["OBSERVED"]) + + def test_any_fail_is_an_unresolved_aggregation_veto(self) -> None: + cases = ( + [("model_replay", "PASS"), ("model_replay", "FAIL")], + [("model_replay", "PASS"), ("live_execution", "FAIL")], + [("model_proof", "PASS"), ("model_replay", "PASS"), ("live_execution", "FAIL")], + ) + for checks in cases: + with self.subTest(checks=checks): + self.assertSourceBadges(self.with_checks(checks), ["OBSERVED"]) + + def test_source_labels_never_promote_and_are_preserved(self) -> None: + artifact = valid_artifact() + artifact["evidence"]["checks"][0]["source_labels"] = [ + "VERIFIED", + "MODEL_PROVEN", + "LIVE_CONFIRMED", + "arbitrary upstream label", + ] + artifact["evidence"]["negative_controls"] = [] + reseal(artifact) + before = copy.deepcopy(artifact) + self.assertSourceBadges(artifact, ["OBSERVED"]) + self.assertEqual(artifact, before) + self.assertEqual(artifact["evidence"]["checks"][0]["source_labels"], before["evidence"]["checks"][0]["source_labels"]) + + def test_invalid_artifacts_have_no_derived_badges(self) -> None: + artifact = valid_artifact() + artifact["claim"]["statement"] = "tampered" + self.assertEqual(derive_evidence_badges(artifact), []) + self.assertInvalid(artifact) + + +class SchemaTests(unittest.TestCase): + def test_schema_is_json_and_closes_every_envelope_object(self) -> None: + path = Path(__file__).resolve().parents[1] / "schema" / "gameplay-evidence-v0.1.schema.json" + schema = json.loads(path.read_text(encoding="utf-8")) + self.assertEqual(set(schema["required"]), set(valid_artifact()) - {"artifact_sha256"} | {"artifact_sha256"}) + self.assertFalse(schema["additionalProperties"]) + for name in ("producer", "claim", "payload", "evidence", "source"): + self.assertFalse(schema["properties"][name]["additionalProperties"]) + for name in ("mechanic", "check", "negativeControl"): + self.assertFalse(schema["definitions"][name]["additionalProperties"]) + self.assertFalse(schema["definitions"]["check"]["properties"]["checker"]["additionalProperties"]) + self.assertEqual(schema["properties"]["schema"]["const"], "gameplay-evidence/v0.1") + + +if __name__ == "__main__": + unittest.main()