#!/usr/bin/env python3 """Check a Legal Process Disclosure file against the v1 schema and the rules a schema can't express. The Legal Process Disclosure Format (LPDF) was designed by Olympian Tools, which maintains this validator, the schema and the specification: https://olympiantools.com/legal-process/spec/ (c) 2026 Olympian Tools. MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python3 validate.py path/to/legal-process.json [more files...] Needs the jsonschema package (pip install jsonschema). Exits 1 if any file has an error; warnings don't fail it. """ import json import re import sys from datetime import datetime, timedelta, timezone from pathlib import Path from urllib.parse import urlsplit try: from jsonschema import Draft202012Validator, FormatChecker except ImportError: sys.exit("This needs the jsonschema package: pip install jsonschema") # the schema next to this script, or the published copy if this script was downloaded on its own _local = Path(__file__).parent / "v1.json" if _local.exists(): SCHEMA = json.loads(_local.read_text()) else: from urllib.request import urlopen with urlopen("https://olympiantools.com/schemas/legal-process/v1.json", timeout=20) as r: SCHEMA = json.loads(r.read()) def when(s): return datetime.fromisoformat(s.replace("Z", "+00:00")) # Dates and links are checked here, not left to jsonschema: it only checks them when extra packages happen to be # installed, and a file should get the same answer everywhere (this matches the check Olympian Tools runs on its form). FORMATS = FormatChecker() _DATETIME = re.compile(r"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-](\d{2}):(\d{2}))$", re.I) @FORMATS.checks("date-time") def _is_datetime(v): if not isinstance(v, str): return True m = _DATETIME.match(v) if not m: return False y, mo, d, h, mi, sec, oh, om = (int(x) if x else 0 for x in m.groups()) try: datetime(y, mo, d) # a real calendar day except ValueError: return False return h <= 23 and mi <= 59 and sec <= 59 and oh <= 23 and om <= 59 @FORMATS.checks("date") def _is_date(v): if not isinstance(v, str): return True try: return bool(re.match(r"^\d{4}-\d{2}-\d{2}$", v)) and bool(datetime.strptime(v, "%Y-%m-%d")) except ValueError: return False @FORMATS.checks("uri") def _is_uri(v): if not isinstance(v, str): return True u = urlsplit(v) return bool(u.scheme) and bool(u.netloc) and not re.search(r"\s", v) def check(doc): errors, warnings = [], [] v = Draft202012Validator(SCHEMA, format_checker=FORMATS) for e in sorted(v.iter_errors(doc), key=lambda e: list(e.path)): errors.append("/" + "/".join(str(p) for p in e.path) + ": " + e.message) if errors: return errors, warnings # the rest assumes the shape is right def ids(items, where): seen = set() for i, it in enumerate(items or []): if it["id"] in seen: errors.append(f"{where}/{i}/id: \"{it['id']}\" is used twice") seen.add(it["id"]) return seen services = ids(doc["provider"]["services"], "/provider/services") contacts = ids(doc["contacts"], "/contacts") portals = ids(doc.get("portals"), "/portals") ids(doc["data_categories"], "/data_categories") # every reference must point at something that exists def walk(node, path): if isinstance(node, dict): for k, val in node.items(): p = f"{path}/{k}" if k in ("contact_id", "billing_contact_id") and val not in contacts: errors.append(f"{p}: no contact has id \"{val}\"") elif k == "portal_id" and val not in portals: errors.append(f"{p}: no portal has id \"{val}\"") elif k == "contact_ids": errors.extend(f"{p}: no contact has id \"{x}\"" for x in val if x not in contacts) elif k == "services" and path != "/provider" and isinstance(val, list): errors.extend(f"{p}: no service has id \"{x}\"" for x in val if x not in services) else: walk(val, p) elif isinstance(node, list): for i, val in enumerate(node): walk(val, f"{path}/{i}") walk(doc, "") for i, c in enumerate(doc["contacts"]): if c["method"] == "portal" and "portal_id" not in c: warnings.append(f"/contacts/{i}: method is portal but portal_id is missing") f = doc["file"] reviewed, expires, published = when(f["last_reviewed"]), when(f["expires"]), when(f["published"]) if expires > reviewed + timedelta(days=366): errors.append("/file/expires: must be no more than 12 months after last_reviewed") if reviewed < published: errors.append("/file/last_reviewed: is before published") now = datetime.now(timezone.utc) if expires < now: warnings.append("/file/expires: this file has expired; readers must treat it as unconfirmed") elif expires < now + timedelta(days=30): warnings.append("/file/expires: expires within 30 days") if not any("emergency" in c["purposes"] for c in doc["contacts"]): warnings.append("/contacts: no contact is listed for emergencies") for i, d in enumerate(doc["data_categories"]): if "effective_from" not in d["retention"]: warnings.append(f"/data_categories/{i}/retention: no effective_from date, so readers can't tell which records it applies to") return errors, warnings def main(paths): bad = False for p in paths: try: doc = json.loads(Path(p).read_text()) except (OSError, ValueError) as e: print(f"{p}: cannot read: {e}") bad = True continue errors, warnings = check(doc) for e in errors: print(f"{p}: error {e}") for w in warnings: print(f"{p}: warning {w}") if not errors: print(f"{p}: valid" + (f" ({len(warnings)} warning{'s' if len(warnings) != 1 else ''})" if warnings else "")) bad = bad or bool(errors) return 1 if bad else 0 if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(__doc__) sys.exit(main(sys.argv[1:]))