diff --git a/src/openultrasast/push/advisory-scope.json b/src/openultrasast/push/advisory-scope.json new file mode 100644 index 00000000..63657d30 --- /dev/null +++ b/src/openultrasast/push/advisory-scope.json @@ -0,0 +1,54 @@ +{ + "schema_version": 1, + "status": "provisional", + "basis": "No capability is qualified for alerts today: the shipped capability registry (eligibility.json) has verdict NO-GO and enables no declaration. This is the intended v1 advisory scope; it becomes effective only through the M4 evaluation bound to an immutable spent population (valid-detection-benchmark tasks 11.6 and 11.7).", + "scope": [ + { + "family": "injection", + "label": "injection", + "reason": "Injection entails with witnesses on the measured subjects." + }, + { + "family": "untrusted_destination", + "label": "untrusted destination", + "reason": "Untrusted destination entails with witnesses on the measured subjects." + }, + { + "family": "config_secrets", + "label": "configuration", + "reason": "Configuration entails with witnesses on the measured subjects." + } + ], + "exclusions": [ + { + "family": "access_control", + "label": "access control", + "reason": "Access control does not entail with witnesses on the measured subjects: on an application that splits its route from its data access the obligation is carried, and a carried obligation corroborates by design, so shipping the family would ship silence.", + "not_told": "No defect is reported for access control, so a contributor is not told that a change reaches a protected operation without the guard or ownership constraint its siblings carry, even when it does." + }, + { + "family": "output_encoding", + "label": "output encoding", + "reason": "Has not earned a place through evaluation.", + "not_told": "No defect is reported for output encoding, so a contributor is not told that a change sends untrusted data to a rendered document or a header without encoding, even when it does." + }, + { + "family": "path", + "label": "path", + "reason": "Has not earned a place through evaluation.", + "not_told": "No defect is reported for path, so a contributor is not told that a change lets untrusted input reach a filesystem path, even when it does." + }, + { + "family": "prototype", + "label": "prototype", + "reason": "Has not earned a place through evaluation.", + "not_told": "No defect is reported for prototype, so a contributor is not told that a change lets untrusted keys reach an object merge or an attribute assignment, even when it does." + }, + { + "family": "deserialization", + "label": "deserialization", + "reason": "Has not earned a place through evaluation.", + "not_told": "No defect is reported for deserialization, so a contributor is not told that a change deserializes untrusted data into objects the process then trusts, even when it does." + } + ] +} diff --git a/src/openultrasast/push/advisory_scope.py b/src/openultrasast/push/advisory_scope.py new file mode 100644 index 00000000..b8315e25 --- /dev/null +++ b/src/openultrasast/push/advisory_scope.py @@ -0,0 +1,138 @@ +"""The declared advisory scope of the pre-push safety net (task 15.2): one packaged record. + +``advisory-scope.json`` names the families whose claims are intended to be admitted as alerts and every +family that is not, with the reason and what a contributor is therefore not told. Like the eligibility +registry it is a shipped release input: never repository configuration, never a model response. The +scope is provisional until the M4 evaluation qualifies a capability, so the rendered line states that +limit instead of letting a listed family read as checked and found fine. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path + +from openultrasast.model.taxonomy import FAMILY_IDS + +_DEFAULT = Path(__file__).with_name("advisory-scope.json") +_LIMIT = 64 * 1024 +_SCHEMA_VERSION = 1 +_TOP_KEYS = frozenset({"schema_version", "status", "basis", "scope", "exclusions"}) +_ENTRY_KEYS = frozenset({"family", "label", "reason"}) +_EXCLUSION_KEYS = _ENTRY_KEYS | {"not_told"} +# Families come from the closed vocabulary and are unique, so labels of this size keep the line bounded. +_MAX_LABEL = 48 +_UNAVAILABLE = "advisory_scope_invalid_or_unavailable" +_PROVISIONAL_LINE = ( + "Scope: provisional, not yet in effect: no family is qualified for alerts yet. " + "Intended v1 advisory scope: {scope}. " + "Not reported as defects: {excluded}, or any other family outside the scope. " + "Listing a family does not mean the repository was found free of defects in it." +) +_UNKNOWN_LINE = ( + "Scope: unknown. The shipped scope record could not be read, so which families this tool can and cannot " + "report is unknown; that missing limit is itself a limit of this run." +) + + +@dataclass(frozen=True) +class FamilyScope: + """One family of the record: intended for admission, or excluded from it with what is not told.""" + + family: str + label: str + reason: str + not_told: str | None = None + + def to_payload(self) -> dict[str, str]: + payload = {"family": self.family, "label": self.label, "reason": self.reason} + if self.not_told is not None: + payload["not_told"] = self.not_told + return payload + + +@dataclass(frozen=True) +class AdvisoryScope: + """A validated provisional scope, or the closed `unavailable` result with one reason code.""" + + status: str + basis: str = "" + scope: tuple[FamilyScope, ...] = () + exclusions: tuple[FamilyScope, ...] = () + reason: str = "" + + def to_payload(self) -> dict[str, object]: + """The artifact field: the record itself, or the unavailable status with its reason.""" + if self.status != "provisional": + return {"status": self.status, "reason": self.reason} + return { + "schema_version": _SCHEMA_VERSION, + "status": self.status, + "basis": self.basis, + "scope": [entry.to_payload() for entry in self.scope], + "exclusions": [entry.to_payload() for entry in self.exclusions], + } + + def render(self) -> str: + """The one limit line for the terminal: fixed phrases and the record's labels, nothing else.""" + if self.status != "provisional": + # Anything but a validated provisional record leaves the limits unknown; never a claim. + return _UNKNOWN_LINE + return _PROVISIONAL_LINE.format(scope=_labels(self.scope), excluded=_labels(self.exclusions)) + + +def _labels(entries: tuple[FamilyScope, ...]) -> str: + return ", ".join(entry.label for entry in entries) + + +def _text(value: object, *, limit: int | None = None) -> str: + # Exact type and printable ASCII: a bool is not a name, and no control character can add a line or an escape. + if type(value) is not str or not value.strip() or not value.isascii() or not value.isprintable(): + raise ValueError("advisory_scope_text_invalid") + if limit is not None and len(value) > limit: + raise ValueError("advisory_scope_label_too_long") + return value + + +def _entry(raw: object, *, excluded: bool) -> FamilyScope: + if type(raw) is not dict or set(raw) != (_EXCLUSION_KEYS if excluded else _ENTRY_KEYS): + raise ValueError("advisory_scope_entry_invalid") + family = _text(raw["family"], limit=_MAX_LABEL) + if family not in FAMILY_IDS: + raise ValueError("advisory_scope_family_unknown") + return FamilyScope( + family, + _text(raw["label"], limit=_MAX_LABEL), + _text(raw["reason"]), + _text(raw["not_told"]) if excluded else None, + ) + + +def _validate(data: object) -> AdvisoryScope: + if type(data) is not dict or set(data) != _TOP_KEYS: + raise ValueError("advisory_scope_shape_invalid") + version, status, scope, exclusions = (data[key] for key in ("schema_version", "status", "scope", "exclusions")) + if type(version) is not int or version != _SCHEMA_VERSION or status != "provisional": + raise ValueError("advisory_scope_version_or_status_unsupported") + if type(scope) is not list or type(exclusions) is not list or not scope or not exclusions: + raise ValueError("advisory_scope_families_invalid") + intended = tuple(_entry(item, excluded=False) for item in scope) + leave_out = tuple(_entry(item, excluded=True) for item in exclusions) + families = [entry.family for entry in (*intended, *leave_out)] + if len(set(families)) != len(families): + # One rule for a family named twice and for one listed on both sides: the sides stay disjoint. + raise ValueError("advisory_scope_family_repeated") + return AdvisoryScope("provisional", _text(data["basis"]), intended, leave_out) + + +def load_advisory_scope(path: Path | None = None) -> AdvisoryScope: + """The shipped scope record, or a closed `unavailable` scope: this never raises into the hook.""" + try: + with (path or _DEFAULT).open("rb") as stream: + content = stream.read(_LIMIT + 1) + if len(content) > _LIMIT: + raise ValueError("advisory_scope_size_limit") + return _validate(json.loads(content)) + except (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError): + return AdvisoryScope("unavailable", reason=_UNAVAILABLE) diff --git a/src/openultrasast/push/report.py b/src/openultrasast/push/report.py index dc7c5ead..fb6b474b 100644 --- a/src/openultrasast/push/report.py +++ b/src/openultrasast/push/report.py @@ -17,6 +17,7 @@ from typing import Literal from openultrasast.model.contracts import ChangeContext, ExecutionBudget from openultrasast.model.scan import ModelScanResult +from openultrasast.push.advisory_scope import AdvisoryScope, load_advisory_scope from openultrasast.push.contracts import PushComparison, PushResolution, PushResult, SnapshotManifest from openultrasast.push.explain import explain from openultrasast.push.policy import AdmissionResult, _context_boundaries @@ -49,6 +50,9 @@ class PushReport: quick: tuple[Mapping[str, object], ...] = () # The background engine (task 17.5): what this run started, and earlier results shown now. background: Mapping[str, object] = field(default_factory=dict) + # The declared advisory scope (task 15.2): the shipped record, kept in the artifact and rendered as the + # one limit line. Loading is closed: an unreadable record is itself reported as a limit. + advisory_scope: AdvisoryScope = field(default_factory=load_advisory_scope) def __post_init__(self) -> None: object.__setattr__(self, "model_assistance", MappingProxyType(dict(self.model_assistance))) @@ -90,6 +94,8 @@ class PushReport: type(value) not in (int, float) or not math.isfinite(value) or value < 0 for value in self.timings.values() ): raise ValueError("report requires finite nonnegative timings including total_seconds") + if not isinstance(self.advisory_scope, AdvisoryScope): + raise ValueError("report requires a loaded advisory scope") @dataclass(frozen=True) @@ -140,6 +146,7 @@ def _write_artifact(report: PushReport, target: Path, temporary: Path, connectio "experimental": dict(report.experimental), "quick_tier": [dict(item) for item in report.quick], "engine_background": dict(report.background), + "advisory_scope": report.advisory_scope.to_payload(), } json.dump(payload, stream, ensure_ascii=True, allow_nan=False, indent=2) stream.write("\n") @@ -413,6 +420,8 @@ def render_report(report: PushReport, *, artifact: Path | None, error: str | Non lines.append("Notice: " + " ".join(notices)) if report.experimental: lines.append("Experimental: " + _experimental_line(report.experimental)) + # The limit notice of the whole report (task 15.2): once per run, with or without defects. + lines.append(report.advisory_scope.render()) if artifact is not None: lines.append("Details: " + _short(str(artifact), 4096)) if report.result.push_disposition == "block": diff --git a/tests/test_push_advisory_scope.py b/tests/test_push_advisory_scope.py new file mode 100644 index 00000000..1c517963 --- /dev/null +++ b/tests/test_push_advisory_scope.py @@ -0,0 +1,212 @@ +"""The declared advisory scope (pre-push task 15.2): one shipped record, published as a limit. + +The scope is provisional. No capability is qualified for alerts, so the terminal line has to say so, +and it must never read as "these families were checked and are fine". +""" + +import json +import re +from dataclasses import replace +from importlib.resources import files + +import pytest +from test_push_report import budget, report_with + +from openultrasast.model.taxonomy import FAMILY_IDS +from openultrasast.push.report import deliver_report + +UNAVAILABLE = "advisory_scope_invalid_or_unavailable" +UNAVAILABLE_LINE = ( + "Scope: unknown. The shipped scope record could not be read, so which families this tool can and cannot " + "report is unknown; that missing limit is itself a limit of this run." +) +# Every artifact key that existed before the scope record, plus the new one: none may be renamed or dropped. +ARTIFACT_KEYS = frozenset( + { + "schema_version", + "model_assistance", + "change_contexts", + "snapshots", + "change_context", + "result", + "admission", + "scans", + "provenance", + "timings", + "timing_scope", + "resolution", + "experimental", + "quick_tier", + "engine_background", + "advisory_scope", + } +) + + +def _edited(record, side, index, *removed, **changes): + entries = [dict(entry) for entry in record[side]] + for key in removed: + del entries[index][key] + entries[index].update(changes) + return {**record, side: entries} + + +# Each damage breaks exactly one rule of the shipped record; each must end in the same closed result. +DAMAGES = { + "truncated": lambda record, raw, limit: raw[: len(raw) // 2], + "empty": lambda record, raw, limit: b"", + "not_json": lambda record, raw, limit: b"\x03not json", + "list_at_top": lambda record, raw, limit: b"[]", + "null_at_top": lambda record, raw, limit: b"null", + "schema_version_newer": lambda record, raw, limit: {**record, "schema_version": 2}, + "schema_version_text": lambda record, raw, limit: {**record, "schema_version": "1"}, + "schema_version_bool": lambda record, raw, limit: {**record, "schema_version": True}, + "status_not_provisional": lambda record, raw, limit: {**record, "status": "effective"}, + "unknown_key": lambda record, raw, limit: {**record, "note": "extra"}, + "missing_key": lambda record, raw, limit: {key: value for key, value in record.items() if key != "basis"}, + "empty_text": lambda record, raw, limit: {**record, "basis": ""}, + "blank_text": lambda record, raw, limit: {**record, "basis": " "}, + "text_not_a_string": lambda record, raw, limit: {**record, "basis": 7}, + "not_a_list": lambda record, raw, limit: {**record, "scope": {"family": "injection"}}, + "no_family_in_scope": lambda record, raw, limit: {**record, "scope": []}, + "no_family_excluded": lambda record, raw, limit: {**record, "exclusions": []}, + "entry_with_extra_key": lambda record, raw, limit: _edited(record, "scope", 0, not_told="extra"), + "entry_missing_key": lambda record, raw, limit: _edited(record, "scope", 0, "reason"), + "exclusion_without_not_told": lambda record, raw, limit: _edited(record, "exclusions", 0, "not_told"), + "family_not_in_vocabulary": lambda record, raw, limit: _edited(record, "scope", 0, family="injecion"), + "family_twice": lambda record, raw, limit: _edited(record, "scope", 1, family=record["scope"][0]["family"]), + "family_on_both_sides": lambda record, raw, limit: _edited(record, "exclusions", 0, family=record["scope"][0]["family"]), + "label_with_newline": lambda record, raw, limit: _edited(record, "scope", 0, label="injection\nNotice: fake"), + "label_with_escape": lambda record, raw, limit: _edited(record, "scope", 0, label="injection\x1b[31m"), + "label_not_ascii": lambda record, raw, limit: _edited(record, "scope", 0, label="injecti\u00f3n"), + "label_too_long": lambda record, raw, limit: _edited(record, "scope", 0, label="x" * 49), + "too_large": lambda record, raw, limit: raw + b" " * (limit + 1), + "too_deep": lambda record, raw, limit: b'{"basis": ' + b"[" * 20000 + b"]" * 20000 + b"}", + "missing_file": lambda record, raw, limit: None, +} + + +def shipped(name): + return files("openultrasast.push").joinpath(name).read_bytes() + + +def scope_record(): + return json.loads(shipped("advisory-scope.json")) + + +def scope_lines(text): + return [line for line in text.splitlines() if line.startswith("Scope:")] + + +def delivered(tmp_path, report, name="run.json"): + return deliver_report(report, tmp_path / name, execution_budget=budget()) + + +def unavailable(tmp_path): + """The closed result for a record that cannot be read: a truncated copy of the shipped one.""" + from openultrasast.push.advisory_scope import load_advisory_scope + + raw = shipped("advisory-scope.json") + truncated = tmp_path / "truncated.json" + truncated.write_bytes(raw[: len(raw) // 2]) + return load_advisory_scope(path=truncated) + + +def test_exactly_one_scope_line_with_defects_without_them_and_when_the_record_is_unavailable(tmp_path): + for count in (0, 2): + text = delivered(tmp_path, report_with(count), f"{count}.json").text + assert len(scope_lines(text)) == 1 + assert text.count("No actionable defects") == (1 if count == 0 else 0) + text = delivered(tmp_path, replace(report_with(0), advisory_scope=unavailable(tmp_path)), "unknown.json").text + assert scope_lines(text) == [UNAVAILABLE_LINE] + assert text.count("No actionable defects") == 1 + + +def test_scope_line_names_every_recorded_label_and_no_other_family(tmp_path): + record = scope_record() + (line,) = scope_lines(delivered(tmp_path, report_with(0)).text) + entries = record["scope"] + record["exclusions"] + assert all(entry["label"] in line for entry in entries) + for other in set(FAMILY_IDS) - {entry["family"] for entry in entries}: + assert not re.search(rf"\b{re.escape(other)}\b", line), other + intended = ", ".join(entry["label"] for entry in record["scope"]) + excluded = ", ".join(entry["label"] for entry in record["exclusions"]) + assert line == ( + "Scope: provisional, not yet in effect: no family is qualified for alerts yet. " + f"Intended v1 advisory scope: {intended}. " + f"Not reported as defects: {excluded}, or any other family outside the scope. " + "Listing a family does not mean the repository was found free of defects in it." + ) + + +def test_scope_line_states_the_provisional_limit_and_never_reads_as_an_alert(tmp_path): + text = delivered(tmp_path, report_with(0)).text + (line,) = scope_lines(text) + lowered = line.lower() + assert "provisional" in lowered and "not yet in effect" in lowered + assert "no family is qualified for alerts" in lowered + assert "secure" not in text.lower() and "clean" not in text.lower() + assert not re.search(r"- \S+ at .+:\d+|Fix:|Evidence:", line) + assert len(line) <= 750 + + +def test_artifact_keeps_the_scope_record_with_every_reason_and_what_is_not_told(tmp_path): + data = json.loads(delivered(tmp_path, report_with(0)).artifact.read_text()) + assert set(data) == ARTIFACT_KEYS + assert data["advisory_scope"] == scope_record() + assert all(entry["reason"] for entry in data["advisory_scope"]["scope"]) + assert all(entry["reason"] and entry["not_told"] for entry in data["advisory_scope"]["exclusions"]) + + +def test_artifact_records_the_unavailable_status_and_reason_when_the_record_cannot_be_read(tmp_path): + report = replace(report_with(0), advisory_scope=unavailable(tmp_path)) + data = json.loads(delivered(tmp_path, report).artifact.read_text()) + assert data["advisory_scope"] == {"status": "unavailable", "reason": UNAVAILABLE} + + +def test_provisional_iff_the_shipped_registry_is_no_go_and_enables_no_declaration(): + registry = json.loads(shipped("eligibility.json")) + no_go = registry["verdict"] == "NO-GO" and all(not entry["declaration"]["enabled"] for entry in registry["entries"]) + # Flipping the registry or the record without the other fails here (maintainer decision 5). + assert (scope_record()["status"] == "provisional") == no_go + + +def test_shipped_record_loads_as_the_declared_provisional_scope(): + from openultrasast.push.advisory_scope import load_advisory_scope + + scope = load_advisory_scope() + assert scope.status == "provisional" and scope.reason == "" + assert [(entry.family, entry.label) for entry in scope.scope] == [ + ("injection", "injection"), + ("untrusted_destination", "untrusted destination"), + ("config_secrets", "configuration"), + ] + assert [(entry.family, entry.label) for entry in scope.exclusions] == [ + ("access_control", "access control"), + ("output_encoding", "output encoding"), + ("path", "path"), + ("prototype", "prototype"), + ("deserialization", "deserialization"), + ] + assert scope.to_payload() == scope_record() + + +@pytest.mark.parametrize("name", sorted(DAMAGES)) +def test_invalid_or_truncated_record_gives_a_closed_unavailable_result(tmp_path, name): + from openultrasast.push.advisory_scope import _LIMIT, load_advisory_scope + + raw = shipped("advisory-scope.json") + content = DAMAGES[name](json.loads(raw), raw, _LIMIT) + path = tmp_path / "copy.json" + if content is not None: + path.write_bytes(content if isinstance(content, bytes) else json.dumps(content).encode()) + scope = load_advisory_scope(path=path) + assert scope.status == "unavailable" and scope.reason == UNAVAILABLE + assert (scope.basis, scope.scope, scope.exclusions) == ("", (), ()) + assert scope.render() == UNAVAILABLE_LINE + assert scope.to_payload() == {"status": "unavailable", "reason": UNAVAILABLE} + + +def test_report_refuses_anything_but_a_loaded_scope(): + with pytest.raises(ValueError, match="advisory scope"): + replace(report_with(0), advisory_scope=None)