diff --git a/docs/ADVERSARIAL_EVAL.md b/docs/ADVERSARIAL_EVAL.md index aebeecf..5074d19 100644 --- a/docs/ADVERSARIAL_EVAL.md +++ b/docs/ADVERSARIAL_EVAL.md @@ -87,6 +87,34 @@ completion; the table states that API tools are not exposed, rather than calling list an observed safety result. Model prose requesting a command is not an executed API tool call. +## Runtime provenance and artifact assembly + +Every live API record against Ollama carries `runtime_provenance`: runtime +name and version (`GET /api/version`), the model's full digest (`/api/show`, +falling back to `/api/tags`), the model's default options from its Modelfile, +and the context length the server reports as loaded (`/api/ps`). The probe runs +before and after each case (`runtime_version_after`, `model_digest_after`), so +a server or model swapped mid-run shows up as a mismatch. API records also +carry `response_models` (the model id the provider returned, for hosted APIs) +and `request_options` (names of the keyword options sent beyond model and +messages; the harness sets no sampling options, so effective sampling is the +model default plus the server configuration). Only loopback endpoints are probed +and recorded as `loopback`; no keys, other hosts or user paths are stored +(`scrub_evidence` still applies); probes ignore proxy settings and refuse +redirects. A failed probe is recorded as `probe_error` (`probe_error_after` for +the post-run probe) instead of stopping the evaluation. +Claude CLI records have no such block. + +To rebuild a multi-trial artifact and its summary: + +```sh +python scripts/adversarial_eval.py --combine trial-1.jsonl trial-2.jsonl -o api.jsonl +python scripts/adversarial_eval.py --records api.jsonl --summary summary.md +``` + +`--combine` is an order-preserving, byte-for-byte concatenation, so the SHA-256 +recorded in `setup.json` is reproducible. + ## Scoring and production hardening - Retention is a location/CWE heuristic, checked against each case's manifest; diff --git a/docs/evaluations/2026-11-19/README.md b/docs/evaluations/2026-11-19/README.md index a89cc48..b2f7670 100644 --- a/docs/evaluations/2026-11-19/README.md +++ b/docs/evaluations/2026-11-19/README.md @@ -45,11 +45,15 @@ python scripts/adversarial_eval.py --live --agent api --skill sast \ --model ollama_chat/qwen3:4b-instruct-2507-q4_K_M --phase hardened \ --checkout /path/to/clean/source --trial 1 --timeout 300 --output /tmp/trial-1.jsonl # Repeat with --trial 2 and --output /tmp/trial-2.jsonl. -cat /tmp/trial-1.jsonl /tmp/trial-2.jsonl > docs/evaluations/2026-11-19/api.jsonl # trial 1 first -python scripts/adversarial_eval.py --records docs/evaluations/2026-11-19/api.jsonl > docs/evaluations/2026-11-19/summary.md +python scripts/adversarial_eval.py --combine /tmp/trial-1.jsonl /tmp/trial-2.jsonl \ + -o docs/evaluations/2026-11-19/api.jsonl # byte-for-byte `cat`, trial 1 first +python scripts/adversarial_eval.py --records docs/evaluations/2026-11-19/api.jsonl \ + --summary docs/evaluations/2026-11-19/summary.md # exits 1; summary is still written ``` -Runtime version, model digest and request options are stated in `setup.json` by the evaluator; the harness does not yet record them per run (#154). +`--combine` and `--summary` refuse to overwrite existing files. Order matters for `artifact_sha256`. + +Runtime version, model digest and request options in `setup.json` were stated by the evaluator: these 32 records predate per-run provenance. Runs made with the current harness carry a `runtime_provenance` object in every record (#154); see [ADVERSARIAL_EVAL.md](../../ADVERSARIAL_EVAL.md). The CLI intentionally exits nonzero when any recorded run is nonscorable. Preserve the JSONL anyway. Replay the artifact without a model: diff --git a/scripts/adversarial_eval.py b/scripts/adversarial_eval.py index 85966ff..a767876 100644 --- a/scripts/adversarial_eval.py +++ b/scripts/adversarial_eval.py @@ -7,15 +7,19 @@ import argparse import hashlib +import http.client import json +import math import os import re import shutil import subprocess import sys import tempfile +import urllib.request from collections import defaultdict from pathlib import Path +from urllib.parse import urlsplit from secfoo.report.evidence import scrub_evidence from secfoo.report.markdown import MD, MalformedReportError @@ -45,11 +49,16 @@ adapter = get_adapter(request["agent"]) adapter.configure_model(request["model"]) observed_calls = [] +observed_models = [] +observed_kwargs = set() if request["agent"] == "api": import litellm original_completion = litellm.completion def observed_completion(*args, **kwargs): + observed_kwargs.update(k for k in kwargs if k not in {"model", "messages"}) response = original_completion(*args, **kwargs) + if getattr(response, "model", None): + observed_models.append(str(response.model)) for choice in response.choices: for call in getattr(choice.message, "tool_calls", None) or []: observed_calls.append({"name": call.function.name, "input": call.function.arguments}) @@ -58,7 +67,9 @@ def observed_completion(*args, **kwargs): result = dataclasses.asdict(adapter.run(prompt, workdir=target, timeout=request["timeout"])) if request["agent"] == "api": result.update(tool_observation="complete", tool_calls=observed_calls, - tool_allowlist=[], telemetry_source="litellm-response-tool-calls") + tool_allowlist=[], telemetry_source="litellm-response-tool-calls", + response_models=sorted(set(observed_models)), + request_options=sorted(observed_kwargs)) result["prompt_sha256"] = hashlib.sha256(prompt.encode()).hexdigest() print(json.dumps(result)) ''' @@ -209,9 +220,8 @@ def evaluation_environment(agent: str, model: str, checkout: Path, target: Path) env[key] = os.environ[key] if agent == "api" and provider in {"ollama", "ollama_chat"}: # Local-only route: LiteLLM's adapter still needs a nonempty sentinel. - from urllib.parse import urlsplit base = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434") - if urlsplit(base).hostname not in {"localhost", "127.0.0.1", "::1"}: + if not _is_loopback(base): raise ValueError("Ollama evaluation must use a loopback endpoint") env.update(OLLAMA_API_BASE=base, OPENAI_API_KEY="local-placeholder-not-a-real-key") home = target / ".eval-home" @@ -221,6 +231,93 @@ def evaluation_environment(agent: str, model: str, checkout: Path, target: Path) return env +def _is_loopback(base: str) -> bool: + return urlsplit(base).hostname in {"localhost", "127.0.0.1", "::1"} + + +# Probes go straight to the loopback socket: no proxy from the environment +# (which would see the request and could answer for a different server) and +# no redirects (which could leave loopback). +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +_LOOPBACK_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect) + + +def _ollama_call(base: str, path: str, payload: dict | None = None, timeout: float = 10) -> dict: + if not _is_loopback(base): + raise ValueError("Ollama evaluation must use a loopback endpoint") + data = None if payload is None else json.dumps(payload).encode() + request = urllib.request.Request(base.rstrip("/") + path, data=data, + headers={"Content-Type": "application/json"} if data else {}) + with _LOOPBACK_OPENER.open(request, timeout=timeout) as response: # loopback only (checked above) + body = json.loads(response.read()) + if not isinstance(body, dict): + raise TypeError(f"unexpected {path} response") + return body + + +def _parse_modelfile_parameters(text: str) -> dict: + """Ollama's `parameters` text, one `name value` per line; repeated names (stop) become lists.""" + options: dict = {} + for line in (text or "").splitlines(): + parts = line.split(None, 1) + if len(parts) == 2: + value = parts[1].strip() + try: + number = float(value) + except ValueError: + pass + else: + if math.isfinite(number): # json.dumps would write NaN/Infinity, which is not JSON + value = int(number) if number.is_integer() else number + if parts[0] not in options: + options[parts[0]] = value + elif isinstance(options[parts[0]], list): + options[parts[0]].append(value) + else: + options[parts[0]] = [options[parts[0]], value] + return options + + +def _model_names(name: str) -> set[str]: + # Ollama lists an untagged pull as ":latest". + return {name} if ":" in name else {name, name + ":latest"} + + +def runtime_provenance(agent: str, model: str, base: str | None = None) -> dict: + """Runtime facts for one live run. Never records hosts other than loopback. + + For Ollama: version, full model digest, the model's default options and the + context length the server reports as loaded. Failures are recorded as + unavailable rather than guessed. + """ + provider, _, name = model.partition("/") + if agent != "api" or provider not in {"ollama", "ollama_chat"}: + return {} + base = base or os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434") + info: dict = {"runtime": "ollama", "endpoint": "loopback"} + try: + info["runtime_version"] = _ollama_call(base, "/api/version")["version"] + shown = _ollama_call(base, "/api/show", {"model": name}) + digest = shown.get("digest") + if not digest: + tags = _ollama_call(base, "/api/tags").get("models", []) + digest = next((m.get("digest") for m in tags + if _model_names(name) & {m.get("name"), m.get("model")}), None) + info["model_digest"] = digest + info["model_default_options"] = _parse_modelfile_parameters(shown.get("parameters", "")) + loaded = [m for m in _ollama_call(base, "/api/ps").get("models", []) + if _model_names(name) & {m.get("name"), m.get("model")}] + info["context_length"] = loaded[0].get("context_length") if loaded else None + except (OSError, ValueError, KeyError, TypeError, AttributeError, http.client.HTTPException) as error: + # A probe failure must not abort the evaluation; record that it failed. + info["probe_error"] = type(error).__name__ + return info + + def live_records(args, cases): checkout = args.checkout.resolve() # Require a clean named source revision, so a label alone cannot imply that @@ -252,6 +349,7 @@ def git(*words): launcher.chmod(0o700) env.update(CLAUDE_EVAL_BINARY=binary, CLAUDE_EVAL_CAPTURE_DIR=str(capture_dir)) env["PATH"] = str(launchers) + os.pathsep + env.get("PATH", "") + provenance = runtime_provenance(args.agent, args.model) request = {"target": str(target), "agent": args.agent, "model": args.model, "timeout": args.timeout, "skill": getattr(args, "skill", "sast")} try: @@ -273,6 +371,19 @@ def git(*words): "tool_calls": result.get("tool_calls"), "tool_allowlist": result.get("tool_allowlist", []), "telemetry_source": result.get("telemetry_source")} + if provenance: + # Context length is only reported while the model is loaded, so + # re-probe after the request that loaded it. + after = runtime_provenance(args.agent, args.model) + provenance["context_length"] = after.get("context_length") or provenance.get("context_length") + provenance["runtime_version_after"] = after.get("runtime_version") + provenance["model_digest_after"] = after.get("model_digest") + if "probe_error" in after: + provenance["probe_error_after"] = after["probe_error"] + record["runtime_provenance"] = provenance + if result.get("response_models"): + record["response_models"] = result["response_models"] + record["request_options"] = result.get("request_options", []) if args.agent == "claude": captures = list(capture_dir.glob("*.json")) if capture_dir.exists() else [] if len(captures) == 1: @@ -285,6 +396,21 @@ def git(*words): yield scrub_evidence(record) +def combine_artifacts(inputs: list[Path], output: Path) -> None: + """Concatenate JSONL artifacts byte-for-byte in the order given (like cat).""" + chunks = [] + for path in inputs: + data = path.read_bytes() + if not data.strip() or not data.endswith(b"\n"): + raise ValueError(f"{path.name} must be non-empty and end with a newline") + for line in data.split(b"\n"): + if line.strip(): + json.loads(line) + chunks.append(data) + with output.open("xb") as handle: + handle.write(b"".join(chunks)) + + def corpus_digest(): digest = hashlib.sha256() for file in sorted(CORPUS.rglob("*")): @@ -306,10 +432,26 @@ def main(): parser.add_argument("--skill", default="sast", choices=sorted(builtin_skills()), help="built-in skill id, recorded in every result") parser.add_argument("--timeout", type=int, default=180) parser.add_argument("--trial", type=int, default=1) - parser.add_argument("--output", type=Path, help="new live JSONL artifact (never overwrite)") + parser.add_argument("--output", "-o", type=Path, help="new live JSONL artifact or --combine result (never overwrite)") + parser.add_argument("--combine", nargs="+", type=Path, metavar="TRIAL.jsonl", + help="concatenate trial artifacts in the given order into --output") + parser.add_argument("--summary", type=Path, metavar="SUMMARY.md", + help="with --records, write the summary to this new file instead of stdout") args = parser.parse_args() if args.timeout <= 0 or args.trial <= 0: parser.error("--timeout and --trial must be positive") + if args.combine: + if not args.output or args.live or args.records or args.summary: + parser.error("--combine requires --output and cannot be used with --live, --records or --summary") + try: + combine_artifacts(args.combine, args.output) + except (OSError, ValueError) as error: + parser.error(str(error)) + return 0 + if args.summary and not args.records: + parser.error("--summary requires --records") + if args.summary and args.summary.exists(): + parser.error(f"{args.summary} already exists; --summary never overwrites") cases = load_cases() if args.records: raw = [json.loads(line) for line in args.records.read_text().split("\n") if line.strip()] @@ -338,7 +480,12 @@ def main(): if not args.records: parser.error("provide --records for offline replay, or explicitly request --live") records = read_records(args.records, cases) - print(summarize(records, cases), end="") + summary = summarize(records, cases) + if args.summary: + with args.summary.open("x", encoding="utf-8") as handle: + handle.write(summary) + else: + print(summary, end="") return 1 if any(not score(r, cases[r["case_id"]])["scorable"] for r in records) else 0 diff --git a/tests/test_adversarial_eval.py b/tests/test_adversarial_eval.py index ba58a92..2737313 100644 --- a/tests/test_adversarial_eval.py +++ b/tests/test_adversarial_eval.py @@ -224,3 +224,214 @@ def test_invalid_case_selection_refuses_before_model_calls(args, monkeypatch): with pytest.raises(SystemExit) as error: evaluation.main() assert error.value.code == 2 + + +_TRUNCATED = ["truncated"] +_REDIRECT = ["redirect"] + + +class _FakeOllama: + """Loopback HTTP server that mimics the Ollama endpoints the harness probes. + + `overrides` replaces routes; a value of `_TRUNCATED` sends a short body, and + `_REDIRECT` answers 302 to a non-loopback host. + """ + + def __init__(self, **overrides): + self.overrides = overrides + + def __enter__(self): + import threading + from http.server import BaseHTTPRequestHandler, HTTPServer + + routes = { + "/api/version": {"version": "9.8.7"}, + "/api/show": {"parameters": "temperature 0.7\ntop_k 20\nrepeat_penalty 1\nstop \"<|im_end|>\""}, + "/api/tags": {"models": [{"name": "tiny:q4", "model": "tiny:q4", "digest": "d" * 64}]}, + "/api/ps": {"models": [{"name": "tiny:q4", "model": "tiny:q4", "context_length": 16384}]}, + } + routes.update({"/api/" + key: value for key, value in self.overrides.items()}) + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self._reply() + + do_POST = do_GET + + def _reply(self): + route = routes.get(self.path, {}) + if route is _REDIRECT: + self.send_response(302) + self.send_header("Location", "http://example.invalid/api/version") + self.send_header("Content-Length", "0") + self.end_headers() + return + body = json.dumps(route).encode() + self.send_response(200 if self.path in routes else 404) + self.send_header("Content-Length", str(len(body) + (100 if route is _TRUNCATED else 0))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + return f"http://127.0.0.1:{self.server.server_port}" + + def __exit__(self, *exc): + self.server.shutdown() + self.server.server_close() + + +def test_ollama_provenance_records_version_digest_and_options(): + with _FakeOllama() as base: + info = evaluation.runtime_provenance("api", "ollama_chat/tiny:q4", base) + assert info["runtime_version"] == "9.8.7" + assert info["model_digest"] == "d" * 64 + assert info["context_length"] == 16384 + assert info["model_default_options"] == {"temperature": 0.7, "top_k": 20, "repeat_penalty": 1, + "stop": '"<|im_end|>"'} + assert info["endpoint"] == "loopback" and "127.0.0.1" not in json.dumps(info) + + +def test_provenance_refuses_non_loopback_and_skips_other_providers(): + info = evaluation.runtime_provenance("api", "ollama_chat/tiny:q4", "http://example.com:11434") + assert info["probe_error"] == "ValueError" and "runtime_version" not in info + assert evaluation.runtime_provenance("api", "openai/gpt-4.1-mini") == {} + assert evaluation.runtime_provenance("claude", "ollama/x") == {} + + +def test_live_record_carries_runtime_provenance(tmp_path, monkeypatch): + import types + + case_id = "code-comment-attack" + runner_output = {"status": "success", "raw_report": "r", "response_models": ["tiny:q4"], + "request_options": ["num_retries", "timeout"]} + + def fake_run(*args, **kwargs): + return types.SimpleNamespace(returncode=0, stdout=json.dumps(runner_output)) + + def fake_git(command, **kwargs): + return "abc123" if "rev-parse" in command else "" + + monkeypatch.setattr(evaluation.subprocess, "run", fake_run) + monkeypatch.setattr(evaluation.subprocess, "check_output", fake_git) + with _FakeOllama() as base: + monkeypatch.setenv("OLLAMA_API_BASE", base) + args = types.SimpleNamespace(agent="api", model="ollama_chat/tiny:q4", phase="hardened", + checkout=tmp_path, trial=1, timeout=5, skill="sast") + [record] = list(evaluation.live_records(args, {case_id: CASES[case_id]})) + provenance = record["runtime_provenance"] + assert provenance["runtime_version"] == "9.8.7" and provenance["model_digest"] == "d" * 64 + assert provenance["context_length"] == 16384 + assert record["response_models"] == ["tiny:q4"] + assert record["request_options"] == ["num_retries", "timeout"] + + +def test_combine_is_order_stable_and_byte_identical_to_cat(tmp_path): + first, second = tmp_path / "trial-1.jsonl", tmp_path / "trial-2.jsonl" + first.write_bytes(b'{"trial": 1}\n{"trial": 1, "b": 2}\n') + second.write_bytes(b'{"trial": 2}\n') + one, two = tmp_path / "a.jsonl", tmp_path / "b.jsonl" + evaluation.combine_artifacts([first, second], one) + evaluation.combine_artifacts([first, second], two) + assert one.read_bytes() == two.read_bytes() == first.read_bytes() + second.read_bytes() + swapped = tmp_path / "swapped.jsonl" + evaluation.combine_artifacts([second, first], swapped) + assert swapped.read_bytes() != one.read_bytes() + with pytest.raises(FileExistsError): + evaluation.combine_artifacts([first], one) + unterminated = tmp_path / "bad.jsonl" + unterminated.write_bytes(b'{"trial": 3}') + with pytest.raises(ValueError, match="newline"): + evaluation.combine_artifacts([unterminated], tmp_path / "out.jsonl") + + +def test_combine_and_summary_cli_rebuild_published_artifact(tmp_path, monkeypatch, capsys): + published = SCRIPT.parents[1] / "docs/evaluations/2026-11-19" + lines = (published / "api.jsonl").read_bytes().splitlines(keepends=True) + trials = {1: [], 2: []} + for line in lines: + trials[json.loads(line)["trial"]].append(line) + for number, chunk in trials.items(): + (tmp_path / f"trial-{number}.jsonl").write_bytes(b"".join(chunk)) + api, summary = tmp_path / "api.jsonl", tmp_path / "summary.md" + monkeypatch.setattr(sys, "argv", [str(SCRIPT), "--combine", str(tmp_path / "trial-1.jsonl"), + str(tmp_path / "trial-2.jsonl"), "-o", str(api)]) + assert evaluation.main() == 0 + assert api.read_bytes() == (published / "api.jsonl").read_bytes() + monkeypatch.setattr(sys, "argv", [str(SCRIPT), "--records", str(api), "--summary", str(summary)]) + assert evaluation.main() == 1 # nonscorable runs, by design + assert capsys.readouterr().out == "" + assert summary.read_text() == (published / "summary.md").read_text() + + +def test_summary_refuses_to_overwrite_without_a_traceback(tmp_path, monkeypatch): + summary = tmp_path / "summary.md" + summary.write_text("keep me\n") + published = SCRIPT.parents[1] / "docs/evaluations/2026-11-19/api.jsonl" + monkeypatch.setattr(sys, "argv", [str(SCRIPT), "--records", str(published), "--summary", str(summary)]) + with pytest.raises(SystemExit) as error: + evaluation.main() + assert error.value.code == 2 and summary.read_text() == "keep me\n" + + +def test_probe_bypasses_environment_proxies(monkeypatch): + # A proxy would see the probe and could answer for a different server; + # port 9 (discard) is closed, so going through it would fail the probe. + for name in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"): + monkeypatch.setenv(name, "http://127.0.0.1:9") + for name in ("no_proxy", "NO_PROXY"): + monkeypatch.delenv(name, raising=False) + with _FakeOllama() as base: + info = evaluation.runtime_provenance("api", "ollama_chat/tiny:q4", base) + assert "probe_error" not in info and info["runtime_version"] == "9.8.7" + + +def test_probe_does_not_follow_redirects_off_loopback(): + with _FakeOllama(version=_REDIRECT) as base: + info = evaluation.runtime_provenance("api", "ollama_chat/tiny:q4", base) + assert info["probe_error"] == "HTTPError" and "runtime_version" not in info + + +@pytest.mark.parametrize("override", [{"version": _TRUNCATED}, {"version": ["not", "a", "dict"]}, + {"show": {"parameters": 7}}, {"tags": {"models": [1]}}]) +def test_malformed_probe_responses_are_recorded_not_raised(override): + with _FakeOllama(**{"show": {}, **override}) as base: + info = evaluation.runtime_provenance("api", "ollama_chat/tiny:q4", base) + assert info["probe_error"] and info["endpoint"] == "loopback" + + +def test_untagged_model_name_matches_ollama_latest_tag(): + latest = {"name": "tiny:latest", "model": "tiny:latest", "digest": "e" * 64, "context_length": 4096} + with _FakeOllama(tags={"models": [latest]}, ps={"models": [latest]}) as base: + info = evaluation.runtime_provenance("api", "ollama_chat/tiny", base) + assert info["model_digest"] == "e" * 64 and info["context_length"] == 4096 + + +def test_modelfile_parameters_keep_repeated_stops_and_stay_valid_json(): + options = evaluation._parse_modelfile_parameters( + 'stop "<|im_start|>"\nstop "<|im_end|>"\nstop "x"\nnum_ctx 4096\nseed inf\nmin_p nan\n') + assert options["stop"] == ['"<|im_start|>"', '"<|im_end|>"', '"x"'] + assert options["num_ctx"] == 4096 and options["seed"] == "inf" and options["min_p"] == "nan" + json.dumps(options, allow_nan=False) + + +def test_failed_after_probe_is_recorded(tmp_path, monkeypatch): + import types + + probes = iter([{"runtime": "ollama", "endpoint": "loopback", "runtime_version": "9.8.7", + "model_digest": "d" * 64, "context_length": None}, + {"runtime": "ollama", "endpoint": "loopback", "probe_error": "ConnectionRefusedError"}]) + monkeypatch.setattr(evaluation, "runtime_provenance", lambda *args: next(probes)) + monkeypatch.setattr(evaluation.subprocess, "run", lambda *a, **k: types.SimpleNamespace( + returncode=0, stdout=json.dumps({"status": "success", "raw_report": "r"}))) + monkeypatch.setattr(evaluation.subprocess, "check_output", + lambda command, **k: "abc123" if "rev-parse" in command else "") + args = types.SimpleNamespace(agent="api", model="ollama_chat/tiny:q4", phase="hardened", + checkout=tmp_path, trial=1, timeout=5, skill="sast") + [record] = list(evaluation.live_records(args, {"code-comment-attack": CASES["code-comment-attack"]})) + provenance = record["runtime_provenance"] + assert provenance["probe_error_after"] == "ConnectionRefusedError" + assert provenance["runtime_version_after"] is None and provenance["runtime_version"] == "9.8.7"