From b372d08ab17646f15ae3f486494a2d18fe9df52f Mon Sep 17 00:00:00 2001 From: binaryknight Date: Tue, 10 Nov 2026 05:46:09 +0000 Subject: [PATCH] State what stays compatible, and test each promise docs/COMPATIBILITY.md says what holds from one version to the next: the commands, flags and exit codes, the report format, the scoring weights and finding IDs, and the GitHub Action's inputs and outputs. It names verify, submit and benchmark as experimental and says how a score can still change. tests/test_compatibility.py checks each promise. Reports now record agentsec_version beside probe_version, so a change in scoring is visible in the report. --baseline and agentsec history note a difference in either version. A difference with nothing worse passes, as the gate always has. The README and the gate's note said it failed, and now match the code. JSON Schemas for the blast-radius report and the assert result ship in agentsec/data/, and every report in examples/ is checked against the first. Also adds agentsec --version, the experimental labels in help, PyPI classifiers, and jsonschema as a test dependency. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + README.md | 4 +- agentsec/baseline.py | 20 +- agentsec/cli.py | 14 +- agentsec/data/blast-radius-report.schema.json | 82 +++++++ agentsec/data/path-assertions.schema.json | 35 +++ agentsec/history.py | 6 +- agentsec/integrations/promptfoo_combine.py | 3 +- agentsec/runner.py | 3 +- agentsec/ui/server.py | 3 +- agentsec/verify.py | 3 +- docs/COMPATIBILITY.md | 52 +++++ pyproject.toml | 17 +- tests/fixtures/cli_surface.json | 90 ++++++++ tests/test_compatibility.py | 215 ++++++++++++++++++ 15 files changed, 534 insertions(+), 17 deletions(-) create mode 100644 agentsec/data/blast-radius-report.schema.json create mode 100644 agentsec/data/path-assertions.schema.json create mode 100644 docs/COMPATIBILITY.md create mode 100644 tests/fixtures/cli_surface.json create mode 100644 tests/test_compatibility.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 12dd232..70b05f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and two reports are only comparable when it matches or the difference is known. ## Unreleased +- `docs/COMPATIBILITY.md` states what stays the same from one version to the next: the commands, flags and exit codes, the report format, the scoring and the GitHub Action's inputs and outputs. `tests/test_compatibility.py` checks each of those. `verify`, `submit` and `benchmark` are marked experimental in their help text. +- Reports now record `agentsec_version`, the version that wrote and scored them, beside the probe's `probe_version`. `--baseline` and `agentsec history` note when it differs, as they already did for the probe. JSON Schemas for the blast-radius report and the `assert` result ship in `agentsec/data/`. +- `agentsec --version` prints the package and probe versions. +- The README said a probe version difference fails `--baseline`. It fails only when a finding is new or more severe, which is what the gate has always done, and a version difference with nothing worse passes with a note. The README and the note now say so. - The README's GitHub Action example pins `@v0.4.0`, the latest release, instead of `@v0.2.0`. - The README opens with a 63-second explainer video: what the probe measures, the `python:3.12-slim` hardening scores, the Antigravity CLI 1.5.2 and `srt` 0.0.81 measurements, and the Harbor grader control task, with each figure taken from a report in `examples/`. - Antigravity CLI 1.5.2 measured, with writes and proxy traffic tested for real by `scripts/check_sandbox_boundaries.py`. Under `--sandbox`, `--dangerously-skip-permissions` now leaves the home directory, its shell startup files and the project writable and scores 100, and the 1.5.1 proxy still accepts tunnels to any hostname. With `proceed-in-sandbox` the score stays 31 and the working directory stays read-only, while files written to the build caches it leaves writable, including `~/.cargo/bin`, persist on the host. `measure_stubbed_agent.py` gains `--script` to run a check in place of the probe. diff --git a/README.md b/README.md index a4dc447..585c7c6 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ agentsec diff reports/accepted.json reports/latest.json # when measuring and agentsec history reports/latest.json --save reports/history.jsonl # keep a line per run and show the trend ``` -Both `--baseline` and `agentsec diff` exit with code 2 and list each finding that is new or rises in severity. The check also lists and fails on any existing finding whose evidence widens by one additional writable path, reachable host, or readable credential. Disappearing findings are marked as fixed alongside a prompt to record a fresh baseline, so the gate retains the improvement. New informational findings scored at 0 points appear as noted and let the check pass, unless the finding reports an unmeasured axis. Mismatched probe versions across the two runs make the tool report the difference and fail, because an added check can produce a new finding in an unchanged sandbox. Record the baseline with the same `--redact` setting that you use on the runs you compare against it. +Both `--baseline` and `agentsec diff` exit with code 2 and list each finding that is new or rises in severity. The check also lists and fails on any existing finding whose evidence widens by one additional writable path, reachable host, or readable credential. Disappearing findings are marked as fixed alongside a prompt to record a fresh baseline, so the gate retains the improvement. New informational findings scored at 0 points appear as noted and let the check pass, unless the finding reports an unmeasured axis. When the two runs used different probe versions, or were scored by different versions of agentsec, the tool reports the difference. A new or more severe finding still fails, because an added check or a rescored finding can appear in an unchanged sandbox, while a version difference with nothing worse passes. Record the baseline with the same `--redact` setting that you use on the runs you compare against it. `agentsec history` tracks one sandbox's score and findings across runs with the `--baseline` comparison, so new findings or reachable credentials surface at the run that introduced them, even under budget. Runs sharing a label overwrite the previous report, so `--save` writes one line per run to a history file. That history file stores whatever each finding reached solely as hashes, which allows committing it without including any names. This command never fails a build because the `--max-score` and `--baseline` flags serve as the build gates in CI. @@ -289,6 +289,8 @@ Filesystem checks confirm that a file is readable by opening it and reading zero The list below shows what is built and what is still open. [`docs/ROADMAP.md`](docs/ROADMAP.md) gives the prioritized plan and what each open item needs. +[`docs/COMPATIBILITY.md`](docs/COMPATIBILITY.md) says what stays the same from one version to the next: the commands, flags and exit codes, the report format, the scoring and the GitHub Action's inputs. `agentsec verify`, `agentsec submit` and `agentsec benchmark` are experimental and outside that promise. `agentsec --version` prints the package and probe versions. + - [x] blast-radius probe, runner (docker / podman / local / command template), scorer, JSON + Markdown reports - [x] ten launcher presets, `matrix` comparison table, `--max-score` CI gate, recommended-flag output, image digests - [x] promptfoo integration: containment assertion, `combine` report, OWASP category overlap diff --git a/agentsec/baseline.py b/agentsec/baseline.py index 4344021..b70d08e 100644 --- a/agentsec/baseline.py +++ b/agentsec/baseline.py @@ -16,8 +16,10 @@ reminder to re-baseline so the gate keeps the ground that was gained. Changing the instrument is not the sandbox changing. When the two runs used -different probe versions, a new finding may be a new check rather than a looser -sandbox; the gate still fails, because it cannot tell which, and says so. +different probe versions, or were scored by different agentsec versions, a new or +more severe finding may come from the instrument rather than a looser sandbox. +The gate still fails on that finding, because it cannot tell which, and says so. +A version difference with nothing worse passes, with a note. """ from __future__ import annotations @@ -93,10 +95,14 @@ def compare(baseline: dict, current: dict) -> dict[str, Any]: redacted = [((e.get("probe") or {}).get("identity") or {}).get("hostname") == "" for e in (baseline, current)] pv_old = (baseline.get("probe") or {}).get("probe_version") pv_new = (current.get("probe") or {}).get("probe_version") + # Reports written before agentsec_version existed carry none; that is not a change. + av_old, av_new = baseline.get("agentsec_version"), current.get("agentsec_version") return {"regressions": regressions, "fixed": fixed, "noted": noted, "score": {"baseline": baseline["summary"]["score"], "current": current["summary"]["score"]}, "probe_versions": {"baseline": pv_old, "current": pv_new}, "instrument_changed": pv_old != pv_new, + "agentsec_versions": {"baseline": av_old, "current": av_new}, + "scorer_changed": bool(av_old and av_new and av_old != av_new), "redaction_differs": redacted[0] != redacted[1]} @@ -121,8 +127,14 @@ def render(result: dict[str, Any], baseline_label: str = "baseline") -> str: if result["instrument_changed"]: pv = result["probe_versions"] lines.append(f" note: baseline was taken with probe {pv['baseline']}, this run with {pv['current']}. " - "A new finding may be a new check rather than a looser sandbox; the gate cannot tell which, " - "so it still fails. Re-baseline deliberately once you have read the difference.") + "A new finding may be a new check rather than a looser sandbox. The gate cannot tell which, " + "so any new or more severe finding still fails it. Re-baseline deliberately once you have " + "read the difference.") + if result.get("scorer_changed"): + av = result["agentsec_versions"] + lines.append(f" note: baseline was scored by agentsec {av['baseline']}, this run by {av['current']}. " + "A change in a finding's severity may come from the newer version rather than the sandbox. " + "The gate still fails on it. Re-baseline deliberately once you have read the difference.") if result.get("redaction_differs"): lines.append(" note: one report is redacted and the other is not, so variable names cannot match. " "Gate a run against a baseline taken with the same --redact setting.") diff --git a/agentsec/cli.py b/agentsec/cli.py index 280e43a..c6116d9 100644 --- a/agentsec/cli.py +++ b/agentsec/cli.py @@ -21,6 +21,7 @@ """ from __future__ import annotations +from agentsec import __version__ import argparse import json import os @@ -149,7 +150,7 @@ def cmd_matrix(args: argparse.Namespace) -> int: print("no presets could run here", file=sys.stderr) return 1 digest = next((r["target"].get("digest") for r in runs if r["target"].get("digest")), None) - env = {"tool": "agentsec-pack", "test": "sandbox-blast-radius-matrix", "schema_version": 1, + env = {"tool": "agentsec-pack", "test": "sandbox-blast-radius-matrix", "schema_version": 1, "agentsec_version": __version__, "image": args.image, "digest": digest, "probe_version": runs[0]["summary"] and runner._probe_version(), "generated_at": int(time.time()), "generated_at_iso": time.strftime("%Y-%m-%d", time.gmtime()), "runs": runs, "skipped": skipped} @@ -248,7 +249,7 @@ def cmd_score(args: argparse.Namespace) -> int: if note: print(f"note: {note}", file=sys.stderr) summary = summarize(probe) - env = {"tool": "agentsec-pack", "test": "sandbox-blast-radius", "schema_version": 1, "label": args.label, + env = {"tool": "agentsec-pack", "test": "sandbox-blast-radius", "schema_version": 1, "agentsec_version": __version__, "label": args.label, "generated_at": int(time.time()), "target": {"kind": "captured", "label": args.label, "how": args.how, "note": "Captured externally: the probe was run inside the target by the means described in `how`, not launched by agentsec."}, @@ -503,13 +504,14 @@ def cmd_assert(args: argparse.Namespace) -> int: if args.out: os.makedirs(os.path.dirname(os.path.abspath(args.out)) or ".", exist_ok=True) with open(args.out, "w") as f: - json.dump({"tool": "agentsec-pack", "test": "path-assertions", "schema_version": 1, + json.dump({"tool": "agentsec-pack", "test": "path-assertions", "schema_version": 1, "agentsec_version": __version__, "generated_at": int(time.time()), "target": target, **outcome}, f, indent=2, sort_keys=True) return 2 if outcome["failed"] else 0 def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="agentsec", description="Adversarial tests for AI agent deployments.") + ap.add_argument("--version", action="version", version=f"agentsec-pack {__version__}, probe {runner._probe_version()}") sub = ap.add_subparsers(dest="cmd", required=True) p = sub.add_parser("presets", help="list named sandbox configurations") @@ -622,7 +624,7 @@ def main(argv: list[str] | None = None) -> int: d.add_argument("current", help="the report JSON to check") d.set_defaults(func=cmd_diff) - sb = sub.add_parser("submit", help="prepare one measurement for a public dataset, shown to you first, for you to post") + sb = sub.add_parser("submit", help="(experimental) prepare one measurement for a public dataset, shown to you first, for you to post") sb.add_argument("report", help="the report JSON") sb.add_argument("--to", default=DATASET, metavar="OWNER/REPO", help=f"the public dataset repository to open the issue in (default: {DATASET})") sb.add_argument("--agent", required=True, help="the agent's name") @@ -632,7 +634,7 @@ def main(argv: list[str] | None = None) -> int: sb.add_argument("--no-browser", action="store_true", help="print the address instead of opening it") sb.set_defaults(func=cmd_submit) - bm = sub.add_parser("benchmark", help="published figures from submitted measurements: a median, and only past a threshold of different accounts") + bm = sub.add_parser("benchmark", help="(experimental) published figures from submitted measurements: a median, and only past a threshold of different accounts") bm.add_argument("--issues", required=True, metavar="FILE", help="the output of gh issue list --json author,body,createdAt,labels") bm.add_argument("--reproduced", metavar="FILE", help="results reproduced by the maintainer or a known harness, shown apart: JSON Lines of record and source") bm.add_argument("--min-submitters", type=int, default=5, metavar="N", help="different accounts a configuration needs before it appears (default: 5, lowest: 3)") @@ -647,7 +649,7 @@ def main(argv: list[str] | None = None) -> int: hi.add_argument("--json", action="store_true", help="print JSON instead of Markdown") hi.set_defaults(func=cmd_history) - v = sub.add_parser("verify", help="did a change pass its tests, or did it change the tests? (exit 2 if not shown to pass)") + v = sub.add_parser("verify", help="(experimental) did a change pass its tests, or did it change the tests? (exit 2 if not shown to pass)") v.add_argument("--base", required=True, help="the commit before the change") v.add_argument("--head", required=True, help="the commit to check") v.add_argument("--test-cmd", required=True, help="the test command, run with sh -c from the root of each tree") diff --git a/agentsec/data/blast-radius-report.schema.json b/agentsec/data/blast-radius-report.schema.json new file mode 100644 index 0000000..4ffde21 --- /dev/null +++ b/agentsec/data/blast-radius-report.schema.json @@ -0,0 +1,82 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/binary-knight/agentsec-pack/blob/main/agentsec/data/blast-radius-report.schema.json", + "title": "agentsec blast-radius report, schema_version 1", + "description": "Written by agentsec probe, blast-radius, score and ui. Fields may be added without changing schema_version; removing, renaming or retyping one changes it. The probe block belongs to the probe and is versioned by probe_version.", + "type": "object", + "required": ["tool", "test", "schema_version", "label", "generated_at", "target", "rc", "summary", "probe", "probe_stderr"], + "properties": { + "tool": {"const": "agentsec-pack"}, + "test": {"const": "sandbox-blast-radius"}, + "schema_version": {"const": 1}, + "agentsec_version": {"type": "string", "description": "The agentsec-pack version that wrote and scored the report. Absent from reports written before 0.5.0."}, + "label": {"type": ["string", "null"]}, + "generated_at": {"type": "integer", "description": "Unix time, seconds."}, + "target": {"$ref": "#/$defs/target"}, + "rc": {"type": "integer", "description": "Exit code of the process that ran the probe."}, + "summary": {"$ref": "#/$defs/summary"}, + "probe": { + "type": "object", + "required": ["probe_version"], + "properties": {"probe_version": {"type": "string"}} + }, + "probe_stderr": {"type": "string"} + }, + "$defs": { + "target": { + "type": "object", + "required": ["kind"], + "properties": { + "kind": {"enum": ["local", "self", "container", "command", "captured"]}, + "label": {"type": ["string", "null"]}, + "how": {"type": ["string", "null"]}, + "note": {"type": "string"}, + "python": {"type": "string"}, + "proxy_auth": {"type": "boolean"}, + "engine": {"type": "string"}, + "image": {"type": "string"}, + "digest": {"type": ["string", "null"]}, + "flags": {"type": "array", "items": {"type": "string"}}, + "preset": {"type": "string"}, + "preset_rationale": {"type": "string"}, + "template": {"type": "string"}, + "command": {"type": ["string", "array"]} + } + }, + "summary": { + "type": "object", + "required": ["score", "raw_score", "finding_count", "by_severity", "recommended_flags", "findings"], + "properties": { + "score": {"type": "integer", "minimum": 0, "maximum": 100, "description": "raw_score capped at 100."}, + "raw_score": {"type": "integer", "minimum": 0, "description": "Sum of finding weights: critical 25, high 15, medium 8, low 3, info 0."}, + "finding_count": {"type": "integer", "minimum": 0}, + "by_severity": { + "type": "object", + "required": ["critical", "high", "medium", "low", "info"], + "properties": { + "critical": {"type": "integer", "minimum": 0}, + "high": {"type": "integer", "minimum": 0}, + "medium": {"type": "integer", "minimum": 0}, + "low": {"type": "integer", "minimum": 0}, + "info": {"type": "integer", "minimum": 0} + } + }, + "recommended_flags": {"type": "array", "items": {"type": "string"}}, + "findings": {"type": "array", "items": {"$ref": "#/$defs/finding"}} + } + }, + "finding": { + "type": "object", + "required": ["id", "title", "severity", "category", "evidence", "owasp", "remediation"], + "properties": { + "id": {"type": "string", "pattern": "^(NET|SEC|FS|PRIV|PROC|RES)-[0-9]{3}$"}, + "title": {"type": "string"}, + "severity": {"enum": ["critical", "high", "medium", "low", "info"]}, + "category": {"enum": ["network", "secrets", "filesystem", "privilege", "process", "resources"]}, + "evidence": {"type": "object"}, + "owasp": {"type": "array", "items": {"type": "string"}}, + "remediation": {"type": "string"} + } + } + } +} diff --git a/agentsec/data/path-assertions.schema.json b/agentsec/data/path-assertions.schema.json new file mode 100644 index 0000000..61f657b --- /dev/null +++ b/agentsec/data/path-assertions.schema.json @@ -0,0 +1,35 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/binary-knight/agentsec-pack/blob/main/agentsec/data/path-assertions.schema.json", + "title": "agentsec assert result, schema_version 1", + "description": "Written by agentsec assert --out. Fields may be added without changing schema_version; removing, renaming or retyping one changes it.", + "type": "object", + "required": ["tool", "test", "schema_version", "generated_at", "target", "rows", "failed", "total"], + "properties": { + "tool": {"const": "agentsec-pack"}, + "test": {"const": "path-assertions"}, + "schema_version": {"const": 1}, + "agentsec_version": {"type": "string", "description": "The agentsec-pack version that wrote the result. Absent from results written before 0.5.0."}, + "generated_at": {"type": "integer", "description": "Unix time, seconds."}, + "target": { + "type": "object", + "required": ["kind"], + "properties": {"kind": {"type": "string"}, "command": {"type": "string"}} + }, + "rows": { + "type": "array", + "items": { + "type": "object", + "required": ["kind", "path", "ok", "observed"], + "properties": { + "kind": {"enum": ["readable", "not-readable", "writable", "not-writable", "exists", "not-exists"]}, + "path": {"type": "string"}, + "ok": {"type": "boolean"}, + "observed": {"type": "string", "description": "What the probe saw, such as absent or present, denied."} + } + } + }, + "failed": {"type": "integer", "minimum": 0}, + "total": {"type": "integer", "minimum": 0} + } +} diff --git a/agentsec/history.py b/agentsec/history.py index b7f1ddd..c69e32f 100644 --- a/agentsec/history.py +++ b/agentsec/history.py @@ -116,7 +116,9 @@ def build(entries: list[dict[str, Any]], max_score: int | None = None) -> dict[s runs.append({"generated_at": cur["generated_at"], "score": cur["summary"]["score"], "probe_version": cur["probe"].get("probe_version"), "findings": sorted(f["id"] for f in cur["summary"]["findings"]), "change": step and {"regressions": step["regressions"], "fixed": step["fixed"], - "instrument_changed": step["instrument_changed"], "redaction_differs": step["redaction_differs"]}}) + "instrument_changed": step["instrument_changed"], + "scorer_changed": step.get("scorer_changed", False), + "redaction_differs": step["redaction_differs"]}}) scores = [r["score"] for r in runs] out[label] = {"runs": runs, "first": scores[0], "last": scores[-1], "highest": max(scores), "worsened_since_first": any(r["change"] and r["change"]["regressions"] for r in runs), @@ -138,6 +140,8 @@ def _describe(change: dict[str, Any] | None) -> str: parts += [f"gone {f['id']}" for f in change["fixed"]] if change["instrument_changed"]: parts.append("probe changed, so this step may be a new check") + if change.get("scorer_changed"): + parts.append("agentsec version changed, so a severity may have been rescored") if change["redaction_differs"]: parts.append("only one of these runs is redacted") return "; ".join(parts) diff --git a/agentsec/integrations/promptfoo_combine.py b/agentsec/integrations/promptfoo_combine.py index 796332c..6fb7232 100644 --- a/agentsec/integrations/promptfoo_combine.py +++ b/agentsec/integrations/promptfoo_combine.py @@ -11,6 +11,7 @@ """ from __future__ import annotations +from agentsec import __version__ import json import re from importlib import resources @@ -108,7 +109,7 @@ def combine(pf: dict[str, Any], sandbox: dict[str, Any], deployed_in: str) -> di if hits: overlap.append({"asi": cat, "failed_tests": [r["description"] for r in pfs["failed_rows"] if cat in r.get("asi", [])][:5], "sandbox_findings": [{"id": f["id"], "title": f["title"], "severity": f["severity"]} for f in hits]}) - return {"tool": "agentsec-pack", "test": "promptfoo-sandbox-combined", "schema_version": 1, + return {"tool": "agentsec-pack", "test": "promptfoo-sandbox-combined", "schema_version": 1, "agentsec_version": __version__, "overlap": overlap, "failed_asi": failed_asi, "assumption": {"stated_by": "operator", "deployed_in": deployed_in, "text": ("The agent evaluated by promptfoo runs in the sandbox measured here. " diff --git a/agentsec/runner.py b/agentsec/runner.py index 320de55..9654cba 100644 --- a/agentsec/runner.py +++ b/agentsec/runner.py @@ -11,6 +11,7 @@ """ from __future__ import annotations +from agentsec import __version__ import json import os import shlex @@ -176,7 +177,7 @@ def run_command(template: str, timeout: int = DEFAULT_TIMEOUT) -> dict[str, Any] def result_envelope(run: dict[str, Any], summary: dict[str, Any], label: str | None = None) -> dict[str, Any]: - return {"tool": "agentsec-pack", "test": "sandbox-blast-radius", "schema_version": 1, "label": label, + return {"tool": "agentsec-pack", "test": "sandbox-blast-radius", "schema_version": 1, "agentsec_version": __version__, "label": label, "generated_at": int(time.time()), "target": run["target"], "rc": run["rc"], "summary": summary, "probe": run["probe"], "probe_stderr": run.get("stderr", "")} diff --git a/agentsec/ui/server.py b/agentsec/ui/server.py index 8a17af4..03e094a 100644 --- a/agentsec/ui/server.py +++ b/agentsec/ui/server.py @@ -22,6 +22,7 @@ """ from __future__ import annotations +from agentsec import __version__ import json import re import secrets @@ -91,7 +92,7 @@ def score(self, label: str, how: str, raw: str) -> dict[str, Any]: if not label or not how: raise ValueError("a capture needs a label and a record of how it was run") probe, repaired = _parse_probe(raw) - env = {"tool": "agentsec-pack", "test": "sandbox-blast-radius", "schema_version": 1, + env = {"tool": "agentsec-pack", "test": "sandbox-blast-radius", "schema_version": 1, "agentsec_version": __version__, "label": label, "generated_at": int(time.time()), "target": {"kind": "captured", "label": label, "how": how, "note": "Captured externally: the probe was run inside the target by the means " diff --git a/agentsec/verify.py b/agentsec/verify.py index c4b637d..9a3f4fc 100644 --- a/agentsec/verify.py +++ b/agentsec/verify.py @@ -44,6 +44,7 @@ """ from __future__ import annotations +from agentsec import __version__ import ast import dataclasses import difflib @@ -880,7 +881,7 @@ def check_planted(work: Path, final: str) -> tuple[str, list[Finding], dict[str, summary = {"verdict": verdict, "score": min(100, sum(f.weight for f in findings)), "finding_count": len(findings), "by_severity": {s: sum(1 for f in findings if f.severity == s) for s in SEVERITY_WEIGHT}, "findings": [dataclasses.asdict(f) for f in findings]} - return {"tool": "agentsec-pack", "test": "verifier-integrity", "schema_version": 1, "generated_at": int(time.time()), + return {"tool": "agentsec-pack", "test": "verifier-integrity", "schema_version": 1, "agentsec_version": __version__, "generated_at": int(time.time()), "target": {"repo": repo, "base": base_sha, "head": head_sha, "test_cmd": test_cmd, "image": image, "engine": engine if image else None, "flags": flags or [], "junit": junit}, "changes": {"added": ch.added, "modified": ch.modified, "deleted": ch.deleted, diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md new file mode 100644 index 0000000..418cd8e --- /dev/null +++ b/docs/COMPATIBILITY.md @@ -0,0 +1,52 @@ +# Compatibility + +A build that gates on `agentsec` should not start failing because `agentsec` was upgraded, unless the upgrade says so. This page states what stays the same from one version to the next and how the rest can change. Each promise here has a test in `tests/test_compatibility.py` that fails if the promise breaks. + +From 1.0 on, the promises below hold for every 1.x release, and anything that breaks one waits for 2.0. Releases before 1.0 follow them as far as they can, and the changelog names any exception. + +## What is covered + +**Commands and flags.** `presets`, `probe`, `blast-radius`, `matrix`, `score`, `assert`, `diff`, `history`, `report`, `chart`, `ui`, `combine` and `compare` keep their names and flags. A new flag is optional, and leaving it out keeps the earlier behavior. + +**Exit codes.** + +| Code | Meaning | +|---:|---| +| 0 | The command ran, and any gate it was given passed. | +| 2 | A gate failed: `--max-score`, `--baseline`, `agentsec diff`, or an `agentsec assert` expectation. | +| 1 | The command could not run, for example because the sandbox did not start or an input was missing. | + +**Report files.** Two JSON formats are fixed by schemas that ship with the package: + +- `agentsec/data/blast-radius-report.schema.json`, for what `probe`, `blast-radius`, `score` and `ui` write +- `agentsec/data/path-assertions.schema.json`, for what `assert --out` writes + +Both carry `schema_version` 1. A field can be added without changing it, so a reader should ignore fields it does not know. Removing, renaming or changing the type of a field raises `schema_version`, and only in a new major version. The `probe` block inside a report belongs to the probe. Its contents are versioned by `probe_version`, and only `probe_version` itself is covered here. + +**Scoring.** Each finding has a severity with a fixed weight: critical 25, high 15, medium 8, low 3, info 0. The score is the sum of the weights, capped at 100, and `raw_score` is the uncapped sum. A finding ID is never reused or given a different meaning. Most findings have one severity. Two take theirs from the evidence by a fixed rule: + +- FS-001 is high when `/`, `/etc`, `/usr/bin` or `/usr/local/bin` is writable, and medium for other system paths. +- PRIV-003 takes the severity of the most dangerous Linux capability in the effective set. + +Changing a weight, the severity of an existing finding, or either of those rules needs a new major version. + +**The GitHub Action.** The inputs and outputs in `action.yml` keep their names and meaning. A new input is optional, and its default keeps the earlier behavior. + +## How a score can still change + +A score on an unchanged sandbox can change between minor versions in two ways, and each report records which versions produced it. + +- **A new check.** The probe learns to test something it did not test before, which can add a finding. This ships with a new `probe_version`, and the changelog lists the new finding IDs. +- **A corrected check.** A check that reported something wrongly is fixed, as when probe 0.7.0 stopped counting a connection refused during TLS as reached. The changelog says what changed and why. + +`--baseline` compares `probe_version` and `agentsec_version` between the baseline and the new run. When either differs, it says so. A new or more severe finding still fails the gate, because the gate cannot tell a new check from a looser sandbox. A version difference with nothing worse passes. The README's `--baseline` section describes the rest of the comparison. + +To control when a new check reaches a build, pin the package version, or pin the Action to a release tag. + +## What is not covered + +- **Experimental commands.** `verify`, `submit` and `benchmark` can change in any release. Their help text says so. +- **Human-readable output.** Terminal text, Markdown, HTML and SVG can change in any release. Read the JSON reports and exit codes instead. +- **Other JSON.** `matrix`, `combine` and `verify` write JSON that no schema covers yet. +- **The Python modules.** `agentsec` is used through its command line and its Action. Importing its modules works, but their functions and classes can change in any release. +- **Measured profiles.** The reports in `examples/` record what a sandbox did on the day it was measured. A vendor's next release can change it. diff --git a/pyproject.toml b/pyproject.toml index 6aa6c4b..2a53255 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,13 +9,28 @@ description = "Measure what an AI agent's sandbox lets it reach: network, secret readme = "README.md" requires-python = ">=3.10" license = {text = "MIT"} +classifiers = [ + "Development Status :: 4 - Beta", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: MacOS", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Security", + "Topic :: Software Development :: Testing", +] dependencies = [] [project.scripts] agentsec = "agentsec.cli:main" [project.optional-dependencies] -dev = ["pytest>=7"] +dev = ["pytest>=7", "jsonschema>=4.18"] # Run in CI as the free stand-ins for the GitHub Advanced Security features # a private repo on this plan cannot enable. See SECURITY.md. security = ["detect-secrets>=1.5", "pip-audit>=2.7", "bandit>=1.7"] diff --git a/tests/fixtures/cli_surface.json b/tests/fixtures/cli_surface.json new file mode 100644 index 0000000..8f6559f --- /dev/null +++ b/tests/fixtures/cli_surface.json @@ -0,0 +1,90 @@ +{ + "assert": [ + "--exists", + "--image", + "--kind", + "--not-exists", + "--not-readable", + "--not-writable", + "--out", + "--python", + "--readable", + "--template", + "--timeout", + "--writable" + ], + "blast-radius": [ + "--baseline", + "--image", + "--label", + "--max-score", + "--out", + "--print-findings", + "--python", + "--redact", + "--template", + "--timeout" + ], + "chart": [ + "--out", + "--sort", + "--subtitle", + "--theme", + "--title" + ], + "combine": [ + "--deployed-in", + "--label", + "--out", + "--promptfoo", + "--sandbox" + ], + "compare": [], + "diff": [], + "history": [ + "--json", + "--label", + "--max-score", + "--save" + ], + "matrix": [ + "--label", + "--max-score", + "--out", + "--presets", + "--redact", + "--timeout" + ], + "presets": [ + "--verbose" + ], + "probe": [ + "--baseline", + "--how", + "--label", + "--max-score", + "--out", + "--proxy-auth", + "--redact", + "--timeout" + ], + "report": [ + "--out" + ], + "score": [ + "--baseline", + "--how", + "--label", + "--max-score", + "--out", + "--print-findings", + "--redact" + ], + "ui": [ + "--allow-remote-runs", + "--bind", + "--open", + "--port", + "--results" + ] +} \ No newline at end of file diff --git a/tests/test_compatibility.py b/tests/test_compatibility.py new file mode 100644 index 0000000..3486394 --- /dev/null +++ b/tests/test_compatibility.py @@ -0,0 +1,215 @@ +"""The promises in docs/COMPATIBILITY.md, each as a test that fails if it breaks.""" +import copy +import json +import re +from pathlib import Path + +import jsonschema +import pytest + +from agentsec import __version__ +from agentsec import baseline as bl +from agentsec import scoring +from agentsec.cli import main + +ROOT = Path(__file__).resolve().parent.parent +DATA = ROOT / "agentsec" / "data" +SCORING_SRC = (ROOT / "agentsec" / "scoring.py").read_text() + + +def _schema(name): + schema = json.loads((DATA / name).read_text()) + jsonschema.Draft202012Validator.check_schema(schema) + return schema + + +def _example_reports(): + out = [] + for p in sorted((ROOT / "examples").rglob("*.json")): + d = json.loads(p.read_text()) + if isinstance(d, dict) and d.get("test") == "sandbox-blast-radius": + out.append(p) + return out + + +REPORTS = _example_reports() + + +def test_examples_exist(): + assert len(REPORTS) >= 50 + + +@pytest.mark.parametrize("path", REPORTS, ids=lambda p: str(p.relative_to(ROOT))) +def test_every_example_report_matches_the_schema(path): + jsonschema.validate(json.loads(path.read_text()), _schema("blast-radius-report.schema.json")) + + +def test_the_schema_declares_every_field_the_examples_use(): + """additionalProperties stays open for readers, so this is what catches an undocumented field.""" + schema = _schema("blast-radius-report.schema.json") + declared = { + "envelope": set(schema["properties"]), + "target": set(schema["$defs"]["target"]["properties"]), + "summary": set(schema["$defs"]["summary"]["properties"]), + "finding": set(schema["$defs"]["finding"]["properties"]), + } + seen = {k: set() for k in declared} + for p in REPORTS: + d = json.loads(p.read_text()) + seen["envelope"] |= set(d) + seen["target"] |= set(d["target"]) + seen["summary"] |= set(d["summary"]) + for f in d["summary"]["findings"]: + seen["finding"] |= set(f) + for part in declared: + assert seen[part] <= declared[part], f"{part}: undeclared {sorted(seen[part] - declared[part])}" + + +def test_a_fresh_report_matches_the_schema_and_records_the_version(tmp_path): + src = REPORTS[0] + probe = json.loads(src.read_text())["probe"] + pf = tmp_path / "probe.json" + pf.write_text(json.dumps(probe)) + out = tmp_path / "r" + main(["score", str(pf), "--label", "fresh", "--how", "test", "--out", str(out)]) + report = json.loads((out / "fresh.json").read_text()) + jsonschema.validate(report, _schema("blast-radius-report.schema.json")) + assert report["agentsec_version"] == __version__ + + +def test_an_assert_result_matches_its_schema(tmp_path): + readable = tmp_path / "f.txt" + readable.write_text("x") + out = tmp_path / "assert.json" + main(["assert", "--readable", str(readable), "--not-readable", str(tmp_path / "absent"), "--out", str(out)]) + result = json.loads(out.read_text()) + jsonschema.validate(result, _schema("path-assertions.schema.json")) + assert result["agentsec_version"] == __version__ + + +def test_the_weights_are_the_documented_ones(): + assert scoring.SEVERITY_WEIGHT == {"critical": 25, "high": 15, "medium": 8, "low": 3, "info": 0} + + +def test_the_score_is_the_raw_score_capped_at_100(): + f = scoring.Finding("NET-001", "t", "critical", "network") + assert scoring.score([f] * 5) == 100 + assert scoring.raw_score([f] * 5) == 125 + + +def _constructed(): + """Each finding id the scorer can emit, with the severity argument as written.""" + found = {} + for m in re.finditer(r'_f\(\s*"([A-Z]+-\d{3})",\s*(?:\(?\s*f?"(?:[^"\\]|\\.)*"\s*)+\)?,\s*([^,]+),', SCORING_SRC): + found.setdefault(m.group(1), set()).add(m.group(2).strip()) + return found + + +def test_every_finding_id_fits_the_schema(): + schema = _schema("blast-radius-report.schema.json") + pattern = re.compile(schema["$defs"]["finding"]["properties"]["id"]["pattern"]) + ids = set(re.findall(r'_f\(\s*"([A-Z]+-\d{3})"', SCORING_SRC)) + assert ids and all(pattern.match(i) for i in ids) + assert set(_constructed()) == ids + + +def test_only_the_documented_findings_take_their_severity_from_evidence(): + variable = sorted(i for i, sev in _constructed().items() + if len(sev) > 1 or not re.fullmatch(r'"(critical|high|medium|low|info)"', next(iter(sev)))) + assert variable == ["FS-001", "PRIV-003"], "update docs/COMPATIBILITY.md if this list changes" + + +def test_a_version_difference_alone_passes_the_baseline_gate_with_a_note(): + base = json.loads((ROOT / "examples" / "slim_hardened_online.json").read_text()) + cur = copy.deepcopy(base) + cur["probe"]["probe_version"] = "9.9.9" + base["agentsec_version"], cur["agentsec_version"] = "0.4.0", "9.9.9" + result = bl.compare(base, cur) + assert result["regressions"] == [] + assert result["instrument_changed"] and result["scorer_changed"] + text = bl.render(result) + assert "probe 0.4.0" in text and "agentsec 0.4.0" in text and text.endswith("OK: nothing is worse than the baseline") + + +def test_a_rescored_severity_still_fails_the_baseline_gate(): + base = json.loads((ROOT / "examples" / "slim_hardened_online.json").read_text()) + cur = copy.deepcopy(base) + f = next(f for f in cur["summary"]["findings"] if f["severity"] != "critical") + f["severity"] = "critical" + base["agentsec_version"], cur["agentsec_version"] = "0.4.0", "9.9.9" + result = bl.compare(base, cur) + assert [r["kind"] for r in result["regressions"]] == ["severity"] + + +def test_a_report_without_agentsec_version_is_not_a_change(): + base = json.loads((ROOT / "examples" / "slim_hardened_online.json").read_text()) + cur = copy.deepcopy(base) + cur["agentsec_version"] = __version__ + assert bl.compare(base, cur)["scorer_changed"] is False + + +def test_version_flag(capsys): + with pytest.raises(SystemExit) as e: + main(["--version"]) + assert e.value.code == 0 + out = capsys.readouterr().out + assert out.startswith(f"agentsec-pack {__version__}, probe ") + + +def test_experimental_commands_say_so(capsys): + with pytest.raises(SystemExit): + main(["--help"]) + help_text = capsys.readouterr().out + for cmd in ("verify", "submit", "benchmark"): + line = next(l for l in help_text.splitlines() if l.strip().startswith(cmd + " ") or l.strip() == cmd) + idx = help_text.splitlines().index(line) + assert "(experimental)" in " ".join(help_text.splitlines()[idx:idx + 2]), cmd + + +STABLE = ["presets", "probe", "blast-radius", "matrix", "score", "assert", "diff", "history", "report", "chart", "ui", + "combine", "compare"] + + +def _flags(cmd): + import contextlib + import io + buf = io.StringIO() + with contextlib.redirect_stdout(buf), contextlib.suppress(SystemExit): + main([cmd, "--help"]) + assert f"usage: agentsec {cmd}" in buf.getvalue(), f"agentsec {cmd} is gone" + return sorted(set(re.findall(r"(?