47 lines
2.0 KiB
Python
47 lines
2.0 KiB
Python
"""Evidence v1: deliberately narrow, deterministic wire/signature format."""
|
|
|
|
import json
|
|
import re
|
|
from datetime import datetime
|
|
|
|
FIELDS = {"event_id", "node_id", "risk_level", "timestamp", "sequence"}
|
|
IDENTIFIER = re.compile(r"[A-Za-z0-9_.:-]{1,128}\Z")
|
|
TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\Z", re.ASCII)
|
|
|
|
|
|
def canonical_payload(payload):
|
|
"""Only this validated schema is canonicalized; this is NOT general JCS."""
|
|
if not isinstance(payload, dict) or set(payload) != FIELDS:
|
|
raise ValueError("payload requires exactly event_id, node_id, risk_level, timestamp, sequence")
|
|
for name in ("event_id", "node_id"):
|
|
if not isinstance(payload[name], str) or not IDENTIFIER.fullmatch(payload[name]):
|
|
raise ValueError(f"invalid {name}")
|
|
if not isinstance(payload["risk_level"], str) or payload["risk_level"] not in {
|
|
"LOW", "MEDIUM", "HIGH", "CRITICAL"
|
|
}:
|
|
raise ValueError("invalid risk_level")
|
|
timestamp = payload["timestamp"]
|
|
if not isinstance(timestamp, str) or not TIMESTAMP.fullmatch(timestamp):
|
|
raise ValueError("timestamp must be UTC YYYY-MM-DDTHH:MM:SSZ")
|
|
datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ")
|
|
if type(payload["sequence"]) is not int or not 1 <= payload["sequence"] <= 2**63 - 1:
|
|
raise ValueError("sequence must be an integer from 1 to 2^63-1")
|
|
# All strings above are restricted to ASCII without JSON escape characters.
|
|
# Sorted field names, decimal integer, no whitespace, UTF-8, no trailing LF.
|
|
return json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
|
|
|
|
def unique_object(pairs):
|
|
result = {}
|
|
for key, value in pairs:
|
|
if key in result:
|
|
raise ValueError(f"duplicate JSON key: {key}")
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def read_json(raw):
|
|
def invalid_constant(value):
|
|
raise ValueError(f"invalid JSON constant: {value}")
|
|
return json.loads(raw, object_pairs_hook=unique_object, parse_constant=invalid_constant)
|