| #!/usr/bin/env python3 | |
| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Validator for `trusted/locks/cartridges.lock.json` invariants. | |
| Enforces cartridge stability and composition rules: | |
| - `stability` is `"vetted"` or `"candidate:<snake_case_id>"`. | |
| - `Trusted.Core` (when present) must be `"vetted"` with no parents. | |
| - Vetted cartridges may never depend on a candidate parent. | |
| - Parent edges form a strict DAG (acyclic). | |
| - Candidate refinements own unique longest-prefix sub-namespaces of their | |
| domain cartridge and declare parents within that domain (or its ancestors). | |
| - `incompatible_with` names valid sibling cartridges, never self or ancestors, | |
| and is symmetric across declared pairs. | |
| - Deriving active cartridges from exported declaration names closes over | |
| declared ancestors and rejects co-occurring incompatible cartridges. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import re | |
| import sys | |
| from typing import Any, Iterable | |
| CARTRIDGE_ID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]{0,63}$") | |
| NAMESPACE_PREFIX_RE = re.compile(r"^Trusted(?:\.[A-Za-z][A-Za-z0-9_]*)*$") | |
| STABILITY_RE = re.compile(r"^(?:vetted|candidate:[a-z][a-z0-9_]{0,63})$") | |
| SHA256_RE = re.compile(r"^[0-9a-f]{64}$") | |
| SHA40_RE = re.compile(r"^[0-9a-f]{40}$") | |
| ALLOWED_TOP_KEYS = frozenset({ | |
| "schema_version", | |
| "reference_lean_id", | |
| "polarized_bridge_rustc_commit", | |
| "cartridges", | |
| }) | |
| ALLOWED_CARTRIDGE_KEYS = frozenset({ | |
| "id", | |
| "namespace_prefix", | |
| "stability", | |
| "parents", | |
| "incompatible_with", | |
| "stage_l_required", | |
| "required_semantic_epoch", | |
| "decl_map_sha256", | |
| }) | |
| def candidate_feature_id(stability: str) -> str | None: | |
| """Return `<id>` when `stability == 'candidate:<id>'`, else `None`.""" | |
| if stability.startswith("candidate:"): | |
| return stability[len("candidate:"):] | |
| return None | |
| def _prefix_contains(parent_prefix: str, child_prefix: str) -> bool: | |
| return ( | |
| child_prefix == parent_prefix | |
| or child_prefix.startswith(parent_prefix + ".") | |
| ) | |
| def validate_cartridges_lock(data: Any) -> list[str]: | |
| """Validate a parsed `cartridges.lock.json` object; return error list.""" | |
| errors: list[str] = [] | |
| if not isinstance(data, dict): | |
| return ["root value must be a JSON object"] | |
| extra_top = sorted(set(data.keys()) - ALLOWED_TOP_KEYS) | |
| if extra_top: | |
| errors.append(f"unexpected top-level keys: {', '.join(extra_top)}") | |
| schema_ver = data.get("schema_version") | |
| if ( | |
| not isinstance(schema_ver, int) | |
| or isinstance(schema_ver, bool) | |
| or schema_ver != 1 | |
| ): | |
| errors.append("`schema_version` must be integer 1") | |
| ref_lean = data.get("reference_lean_id") | |
| if not isinstance(ref_lean, str) or not ref_lean.strip(): | |
| errors.append("`reference_lean_id` must be a non-empty string") | |
| bridge_commit = data.get("polarized_bridge_rustc_commit") | |
| if bridge_commit is not None and ( | |
| not isinstance(bridge_commit, str) | |
| or not SHA40_RE.fullmatch(bridge_commit) | |
| ): | |
| errors.append("`polarized_bridge_rustc_commit` must be a 40-hex SHA or null") | |
| raw_carts = data.get("cartridges") | |
| if not isinstance(raw_carts, list) or not raw_carts: | |
| errors.append("`cartridges` must be a non-empty list") | |
| return errors | |
| by_id: dict[str, dict[str, Any]] = {} | |
| by_prefix: dict[str, str] = {} | |
| for idx, entry in enumerate(raw_carts): | |
| label = f"cartridges[{idx}]" | |
| if not isinstance(entry, dict): | |
| errors.append(f"{label}: must be an object") | |
| continue | |
| extra = sorted(set(entry.keys()) - ALLOWED_CARTRIDGE_KEYS) | |
| if extra: | |
| errors.append(f"{label}: unexpected keys: {', '.join(extra)}") | |
| cid = entry.get("id") | |
| if not isinstance(cid, str) or not CARTRIDGE_ID_RE.fullmatch(cid): | |
| errors.append(f"{label}: invalid `id` {cid!r}") | |
| continue | |
| if cid in by_id: | |
| errors.append(f"{label}: duplicate cartridge id `{cid}`") | |
| continue | |
| label = f"cartridge `{cid}`" | |
| prefix = entry.get("namespace_prefix") | |
| if not isinstance(prefix, str) or not NAMESPACE_PREFIX_RE.fullmatch(prefix): | |
| errors.append(f"{label}: invalid `namespace_prefix` {prefix!r}") | |
| elif prefix in by_prefix: | |
| errors.append( | |
| f"{label}: duplicate `namespace_prefix` `{prefix}` " | |
| f"(already owned by `{by_prefix[prefix]}`)" | |
| ) | |
| else: | |
| by_prefix[prefix] = cid | |
| stability = entry.get("stability") | |
| if not isinstance(stability, str) or not STABILITY_RE.fullmatch(stability): | |
| errors.append(f"{label}: invalid `stability` {stability!r}") | |
| parents = entry.get("parents") | |
| if ( | |
| not isinstance(parents, list) | |
| or not all(isinstance(p, str) for p in parents) | |
| or len(set(parents)) != len(parents) | |
| ): | |
| errors.append(f"{label}: `parents` must be a duplicate-free list of strings") | |
| incompat = entry.get("incompatible_with", []) | |
| if ( | |
| not isinstance(incompat, list) | |
| or not all(isinstance(x, str) for x in incompat) | |
| or len(set(incompat)) != len(incompat) | |
| ): | |
| errors.append( | |
| f"{label}: `incompatible_with` must be a duplicate-free list of strings" | |
| ) | |
| stage_l_req = entry.get("stage_l_required") | |
| if not isinstance(stage_l_req, bool): | |
| errors.append(f"{label}: `stage_l_required` must be a boolean") | |
| epoch = entry.get("required_semantic_epoch") | |
| if stage_l_req is True: | |
| if not isinstance(epoch, int) or isinstance(epoch, bool) or epoch < 1: | |
| errors.append( | |
| f"{label}: `required_semantic_epoch` must be a positive integer " | |
| "when `stage_l_required` is true" | |
| ) | |
| elif epoch is not None and ( | |
| not isinstance(epoch, int) or isinstance(epoch, bool) or epoch < 1 | |
| ): | |
| errors.append( | |
| f"{label}: `required_semantic_epoch` must be a positive integer or null" | |
| ) | |
| decl_sha = entry.get("decl_map_sha256") | |
| if decl_sha is not None and ( | |
| not isinstance(decl_sha, str) or not SHA256_RE.fullmatch(decl_sha) | |
| ): | |
| errors.append(f"{label}: `decl_map_sha256` must be a 64-hex SHA-256 or null") | |
| by_id[cid] = entry | |
| if errors: | |
| return errors | |
| # Root `Trusted` / `Trusted.Core` cartridges must be vetted with no parents. | |
| for cid, entry in by_id.items(): | |
| if cid == "Trusted.Core" or entry["namespace_prefix"] in ( | |
| "Trusted", | |
| "Trusted.Core", | |
| ): | |
| if entry["stability"] != "vetted": | |
| errors.append( | |
| f"core cartridge `{cid}` ({entry['namespace_prefix']}) " | |
| "must have stability `vetted`" | |
| ) | |
| if entry["parents"]: | |
| errors.append( | |
| f"core cartridge `{cid}` ({entry['namespace_prefix']}) " | |
| "must not declare parents" | |
| ) | |
| # Validate parent existence, vetted-never-depends-on-candidate, and cycles. | |
| for cid, entry in by_id.items(): | |
| for parent_id in entry["parents"]: | |
| if parent_id not in by_id: | |
| errors.append(f"cartridge `{cid}` references unknown parent `{parent_id}`") | |
| continue | |
| if entry["stability"] == "vetted" and by_id[parent_id]["stability"] != "vetted": | |
| errors.append( | |
| f"vetted cartridge `{cid}` may not depend on candidate parent `{parent_id}`" | |
| ) | |
| # Cycle detection and ancestor closure. | |
| visiting: set[str] = set() | |
| visited: set[str] = set() | |
| ancestors: dict[str, set[str]] = {} | |
| def dfs(cid: str) -> set[str]: | |
| if cid in ancestors: | |
| return ancestors[cid] | |
| if cid in visiting: | |
| errors.append(f"cycle detected in cartridge parent graph involving `{cid}`") | |
| return set() | |
| visiting.add(cid) | |
| anc: set[str] = set() | |
| for parent_id in by_id[cid]["parents"]: | |
| if parent_id in by_id: | |
| anc.add(parent_id) | |
| anc |= dfs(parent_id) | |
| visiting.remove(cid) | |
| visited.add(cid) | |
| ancestors[cid] = anc | |
| return anc | |
| for cid in sorted(by_id): | |
| dfs(cid) | |
| # Validate sub-namespace domain chaining: | |
| # - A vetted cartridge may never sit inside a candidate's namespace | |
| # (otherwise longest-prefix ownership would drop the enclosing candidate | |
| # feature from derived observations). | |
| # - If a candidate cartridge's namespace_prefix is a strict sub-prefix of | |
| # one or more enclosing cartridges, every enclosing cartridge must be an | |
| # ancestor, and all parents must lie within the most-specific | |
| # (longest-prefix) enclosing cartridge or its declared ancestors. | |
| for cid, entry in by_id.items(): | |
| prefix = entry["namespace_prefix"] | |
| strict_containers = [ | |
| other_id | |
| for other_id, other in by_id.items() | |
| if other_id != cid | |
| and _prefix_contains(other["namespace_prefix"], prefix) | |
| and other["namespace_prefix"] != prefix | |
| ] | |
| if not strict_containers: | |
| continue | |
| if entry["stability"] == "vetted": | |
| for enc_id in sorted(strict_containers): | |
| if by_id[enc_id]["stability"] != "vetted": | |
| errors.append( | |
| f"vetted cartridge `{cid}` ({prefix}) may not nest inside " | |
| f"candidate cartridge `{enc_id}` " | |
| f"({by_id[enc_id]['namespace_prefix']})" | |
| ) | |
| continue | |
| cid_anc = ancestors.get(cid, set()) | |
| # Every enclosing cartridge must be an ancestor. | |
| for enc_id in sorted( | |
| strict_containers, | |
| key=lambda oid: len(by_id[oid]["namespace_prefix"]), | |
| reverse=True, | |
| ): | |
| if enc_id not in cid_anc: | |
| enc_prefix = by_id[enc_id]["namespace_prefix"] | |
| errors.append( | |
| f"candidate refinement `{cid}` ({prefix}) must declare " | |
| f"enclosing domain `{enc_id}` ({enc_prefix}) as an ancestor" | |
| ) | |
| # Longest-prefix strict container is the immediate enclosing domain. | |
| domain_id = max( | |
| strict_containers, key=lambda oid: len(by_id[oid]["namespace_prefix"]) | |
| ) | |
| domain_prefix = by_id[domain_id]["namespace_prefix"] | |
| domain_anc = ancestors.get(domain_id, set()) | |
| for parent_id in entry["parents"]: | |
| if parent_id not in by_id: | |
| continue | |
| p_prefix = by_id[parent_id]["namespace_prefix"] | |
| in_domain = _prefix_contains(domain_prefix, p_prefix) | |
| if not (in_domain or parent_id in domain_anc): | |
| errors.append( | |
| f"candidate refinement `{cid}` may not declare cross-domain " | |
| f"parent `{parent_id}` outside `{domain_id}`" | |
| ) | |
| # Validate `incompatible_with` symmetry, non-ancestor rule, and that no | |
| # cartridge's own ancestor closure contains an incompatible pair. | |
| for cid, entry in by_id.items(): | |
| for other_id in entry.get("incompatible_with", []): | |
| if other_id not in by_id: | |
| errors.append( | |
| f"cartridge `{cid}` lists unknown incompatible cartridge `{other_id}`" | |
| ) | |
| continue | |
| if other_id == cid: | |
| errors.append(f"cartridge `{cid}` cannot be incompatible with itself") | |
| continue | |
| if other_id in ancestors.get(cid, set()) or cid in ancestors.get(other_id, set()): | |
| errors.append( | |
| f"cartridge `{cid}` cannot be incompatible with ancestor/descendant " | |
| f"`{other_id}`" | |
| ) | |
| continue | |
| if cid not in by_id[other_id].get("incompatible_with", []): | |
| errors.append( | |
| f"asymmetric `incompatible_with`: `{cid}` lists `{other_id}` " | |
| f"but `{other_id}` does not list `{cid}`" | |
| ) | |
| for cid in sorted(by_id): | |
| anc = ancestors.get(cid, set()) | |
| for u in sorted(anc): | |
| for v in by_id[u].get("incompatible_with", []): | |
| if v in anc and u < v: | |
| errors.append( | |
| f"cartridge `{cid}` depends on mutually incompatible " | |
| f"ancestors `{u}` and `{v}`" | |
| ) | |
| return errors | |
| def derive_observed_candidates( | |
| data: dict[str, Any], exported_decls: Iterable[str] | |
| ) -> tuple[list[str], list[str]]: | |
| """Derive active cartridge IDs and candidate feature IDs from declarations. | |
| Assigns each `Trusted.*` declaration to its longest-prefix owning cartridge, | |
| closes over declared ancestors, rejects incompatible co-occurring pairs, | |
| and returns `(sorted_cartridge_ids, sorted_candidate_feature_ids)`. | |
| """ | |
| errs = validate_cartridges_lock(data) | |
| if errs: | |
| raise ValueError("invalid cartridges.lock.json: " + "; ".join(errs)) | |
| by_id: dict[str, dict[str, Any]] = {c["id"]: c for c in data["cartridges"]} | |
| ordered = sorted( | |
| data["cartridges"], | |
| key=lambda c: len(c["namespace_prefix"]), | |
| reverse=True, | |
| ) | |
| active: set[str] = set() | |
| for decl in exported_decls: | |
| if decl != "Trusted" and not decl.startswith("Trusted."): | |
| continue | |
| owner: str | None = None | |
| for cart in ordered: | |
| if _prefix_contains(cart["namespace_prefix"], decl): | |
| owner = cart["id"] | |
| break | |
| if owner is None: | |
| raise ValueError(f"unowned Trusted declaration `{decl}`") | |
| active.add(owner) | |
| # Close over declared ancestors. | |
| stack = list(active) | |
| while stack: | |
| cur = stack.pop() | |
| for parent_id in by_id[cur]["parents"]: | |
| if parent_id not in active: | |
| active.add(parent_id) | |
| stack.append(parent_id) | |
| # Check pairwise incompatibility. | |
| for cid in sorted(active): | |
| for other_id in by_id[cid].get("incompatible_with", []): | |
| if other_id in active: | |
| raise ValueError( | |
| f"incompatible cartridges co-occur in proof export: " | |
| f"`{cid}` and `{other_id}`" | |
| ) | |
| features = sorted({ | |
| feat | |
| for cid in active | |
| if (feat := candidate_feature_id(by_id[cid]["stability"])) is not None | |
| }) | |
| return sorted(active), features | |
| def _load_json_no_duplicate_keys(text: str) -> Any: | |
| def _reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: | |
| out: dict[str, Any] = {} | |
| for key, value in pairs: | |
| if key in out: | |
| raise ValueError(f"duplicate JSON key `{key}`") | |
| out[key] = value | |
| return out | |
| return json.loads(text, object_pairs_hook=_reject_duplicates) | |
| def _find_boundary_prefix( | |
| raw_abs: Path, stop_at: Path | |
| ) -> tuple[Path, tuple[str, ...]] | None: | |
| """Return `(prefix, remaining_parts)` for the shallowest prefix matching `stop_at`.""" | |
| parts = raw_abs.parts | |
| if not parts: | |
| return None | |
| try: | |
| stop_resolved = stop_at.resolve() | |
| except OSError: | |
| stop_resolved = stop_at | |
| cur = Path(parts[0]) | |
| try: | |
| cur_resolved = cur.resolve() | |
| except OSError: | |
| cur_resolved = None | |
| if cur == stop_at or cur_resolved == stop_resolved: | |
| return cur, parts[1:] | |
| for idx in range(1, len(parts)): | |
| cur = cur / parts[idx] | |
| try: | |
| cur_resolved = cur.resolve() | |
| except OSError: | |
| cur_resolved = None | |
| if cur == stop_at or cur_resolved == stop_resolved: | |
| return cur, parts[idx + 1 :] | |
| return None | |
| def _has_symlink_component(path: Path, stop_at: Path | None = None) -> bool: | |
| """True when `path` or any component below `stop_at` (or CWD if relative) is a symlink.""" | |
| if stop_at is not None: | |
| raw_abs = path if path.is_absolute() else (Path.cwd() / path) | |
| boundary = _find_boundary_prefix(raw_abs, stop_at) | |
| if boundary is not None: | |
| cur, remaining = boundary | |
| for part in remaining: | |
| cur = cur / part | |
| if cur.is_symlink(): | |
| return True | |
| return False | |
| if raw_abs.is_symlink(): | |
| return True | |
| try: | |
| if raw_abs.resolve().is_relative_to(stop_at.resolve()): | |
| return True | |
| except OSError: | |
| return False | |
| return False | |
| if not path.is_absolute(): | |
| cur = Path.cwd() | |
| for part in path.parts: | |
| cur = cur / part | |
| if cur.is_symlink(): | |
| return True | |
| return False | |
| # Without a repository root boundary, avoid walking host/OS ancestors (such | |
| # as `/var -> private/var` or symlinked `TMPDIR`); still reject a symlink | |
| # leaf. | |
| return path.is_symlink() | |
| def _infer_repo_root(lock_path: Path, default_root: Path) -> Path | None: | |
| """Return `default_root` when `lock_path` is lexically or effectively inside it.""" | |
| raw_abs = lock_path if lock_path.is_absolute() else (Path.cwd() / lock_path) | |
| norm_abs = Path(os.path.normpath(str(raw_abs))) | |
| if _find_boundary_prefix(norm_abs, default_root) is not None: | |
| return default_root | |
| try: | |
| if raw_abs.resolve().is_relative_to(default_root.resolve()): | |
| return default_root | |
| except OSError: | |
| pass | |
| return None | |
| def check_file( | |
| path: Path, | |
| *, | |
| require_exists: bool = False, | |
| repo_root: Path | None = None, | |
| ) -> list[str]: | |
| if _has_symlink_component(path, stop_at=repo_root): | |
| return [f"{path}: symlinks are forbidden"] | |
| if repo_root is not None: | |
| try: | |
| resolved_path = path.resolve() | |
| resolved_root = repo_root.resolve() | |
| except OSError as exc: | |
| return [f"{path}: cannot resolve path: {exc}"] | |
| if not resolved_path.is_relative_to(resolved_root): | |
| return [f"{path}: escapes repository root"] | |
| if not path.exists(): | |
| if require_exists: | |
| return [f"{path}: required lock file is missing"] | |
| return [] | |
| if not path.is_file(): | |
| return [f"{path}: expected a regular file"] | |
| try: | |
| data = _load_json_no_duplicate_keys(path.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: | |
| return [f"{path}: cannot parse JSON: {exc}"] | |
| return validate_cartridges_lock(data) | |
| def main(argv: Iterable[str] | None = None) -> int: | |
| default_root = Path(__file__).resolve().parent.parent | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument( | |
| "--lock", | |
| type=Path, | |
| default=default_root / "trusted/locks/cartridges.lock.json", | |
| help="path to cartridges.lock.json", | |
| ) | |
| parser.add_argument( | |
| "--require-exists", | |
| action="store_true", | |
| help="fail if the lock file does not exist", | |
| ) | |
| args = parser.parse_args(list(argv) if argv is not None else None) | |
| root = _infer_repo_root(args.lock, default_root) | |
| errors = check_file(args.lock, require_exists=args.require_exists, repo_root=root) | |
| if errors: | |
| for err in errors: | |
| print(f"cartridges-lock: {err}", file=sys.stderr) | |
| return 1 | |
| print("cartridges-lock: OK") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |