diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index fbc9b63..4c163a8 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -51,6 +51,25 @@ jobs: - name: Test run: python -m pytest -q -rs + security: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: Install with every optional dependency + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[langgraph,security]" mcp + - name: Bandit (source code; fails on any unmarked finding) + run: python -m bandit -r agent_readback examples -q + - name: pip-audit (known vulnerabilities in installed dependencies) + run: python -m pip_audit --skip-editable --progress-spinner off + build: runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.gitignore b/.gitignore index 777b228..e9a9428 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,4 @@ build/ graphify-out/ .test-tmp*/ .test-python*/ -.venv/ +.venv*/ diff --git a/CHANGELOG.md b/CHANGELOG.md index c2db6a9..37fe064 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,40 @@ All notable changes to `agent-readback`. Dates are UTC. -## Unreleased +## 0.3.0 — 2026-11-21 + +### Breaking changes + +- `StripeRefundVerifier` refuses a client that sends a Stripe secret key + (`sk_live_...` or `sk_test_...`, as Basic auth or a Bearer header) with + `ValueError`. A secret key can also create refunds, which defeats the + independent check; use a restricted read-only `rk_` key. +- `SqlRowVerifier(..., placeholder=...)` raises `ValueError` for anything + other than `?`, `%s`, `:name`, `:1` or `$1`. +- A pending Stripe refund's finding is `pending` (was `unreachable`), and the + verdict keeps the new refunds in `observed` so it can be re-checked. +- The LangGraph example uses the same outcome labels as `run_eval`: + `false_completion` (was `false_completion_caught`), `done_but_unverified` + (was `said_done_unverified`), `said_failed_but_actually_done` (was + `said_failed_but_verified`) and `reported_failure` (was + `said_failed_and_failed` / `said_failed_unverified`). + +### Security + +- On Windows, where mode `0600` does nothing, a new evidence log is created + empty, has every existing access entry (explicit and inherited) removed with + `icacls` and is granted only to the + SID of the process's own access token (read with `whoami`), all before the + first record is written. `icacls` and `whoami` are run from the directory + `GetSystemDirectoryW` returns; `USERNAME`, `USERDOMAIN`, `SystemRoot` and + `PATH` are never used, so an environment naming another account cannot + lock the writer out of its own log. A failure (including an `icacls` that + prints nothing) warns and the log is still written. +- The `sk_` key check inspects only static keys (exactly httpx `BasicAuth`, not + a subclass, or a + Bearer header); a custom auth flow is never run during construction. +- `SqlRowVerifier` validates `placeholder`: it is spliced into the query + text, so a value such as `? OR 1=1` used to reach the database. ### Added @@ -17,16 +50,44 @@ All notable changes to `agent-readback`. Dates are UTC. failed verdicts are never re-checked. `StripeRefundVerifier.recheck` judges only the refunds seen at the first check. - `FindingKind.PENDING`: a Stripe refund that matches but has not settled. - -### Changed - -- A pending Stripe refund's finding is `pending` (was `unreachable`), and the - verdict keeps the new refunds in `observed` so it can be re-checked. +- Opt-in read limiting: `RateLimit(per_second, burst=1, *, max_wait=None)` + (thread-safe token bucket) and `limit_reads(target, limit)`, which applies it + to a verifier's `httpx.Client` (every request, paging included) or SQL + `connect` callable. A limit only delays reads. With `max_wait`, a read that + would wait longer raises `RateLimitTimeout` (a subclass of + `httpx.TimeoutException`) at once without using a slot, so the verdict is + `unverified` instead of the agent stalling. Limiting the same target twice + is refused. +- Test of `watched()` over MCP Streamable HTTP (local server on 127.0.0.1, + MCP 1.x and 2.x): an honest booking is `verified` and a misdescribed one + `failed`. `tests/mcp_stdio_server.py DATABASE PORT` serves HTTP. +- `security` extra (bandit, pip-audit, pinned) and a `security` CI job that + fails on any unmarked bandit finding or any known dependency vulnerability. ### Fixed +- On Windows, output from `whoami`/`icacls` that cannot be decoded (for + example a non-ASCII account name in another code page) no longer escapes + and stops the first evidence append; it is decoded tolerantly and any + failure warns. +- `RateLimit(..., max_wait=0)` no longer refuses a read inside a fresh burst + because of floating-point rounding. A rounding-sized wait counts as none; + the cutoff scales with the clock value, since `time.monotonic()` counts + from boot and its rounding error grows with uptime. +- The LangGraph example classifies a `FAILED` reply by the task verdict when + there is one, as `run_eval` does: writes that held at the wrong time are + `reported_failure`, not `said_failed_but_actually_done`. - A pending Stripe refund with a wrong amount, currency or a second refund is now `failed`; before, being pending hid the mismatch as `unverified`. +- The example `.env` loader warns when the file cannot be read instead of + ignoring the error. + +### Documentation + +- README: real-model results for the LangGraph agent (claude-sonnet-5-5, + claude-haiku-5-5, gpt-6-luna; 50 runs each, verdicts identical to + `run_eval` run for run), MCP 2.x and HTTP coverage, a "Rate limiting the + verifier's reads" section, and two new Security model rows. ## 0.2.2 — 2026-11-19 diff --git a/CLAUDE.md b/CLAUDE.md index 08bd3f3..6acb7dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## What this is -Readback (`agent-readback`, v0.2.2): checks an AI agent's "Done." claim against the system of record. Snapshot before the agent acts, re-read afterward through a read-only path, emit a deterministic verdict (`verified` / `failed` / `unverified`). Verdicts never come from an LLM. Only runtime dependency: `httpx`. +Readback (`agent-readback`, v0.3.0): checks an AI agent's "Done." claim against the system of record. Snapshot before the agent acts, re-read afterward through a read-only path, emit a deterministic verdict (`verified` / `failed` / `unverified`). Verdicts never come from an LLM. Only runtime dependency: `httpx`. ## Commands @@ -21,9 +21,10 @@ export READBACK_LOG_KEY=... # key the log was written wit readback verify-log evidence.jsonl # chain check, prints head hash (0 ok, 1 broken/untrustworthy, 2 bad args, 3 file error; --require-key for audits) readback report evidence.jsonl # verdict counts / failed rate by action python -m build # wheel + sdist into dist/ +python -m pip install -e ".[security]" && python -m bandit -r agent_readback examples -q && python -m pip_audit --skip-editable # security scans (CI runs the same) ``` -`run_eval` refuses an existing `--log` path (default: fresh temp file, path printed at the end). Real-model eval: `--provider anthropic|openai --model ` with `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` in the environment; `--fhir-url` targets a real FHIR R4 test server instead of the mock. No lint/format config exists. On Windows the `readback` script lands outside PATH; use `python -m agent_readback`. +`run_eval` refuses an existing `--log` path (default: fresh temp file, path printed at the end). Real-model eval: `--provider anthropic|openai --model ` with `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` in the environment; `--fhir-url` targets a real FHIR R4 test server instead of the mock. No lint/format config exists; security scans (bandit + pip-audit, pinned in the `security` extra) run in CI and must stay clean: mark a false positive with a reason and `# nosec ` at the end of the reported line. On Windows the `readback` script lands outside PATH; use `python -m agent_readback`. ## Architecture @@ -31,6 +32,7 @@ python -m build # wheel + sdist into dist/ - `agent_readback/verifiers/` — FHIR Appointment (create/update/cancel), Stripe refund, SQL row. Shared pattern: snapshot captures prior state (existing IDs for FHIR/Stripe; row + row count for SQL), or `None` on read error; anything new that wasn't claimed becomes `extra_effect`; read errors yield `UNVERIFIED`, never `FAILED`; a `None` snapshot means `UNVERIFIED`. Field comparison goes through `compare_fields`. FHIR normalizes timestamps to UTC and deliberately leaves zoneless times unnormalized so they mismatch. FHIR and Stripe reads are page-capped (`MAX_PAGES`); overflow → `UNVERIFIED`. A matching `pending` Stripe refund is `UNVERIFIED` with a `PENDING` finding (a pending refund with a wrong field is `FAILED`). `core.recheck(verifier, verdict_or_dict, log)` re-judges only `UNVERIFIED` verdicts via the verifier's optional `recheck(claim, observed)` and tags `context["recheck_of"]`; Stripe judges only the refunds seen at the first check. - `agent_readback/evidence.py` — append-only JSONL log; each record carries `seq` and hashes the previous (`GENESIS` = 64 zeros). With a key (`key=` or `READBACK_LOG_KEY`) hashes are HMAC-SHA256; `_digest(prev, seq, body, key)` is the single hashing function. File opened `0600` + `O_APPEND`. Optional `anchor=` callable gets `(count, head)` after each append (`FileAnchor` writes it atomically to a separate file; a failing anchor warns and sets `anchor_error`, never raises); `verify-log --anchor FILE` / `--head HASH` uses `check_anchor` to catch truncation. Redacts by default: no observed values, agent text replaced by a keyed digest, expected/finding values replaced unless the field is in `keep_fields` (`"*"` keeps all). Preserve this default when changing the log format. README "Security model" table must stay in sync with these guarantees. - `agent_readback/adapters.py` — `watched(fn, verifier, to_claim, log, said=...)` wraps a sync/async callable in `watch()`; `to_claim(*args, **kwargs)` → probe or `None` (skip). Used for MCP (`session.call_tool = watched(...)`, `said=mcp_text`) and LangGraph nodes. Imports neither framework; tests use them via `importorskip`. +- `agent_readback/ratelimit.py` — opt-in read limiting. `RateLimit(per_second, burst)` is a thread-safe token bucket (GCRA; slot reserved under the lock, sleep outside it; clock and sleep injectable for tests). `limit_reads(target, limit)` adds an httpx request hook to a sync `httpx.Client` or wraps a SQL `connect` callable; it refuses an `AsyncClient` and a target it already limited (marked with `_readback_rate_limit`). Keyword-only `max_wait`: a wait longer than that raises `RateLimitTimeout` (subclass of `httpx.TimeoutException`) without taking a slot, which every verifier reports as `unverified`. Otherwise it only ever delays a read, so verdict semantics are unchanged. - `agent_readback/report.py`, `dashboard.py` (one-file HTML page, everything escaped; `readback dashboard`), `cli.py`, `alerts.py` (`WebhookAlert` as an `on_verdict` callback; swallows every exception; signs the body with `X-Readback-Signature` using `READBACK_ALERT_KEY`, never the log key, so a receiver can't forge the log). FHIR paging refuses next links whose httpx-resolved URL leaves the client's origin (token leak). CLI flags keyless OKs as UNKEYED and never lets `dashboard -o` overwrite a log. Evals label replies that start with neither `DONE` nor `FAILED` as `unclear_reply` (not counted as claims); the LangGraph agent labels a DONE whose last write held after an earlier failed one `done_after_failed_write`. Logs are written with LF endings on every OS. - `graphify-out/` — generated knowledge graph of this repo (`/graphify`), not part of the package. Refresh with `/graphify --update` after doc changes. - `examples/healthcare/` — demo harness and test fixtures: `mock_fhir.py` (in-memory FHIR via `httpx.MockTransport`; `server.fault` in `ok|drop|wrong_time|wrong_practitioner|duplicate` — faults still return success; `server.down` simulates outage), `tools.py` (agent's write tools — intentionally never read back), `llm.py` (Anthropic / OpenAI-compatible chat completions / OpenAI Responses (reasoning + tools, chained via `previous_response_id`) / Scripted tool loops via raw httpx), `tasks.py` (Central-time requests plus an oracle for the scripted agent), `run_eval.py`, `langgraph_agent.py` (agent + `ToolNode` loop with `watched()` write tools; scripted agent node by default, `--provider anthropic|openai --model ` via the `[langgraph]` extra; reschedule/cancel claims look up the patient via the verifier's client). @@ -40,5 +42,5 @@ python -m build # wheel + sdist into dist/ - All HTTP goes through an injected `httpx.Client`; tests swap in `httpx.MockTransport`. Keep new verifiers and providers injectable the same way. - New verifier: implement `snapshot`/`check` per `core.Verifier`, name actions `..`, export from `verifiers/__init__.py`, update the README verifier table. - The verifier must use credentials the agent doesn't hold; a shared write path makes the check meaningless. -- The README's "What is tested and what is not" and "Security model" tables are kept honest. Update them (and the test count, currently 128) when coverage or guarantees change. +- The README's "What is tested and what is not" and "Security model" tables are kept honest. Update them (and the test count, currently 162) when coverage or guarantees change. - Security changes need a test that demonstrates the attack failing (see `test_keyed_log_detects_a_chain_forged_without_the_key`), not just the happy path. diff --git a/README.md b/README.md index 161461a..1a43df2 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ flowchart LR ## What is tested and what is not -Version 0.2.2. All 128 offline tests pass with the optional test dependencies +Version 0.3.0. All 162 offline tests pass with the optional test dependencies installed. A separate public HAPI FHIR R4 sandbox run verified 10 scripted operations (6 bookings, 1 reschedule, 3 cancellations); this is a compatibility smoke test, not production validation. @@ -52,9 +52,9 @@ create refunds. | FHIR appointment verifier (create, update, cancel) | in-memory mock, incomplete pagination, stale-search regression, off-server next links; public HAPI R4 sandbox smoke test | a production EHR, authenticated read-only isolation | | Stripe refund verifier and sandbox runner | mock refunds endpoint; test-key guards; Stripe test mode with a read-only restricted key: success, missing, wrong-amount and duplicate scenarios | live mode, a refund left pending by the bank | | SQL row verifier | SQLite, including insert with concurrent deletion | Postgres or any other database | -| Anthropic and OpenAI-compatible agent loops | Mock responses cover each API's message format, Responses tool-call chaining with and without storage, and a once-per-evaluation warning for a model HTTP 400. Earlier live Anthropic runs (claude-sonnet-5-5 and claude-haiku-5-5, 50 tasks each, 20% injected faults) caught every false completion and matched the scripted baseline run for run. On the same tasks and faults, gpt-6-luna with `--reasoning-effort none` caught all 13 injected faults plus 6 of its own wrong reschedule or cancel values. With `--provider openai-responses --reasoning-effort medium`, it caught all 13 and matched the scripted baseline run for run, both with server-side storage and with `--no-store` (OpenAI echoed `store: false`; encrypted reasoning was sent back each turn instead of `previous_response_id`). | Reasoning efforts other than `none` and `medium` | +| Anthropic and OpenAI-compatible agent loops | Mock responses cover each API's message format, Responses tool-call chaining with and without storage, and a once-per-evaluation warning for a model HTTP 400. Earlier live Anthropic runs (claude-sonnet-5-5 and claude-haiku-5-5, 50 tasks each, 20% injected faults) caught every false completion and matched the scripted baseline run for run. On the same tasks and faults, gpt-6-luna with `--reasoning-effort none` caught all 13 injected faults plus 6 of its own wrong reschedule or cancel values. With `--provider openai-responses --reasoning-effort medium`, it caught all 13 and matched the scripted baseline run for run, both with server-side storage and with `--no-store` (OpenAI echoed `store: false`; encrypted reasoning was sent back each turn instead of `previous_response_id`). The LangGraph agent (`examples/healthcare/langgraph_agent.py`, 50 tasks per model, seed 7, 20% injected faults) gave the same task verdict and finding kinds as `run_eval` and the scripted baseline in every run for claude-sonnet-5-5, claude-haiku-5-5 and gpt-6-luna (LangChain default reasoning effort); all three evidence chains were intact. Haiku and gpt-6-luna: 37 `done_and_verified`, 13 `false_completion`. Sonnet: 37, 11 and 2 `reported_failure`: in one run whose write the verifier failed, it reported the failure instead of claiming DONE. | Reasoning efforts other than `none` and `medium`; LangGraph with other models | | Evidence log, redaction, report, dashboard, webhook | unit tests, including HTML escaping of hostile context values and a BROKEN dashboard for a tampered log | production load | -| `watched()` adapters | Sync and async functions, including off-loop verifier reads when an async tool raises, a verdict even when an AnyIO cancel scope cancels the tool after it writes, and objects with `async def __call__`. MCP 1.27 `ClientSession` runs against in-memory FastMCP and a local stdio subprocess backed by SQLite. LangGraph 0.2 and 1.2 run a wrapped `StateGraph` node and a wrapped LangChain tool in `ToolNode`, plus a full agent/`ToolNode` loop (`examples/healthcare/langgraph_agent.py`) that catches every false DONE under injected faults. Mock FHIR tests catch injected drop, wrong-time, wrong-practitioner and duplicate faults. | MCP over HTTP, MCP 2.x | +| `watched()` adapters | Sync and async functions, including off-loop verifier reads when an async tool raises, a verdict even when an AnyIO cancel scope cancels the tool after it writes, and objects with `async def __call__`. MCP 1.30 and 2.3 `ClientSession` run against in-memory FastMCP, a local stdio subprocess, and the same server over Streamable HTTP on 127.0.0.1, both backed by SQLite; over HTTP a booking the agent misdescribes is `failed` on the field read back from the database. LangGraph 0.2 and 1.2 run a wrapped `StateGraph` node and a wrapped LangChain tool in `ToolNode`, plus a full agent/`ToolNode` loop (`examples/healthcare/langgraph_agent.py`) that catches every false DONE under injected faults. Mock FHIR tests catch injected drop, wrong-time, wrong-practitioner and duplicate faults. | MCP over HTTP to a remote host, with TLS or auth | No security or compliance review has been done. @@ -191,6 +191,29 @@ python -m examples.healthcare.langgraph_agent --provider openai --model gpt-6-lu A 3-run smoke test with each model (2026-11-19, 30% injected faults) gave 2 verified and 1 false DONE caught per model. Too small to compare models. +### Rate limiting the verifier's reads + +Every verifier reads through the client or `connect` callable you give it, so +the limit goes there. It is opt-in: + +```python +from agent_readback import RateLimit, limit_reads + +limit = RateLimit(per_second=5, burst=10, max_wait=2.0) # one limit per quota, shared +fhir = FhirAppointmentVerifier(limit_reads(httpx.Client(...), limit)) # every request, paging included +sql = SqlRowVerifier(limit_reads(connect, limit), "orders", "id") # every connection +``` + +- A limit only delays reads, so it never turns a verdict into `failed`. +- With `max_wait`, a read that would wait longer raises `RateLimitTimeout` at + once instead of stalling the agent; verifiers report it as `unverified`. + It subclasses `httpx.TimeoutException`, so do not wrap verifier calls in an + automatic retry-on-timeout: catch `RateLimitTimeout` first and let it stand. +- Limiting the same client or `connect` twice is refused (it would halve the + rate); share one `RateLimit` across clients instead. +- A 429 the server still sends is a read error, so `unverified`. It is not + retried. + ## Verifiers | Verifier | Actions | Catches | @@ -277,18 +300,21 @@ restricted key with `refunds: read`, a database role with `SELECT` only). | Whole chain rewritten by someone with file access | HMAC-SHA256 with `READBACK_LOG_KEY`; a chain built without the key fails verification. Without the key, an OK is labelled `UNKEYED` (not forgery-proof); `--require-key` makes audits fail instead. Keyed records carry `"mac": "hmac-sha256"`, so a keyed log checked without its key says so rather than "edited" | | Newest records dropped | Not detectable from the file alone. `EvidenceLog(anchor=FileAnchor(...))` records the count and head after every append; `verify-log --anchor FILE` or `--head HASH` reports BROKEN when the anchored head is missing. The anchor must live where the log writer cannot change it | | Personal data in the log | Redacted by default: no observed values, no agent text (keyed digest only), expected values replaced unless named in `keep_fields` | +| Verifier given a key that can also write | `StripeRefundVerifier` refuses a client that sends a secret key (`sk_live_` or `sk_test_`, Basic or Bearer); use a restricted `rk_` key with refunds read. It checks the prefix of static keys only (httpx `BasicAuth` or a Bearer header; custom auth flows are never run during the check and their keys are not seen) and cannot prove an `rk_` key is read-only | +| Other Windows accounts reading the log | Mode `0600` does nothing on Windows, so a new log is created empty, has every existing access entry (explicit and inherited) removed with `icacls` and is granted to this process's own SID (read from its access token with `whoami`; System32 located with `GetSystemDirectoryW`; `USERNAME`, `SystemRoot` and `PATH` are never used), all before the first record is written. If that fails the log is still written and a `RuntimeWarning` says so. A process that opens the file in the instant between creation and restriction keeps its handle: put logs in a folder only you can access. Logs created before this change and anchor files keep their folder's access | | Alert spoofing | `WebhookAlert` signs every body with `X-Readback-Signature: sha256=` when `READBACK_ALERT_KEY` is set; receivers must check it | | Alert receiver forging the log | The alert key is separate from `READBACK_LOG_KEY` and the log key is never used for alerts. `WebhookAlert` refuses a key equal to `READBACK_LOG_KEY` or to a key passed to any `EvidenceLog` in the same process, at creation and before each send. It cannot see keys used only by other processes: keep explicit log and alert keys separate yourself | | Server-supplied paging link sends the verifier's token elsewhere | Each FHIR next link is resolved the way httpx will send it (so `//host/x` and similar forms count) and must stay on the client's scheme, host and port; anything else is `unverified` and is never requested | | Evidence log overwritten by the dashboard | `readback dashboard` refuses an output path that is the log itself or any existing `.jsonl` | | Hostile or broken server pages forever | FHIR and Stripe reads are page-capped; the result is `unverified`, not a hang | -| SQL injection via claim | Table and column names come from your code and are pattern-checked; values are always bound parameters | +| SQL injection via claim or config | Table and column names come from your code and are pattern-checked; the `placeholder` must be a DB-API paramstyle (`?`, `%s`, `:name`, `:1`, `$1`); values are always bound parameters | +| Verifier overloading the system of record | Opt-in `limit_reads(..., RateLimit(...))` caps every read; it only delays reads, and with `max_wait` an over-long wait is `unverified`, never `failed` (see [Rate limiting the verifier's reads](#rate-limiting-the-verifiers-reads)) | | Unreadable system of record | `unverified`, never `verified` and never `failed` | Known limits: `Claim.context` is stored as given; `Verdict.observed` holds real values in memory (do not print it in production logs); a pending Stripe refund is `unverified` until you `recheck` it, and scheduling that is up to -you; no rate limiting on the verifier's own reads. No external security or compliance review has been done. +you; rate limiting is opt-in (`limit_reads`) and does not retry a 429. No external security or compliance review has been done. ## Repeat sandbox validation diff --git a/agent_readback/__init__.py b/agent_readback/__init__.py index 3e648cc..bafeaf8 100644 --- a/agent_readback/__init__.py +++ b/agent_readback/__init__.py @@ -4,19 +4,23 @@ from .alerts import WebhookAlert from .core import Claim, Finding, FindingKind, Status, Verdict, Verifier, compare_fields, recheck, watch from .evidence import EvidenceLog, FileAnchor +from .ratelimit import RateLimit, RateLimitTimeout, limit_reads -__version__ = "0.2.2" +__version__ = "0.3.0" __all__ = [ "Claim", "EvidenceLog", "FileAnchor", "Finding", "FindingKind", + "RateLimit", + "RateLimitTimeout", "Status", "Verdict", "Verifier", "WebhookAlert", "compare_fields", + "limit_reads", "mcp_text", "recheck", "watch", diff --git a/agent_readback/evidence.py b/agent_readback/evidence.py index ff1316f..9615ccd 100644 --- a/agent_readback/evidence.py +++ b/agent_readback/evidence.py @@ -106,6 +106,47 @@ def redact(body: dict[str, Any], keep: frozenset[str], key: bytes | None = None) Anchor = Callable[[int, str], None] # called with (record count, head hash) after each append +_SID = re.compile(r"^S-1-\d+(-\d+)+$") + + +def _owner_only(path: Path) -> None: + """Windows ignores mode 0o600; drop inherited access so only the current user can open the log. + + Never raises: a failure warns, like a failing anchor, so the agent keeps running. + """ + if os.name != "nt": + return # 0o600 at creation already does this + import ctypes + import subprocess # fixed system tools, argument lists, no shell # nosec B404 + + # Nothing here comes from the environment: SystemRoot, PATH, USERNAME and + # USERDOMAIN can all name the wrong thing (e.g. under `runas /env`), and a + # grant to the wrong account locks this process out of its own log. + buffer = ctypes.create_unicode_buffer(260) + system32 = Path(buffer.value) if ctypes.windll.kernel32.GetSystemDirectoryW(buffer, 260) else None + failed = "" if system32 else "could not locate the System32 directory" + try: + if not failed: # whoami reads the SID from this process's own access token + run = lambda *args: subprocess.run( # noqa: E731 # absolute executable, list args # nosec B603 + [str(system32 / args[0]), *args[1:]], capture_output=True, text=True, errors="replace", timeout=30 + ) + who = run("whoami.exe", "/user", "/fo", "csv", "/nh") + sid = who.stdout.strip().rsplit(",", 1)[-1].strip('"') if who.returncode == 0 else "" + if not _SID.match(sid): + failed = f"could not read the current user's SID: {(who.stderr or who.stdout).strip()!r}" + else: + # /reset drops explicit entries (some hosts, e.g. GitHub's Windows runners, + # put explicit ones on new files); /inheritance:r then drops inherited ones, + # leaving only this SID. The file is still empty while this runs. + for step in (("/reset",), ("/inheritance:r", "/grant:r", f"*{sid}:F")): + result = run("icacls.exe", str(path), *step) + if result.returncode != 0: # icacls can fail without printing anything + failed = (result.stderr or result.stdout).strip() or f"icacls exited with {result.returncode}" + break + except (OSError, subprocess.SubprocessError, ValueError) as error: # ValueError: e.g. UnicodeDecodeError + failed = str(error) + if failed: + warnings.warn(f"could not restrict {path} to the current user: {failed}", RuntimeWarning, stacklevel=5) class FileAnchor: @@ -176,6 +217,16 @@ def _append(self, verdict: Verdict) -> str: # instead of "edited". A forger can delete it, so the CLI also flags every # keyless verification as not forgery-proof. record["mac"] = MAC_ALG + if not self.path.exists(): + # Create it empty and restrict it before the first record is written. + # ponytail: a process that opens the file in the moment between create and + # restrict keeps that handle; a log folder only you can access closes that too. + try: + os.close(os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)) + except FileExistsError: + pass # another writer created it first and restricts it + else: + _owner_only(self.path) fd = os.open(self.path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) with os.fdopen(fd, "a", encoding="utf-8", newline="\n") as handle: # same bytes on every OS handle.write(json.dumps(record) + "\n") diff --git a/agent_readback/ratelimit.py b/agent_readback/ratelimit.py new file mode 100644 index 0000000..8d232be --- /dev/null +++ b/agent_readback/ratelimit.py @@ -0,0 +1,113 @@ +"""Cap how fast a verifier reads the system of record. + +Every verifier reads through something you inject, so the limit goes there: + + limit = RateLimit(per_second=5, burst=10) + FhirAppointmentVerifier(limit_reads(httpx.Client(...), limit)) # every GET, paging included + SqlRowVerifier(limit_reads(connect, limit), "orders", "id") # every connection + +Share one ``RateLimit`` between all clients that count against the same quota. +Waiting is the only effect: a read is delayed, never dropped or failed, so a +limit cannot turn a verdict into ``failed``. A server that still answers 429 +makes that read ``unverified``, as any read error does. +""" + +from __future__ import annotations + +import math +import threading +import time +from typing import Any, Callable, TypeVar + +import httpx + +T = TypeVar("T") +_MARK = "_readback_rate_limit" # set on a limited client's hook or connect wrapper + + +class RateLimitTimeout(httpx.TimeoutException): + """A read would have waited longer than ``max_wait``. An httpx error, so every verifier reports ``unverified``.""" + + +class RateLimit: + """Token bucket (GCRA): bursts of up to ``burst`` reads, long-run rate ``per_second``. Thread-safe. + + It spaces reservations, not start times: callers that wake late from their + sleep can start together. The long-run rate still holds. + + With ``max_wait`` (seconds), a read that would wait longer is not made: it + raises ``RateLimitTimeout`` at once, uses no slot, and the verdict is + ``unverified`` instead of the agent stalling behind a long queue. + ``RateLimitTimeout`` subclasses ``httpx.TimeoutException``: do not let a + retry-on-timeout wrapper retry it, or it spins against the limit. + """ + + def __init__( + self, per_second: float, burst: int = 1, + clock: Callable[[], float] = time.monotonic, sleep: Callable[[float], Any] = time.sleep, + *, max_wait: float | None = None, # keyword-only, so clock and sleep keep their positions + ) -> None: + if not per_second > 0: # also rejects NaN + raise ValueError("per_second must be greater than 0") + if type(burst) is not int or burst < 1: + raise ValueError("burst must be an integer of at least 1") + if max_wait is not None and not max_wait >= 0: # also rejects NaN + raise ValueError("max_wait must be None or at least 0") + self.interval = 1.0 / per_second + self.burst = burst + self.max_wait = max_wait + self._clock, self._sleep = clock, sleep + self._lock = threading.Lock() + self._next_free = clock() # when the bucket would be full again (GCRA's "theoretical arrival time") + + def acquire(self) -> float: + """Block until a read may start; return the seconds waited.""" + with self._lock: # reserve a slot in order; sleep outside the lock + now = self._clock() + start = max(self._next_free, now) + wait = start - (self.burst - 1) * self.interval - now + # Float rounding must not refuse a read inside a fresh burst. The error grows + # with the clock's magnitude (monotonic() counts from boot), so scale with it. + wait = wait if wait > 1e-9 + 64 * math.ulp(start) else 0.0 + if self.max_wait is not None and wait > self.max_wait: + raise RateLimitTimeout(f"read rate limit: would wait {wait:.2f}s, more than max_wait {self.max_wait}s") + self._next_free = start + self.interval + if wait: + self._sleep(wait) + return wait + + +def limit_reads(target: T, limit: RateLimit) -> T: + """Apply ``limit`` to a verifier's read path and return it. + + ``target`` is an ``httpx.Client`` (FHIR, Stripe: each request waits, including + paging) or a zero-argument ``connect`` callable (SQL: each connection waits). + A target that is already limited is refused: a second limit would silently + halve its rate. Share one ``RateLimit`` instead. + """ + if isinstance(target, httpx.Client): + hooks = target.event_hooks + if any(hasattr(hook, _MARK) for hook in hooks.get("request", [])): + raise ValueError("this client is already rate-limited; share one RateLimit instead of limiting it twice") + + def wait_for_slot(request: httpx.Request) -> None: + limit.acquire() + + setattr(wait_for_slot, _MARK, limit) + hooks["request"] = [*hooks.get("request", []), wait_for_slot] + target.event_hooks = hooks + return target + if isinstance(target, httpx.AsyncClient): + raise TypeError("verifiers read with a synchronous httpx.Client; an AsyncClient would block its event loop") + if callable(target): + if hasattr(target, _MARK): + raise ValueError("this connect callable is already rate-limited; share one RateLimit instead") + connect = target + + def limited_connect(*args: Any, **kwargs: Any) -> Any: + limit.acquire() + return connect(*args, **kwargs) + + setattr(limited_connect, _MARK, limit) + return limited_connect # type: ignore[return-value] + raise TypeError(f"cannot rate-limit {type(target).__name__}: pass an httpx.Client or a connect callable") diff --git a/agent_readback/verifiers/sql.py b/agent_readback/verifiers/sql.py index a968f19..5d68dfd 100644 --- a/agent_readback/verifiers/sql.py +++ b/agent_readback/verifiers/sql.py @@ -23,6 +23,7 @@ INSERT = "sql.row.insert" UPDATE = "sql.row.update" _IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$") +_PLACEHOLDER = re.compile(r"^(\?|%s|:[A-Za-z_][A-Za-z0-9_]*|:[1-9][0-9]*|\$[1-9][0-9]*)$") # DB-API paramstyles def _ident(name: str) -> str: @@ -36,6 +37,8 @@ def __init__(self, connect: Callable[[], Any], table: str, key_column: str, plac self.connect = connect self.table = _ident(table) self.key_column = _ident(key_column) + if not _PLACEHOLDER.match(placeholder): # it is spliced into the query text + raise ValueError(f"unsafe SQL placeholder: {placeholder!r}") self.placeholder = placeholder def _read(self, expected: dict[str, Any]) -> tuple[dict[str, Any] | None, int]: @@ -43,12 +46,13 @@ def _read(self, expected: dict[str, Any]) -> tuple[dict[str, Any] | None, int]: connection = self.connect() try: cursor = connection.cursor() + # Identifiers and placeholder are pattern-checked; the key value is a bound parameter. cursor.execute( - f"SELECT {', '.join(columns)} FROM {self.table} WHERE {self.key_column} = {self.placeholder}", + f"SELECT {', '.join(columns)} FROM {self.table} WHERE {self.key_column} = {self.placeholder}", # nosec B608 (expected[self.key_column],), ) row = cursor.fetchone() - cursor.execute(f"SELECT COUNT(*) FROM {self.table}") + cursor.execute(f"SELECT COUNT(*) FROM {self.table}") # table name pattern-checked # nosec B608 count = cursor.fetchone()[0] finally: connection.close() diff --git a/agent_readback/verifiers/stripe.py b/agent_readback/verifiers/stripe.py index deea0e4..ed022a8 100644 --- a/agent_readback/verifiers/stripe.py +++ b/agent_readback/verifiers/stripe.py @@ -17,6 +17,7 @@ from __future__ import annotations +import base64 from typing import Any import httpx @@ -28,8 +29,37 @@ MAX_PAGES = 50 # 5000 refunds on one payment intent; a server that pages forever gets `unverified`, not a hang +def _api_key(client: httpx.Client) -> str | None: + """The static key the client sends (Basic auth user or Bearer token), or None if unknown. + + Only httpx's own BasicAuth is run: it just sets a header. Any other auth flow + could make network calls or need an async client, so it is never invoked here + and its key counts as unknown. + """ + request = client.build_request("GET", "/v1/refunds") + if type(client.auth) is httpx.BasicAuth: # exactly; a subclass may override the flow. e.g. auth=(key, "") + request = next(client.auth.sync_auth_flow(request)) + scheme, _, value = request.headers.get("Authorization", "").partition(" ") + if scheme.lower() == "basic": + try: + value = base64.b64decode(value).decode().partition(":")[0] + except ValueError: + return None + return value.strip() or None + + class StripeRefundVerifier: def __init__(self, client: httpx.Client) -> None: + # ponytail: prefix check on static keys only. It stops a secret key (which can + # also create refunds) passed as Basic auth or a Bearer header, but cannot prove + # an rk_ key is read-only (examples/stripe_sandbox.py checks that live) and does + # not see keys from custom auth flows or added per request. + key = _api_key(client) + if key is not None and key.startswith("sk_"): + raise ValueError( + "StripeRefundVerifier needs a restricted read-only key (rk_...), not a secret key " + "(sk_...): a secret key can also create refunds, which defeats the independent check" + ) self.client = client def _refunds(self, payment_intent: str) -> dict[str, dict[str, Any]]: diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 88fde33..7a597b1 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -33,10 +33,10 @@ examples: run_eval harness, LangGraph agent, mock FHIR server, Stripe sandbox ru | 5 | SQL verifier on Postgres with a `SELECT`-only role | verifiers | Only SQLite is tested | Postgres instance | | 6 | ~~Re-check pending Stripe refunds later instead of leaving them `unverified`~~ (done: `recheck()`, `FindingKind.PENDING`) | core, verifiers | Known limit | — | | 7 | ~~Anchor the evidence-log head hash outside the log~~ (done: `anchor=`, `FileAnchor`, `verify-log --anchor/--head`) | evidence | Dropping the newest records is undetectable from the file alone | — | -| 8 | Rate-limit the verifier's own reads | verifiers | Known limit; matters under production load | — | -| 9 | Real-model eval on the LangGraph agent, 50+ runs per model | examples | The 3-run smoke test cannot compare models | API keys | -| 10 | MCP over HTTP, not only in-memory and stdio | adapters | Listed as untested | — | -| 11 | Cross-check `run_eval` and the LangGraph agent: same seed and model, aligned outcome labels | examples | The two harnesses label outcomes slightly differently | 9 | +| 8 | ~~Rate-limit the verifier's own reads~~ (done 2026-11-21: `RateLimit` + `limit_reads`, opt-in; no 429 retry) | verifiers | Known limit; matters under production load | — | +| 9 | ~~Real-model eval on the LangGraph agent, 50+ runs per model~~ (done 2026-11-20: Sonnet, Haiku, gpt-6-luna, 50 runs each) | examples | The 3-run smoke test cannot compare models | API keys | +| 10 | ~~MCP over HTTP, not only in-memory and stdio~~ (done 2026-11-21: Streamable HTTP on 127.0.0.1, MCP 1.30 and 2.3; remote hosts with TLS or auth not tested) | adapters | Listed as untested | — | +| 11 | ~~Cross-check `run_eval` and the LangGraph agent on the same seed and model~~ (done: labels aligned in 0.3.0; seed 7 task verdicts identical run for run for all three models) | examples | The two harnesses label outcomes slightly differently | 9 | | 12 | External security and compliance review (HIPAA) | all | None has been done; the target domain is healthcare | 1–8 | Steps 1–3 are short and unblock the rest. Steps 4, 5 and 9 need credentials or @@ -48,5 +48,5 @@ infrastructure from the maintainer. Step 12 needs outside reviewers. UNKEYED flagging and `--require-key`, dashboard overwrite guard, malformed record handling, LF log endings, LangGraph example agent with Anthropic and OpenAI models, `tzdata` on Windows. -- Verified locally: 114 tests pass on MCP 1.30 and on MCP 2.3, both with +- Verified locally (2026-11-21, 0.3.0): 162 tests pass on MCP 1.30 and on MCP 2.3, both with LangGraph 1.2 (1 symlink test skips on Windows without symlink privileges). diff --git a/examples/healthcare/langgraph_agent.py b/examples/healthcare/langgraph_agent.py index 7f83d4d..e658f77 100644 --- a/examples/healthcare/langgraph_agent.py +++ b/examples/healthcare/langgraph_agent.py @@ -195,25 +195,28 @@ def outcome(reply: str, verdicts: list[Verdict], task: Verdict | None = None) -> said = "done" if said_done else "failed" if not verdicts: return f"said_{said}_no_write" # e.g. DONE without ever calling a write tool + # Labels match run_eval.py; only said_*_no_write and done_after_failed_write are LangGraph-specific. if said_done and task is not None and task.status is Status.FAILED: - return "false_completion_caught" # e.g. every write held, but at the wrong time + return "false_completion" # e.g. every write held, but at the wrong time if said_done and task is not None and task.status is Status.UNVERIFIED: - return "said_done_unverified" + return "done_but_unverified" + if not said_done and task is not None: # as run_eval: only a task that really holds counts as done + return "said_failed_but_actually_done" if task.status is Status.VERIFIED else "reported_failure" statuses = {v.status for v in verdicts} if said_done and verdicts[-1].status is Status.VERIFIED and Status.FAILED in statuses: # The last write held, but an earlier one failed and may have left an effect behind. return "done_after_failed_write" - if Status.FAILED in statuses: - return "false_completion_caught" if said_done else "said_failed_and_failed" if statuses == {Status.VERIFIED}: - return "done_and_verified" if said_done else "said_failed_but_verified" - return f"said_{said}_unverified" + return "done_and_verified" if said_done else "said_failed_but_actually_done" + if said_done: + return "false_completion" if Status.FAILED in statuses else "done_but_unverified" + return "reported_failure" def run( runs: int, inject_faults: float, seed: int, log_path: Path, chat: Any | None = None, ) -> dict[str, Any]: - rng = random.Random(seed) + rng = random.Random(seed) # seeded for repeatable evals, not security # nosec B311 server = MockFhirServer() setup = server.client() patients, practitioners = seed_people(setup) diff --git a/examples/healthcare/run_eval.py b/examples/healthcare/run_eval.py index ba726ad..d2c4e8b 100644 --- a/examples/healthcare/run_eval.py +++ b/examples/healthcare/run_eval.py @@ -78,7 +78,7 @@ def call(name: str, arguments: dict[str, Any]) -> dict[str, Any]: def run(args: argparse.Namespace) -> dict[str, Any]: - rng = random.Random(args.seed) + rng = random.Random(args.seed) # seeded for repeatable evals, not security # nosec B311 server: MockFhirServer | None = None if args.fhir_url: new_client = lambda: httpx.Client(base_url=args.fhir_url, timeout=30.0) # noqa: E731 diff --git a/examples/stripe_sandbox.py b/examples/stripe_sandbox.py index 82d2f97..a5bf7e5 100644 --- a/examples/stripe_sandbox.py +++ b/examples/stripe_sandbox.py @@ -9,6 +9,7 @@ import argparse import json import os +import sys from pathlib import Path from uuid import uuid4 @@ -30,8 +31,8 @@ def _load_env_file() -> None: v = v.strip().strip("'\"") if k and k not in os.environ: os.environ[k] = v - except Exception: - pass + except (OSError, UnicodeDecodeError) as error: # unreadable .env: say so, keep the real env + print(f"Warning: could not read {candidate}: {error}", file=sys.stderr) def test_keys() -> tuple[str, str]: diff --git a/pyproject.toml b/pyproject.toml index 233648f..42c7da8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "agent-readback" -version = "0.2.2" +version = "0.3.0" description = "Readback: check what an AI agent says it did against the system of record." readme = "README.md" requires-python = ">=3.10" @@ -10,6 +10,7 @@ dependencies = ["httpx>=0.27"] [project.optional-dependencies] dev = ["pytest>=8", "tzdata; sys_platform == 'win32'"] # zoneinfo has no system tz database on Windows +security = ["bandit==1.9.4", "pip-audit==2.10.1"] # pinned so a scanner update cannot silently change the gate langgraph = ["langgraph>=1.0", "langchain-core>=1.0", "langchain-anthropic>=1.0", "langchain-openai>=1.0", "tzdata; sys_platform == 'win32'"] [project.scripts] diff --git a/tests/mcp_stdio_server.py b/tests/mcp_stdio_server.py index 8e6588a..cc6ef52 100644 --- a/tests/mcp_stdio_server.py +++ b/tests/mcp_stdio_server.py @@ -1,5 +1,10 @@ -"""Offline FastMCP fixture with an appointment store shared via SQLite.""" +"""Offline FastMCP fixture with an appointment store shared via SQLite. +Usage: mcp_stdio_server.py DATABASE [PORT]. Without PORT it speaks stdio; with +PORT it serves Streamable HTTP on 127.0.0.1 only. +""" + +import inspect import sqlite3 import sys from contextlib import closing @@ -24,4 +29,12 @@ def book_appointment(patient: str, practitioner: str, start: str, end: str) -> s if __name__ == "__main__": - app.run(transport="stdio") + if len(sys.argv) < 3: + app.run(transport="stdio") + else: # second argument: serve Streamable HTTP on 127.0.0.1: instead + port = int(sys.argv[2]) + if "port" in inspect.signature(app.run_streamable_http_async).parameters: # mcp 2.x + app.run(transport="streamable-http", host="127.0.0.1", port=port) + else: # mcp 1.x reads host and port from settings + app.settings.host, app.settings.port = "127.0.0.1", port + app.run(transport="streamable-http") diff --git a/tests/test_adapters.py b/tests/test_adapters.py index 085e7f9..d32acac 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -169,6 +169,70 @@ async def scenario(): assert verdicts[0].claim.agent_said == "Booked." +def test_mcp_streamable_http_tool_write_is_verified_and_a_false_claim_fails(tmp_path): + pytest.importorskip("mcp") + import socket + import subprocess + + from anyio import fail_after, sleep + from mcp import ClientSession + from mcp.client.streamable_http import streamable_http_client + + from agent_readback import mcp_text + + database = tmp_path / "appointments.sqlite" + with closing(sqlite3.connect(database)) as connection: + connection.execute("CREATE TABLE appointments (patient TEXT PRIMARY KEY, practitioner TEXT, start TEXT, end TEXT)") + verifier = SqlRowVerifier( + lambda: sqlite3.connect(database.as_uri() + "?mode=ro", uri=True), "appointments", "patient", placeholder="?" + ) + with socket.socket() as probe: # ponytail: free port; tiny race until the server binds it + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + server_log = tmp_path / "server.log" + with server_log.open("w") as log_file: + process = subprocess.Popen( + [sys.executable, str(Path(__file__).with_name("mcp_stdio_server.py")), str(database), str(port)], + stdout=subprocess.DEVNULL, stderr=log_file, + ) + honest = dict(ARGS, patient="Patient/http-1") + lied_about = dict(ARGS, patient="Patient/http-2") + verdicts = [] + + async def scenario(): + with fail_after(30): # generous ceiling for a cold server start; normal run is ~2s + while True: # wait until uvicorn listens + try: + with socket.create_connection(("127.0.0.1", port), timeout=0.2): + break + except OSError: + assert process.poll() is None, server_log.read_text() + await sleep(0.1) + async with streamable_http_client(f"http://127.0.0.1:{port}/mcp") as streams: + async with ClientSession(streams[0], streams[1]) as session: # 1.x yields 3 values, 2.x yields 2 + await session.initialize() + + def claim(name, arguments): + expected = dict(arguments) + if arguments["patient"] == lied_about["patient"]: + expected["practitioner"] = "Practitioner/someone-else" # what the agent claims, not what it booked + return Claim("sql.row.insert", "", expected) + + book = watched(session.call_tool, verifier, claim, said=mcp_text, on_verdict=[verdicts.append]) + return [await book("book_appointment", honest), await book("book_appointment", lied_about)] + + try: + results = asyncio.run(scenario()) # mcp is installed by now: a hang is a real failure, never a skip + finally: + process.terminate() + process.wait(timeout=10) + + assert not any(getattr(r, "isError", getattr(r, "is_error", False)) for r in results) + assert [v.status for v in verdicts] == [Status.VERIFIED, Status.FAILED] + assert verdicts[0].claim.agent_said == "Booked." + assert [f.field for f in verdicts[1].findings] == ["practitioner"] # read back from the database, not the reply + + def test_langgraph_node(server, tools): pytest.importorskip("langgraph") from langgraph.graph import END as GRAPH_END diff --git a/tests/test_evidence_and_cli.py b/tests/test_evidence_and_cli.py index ffe1762..95e59a9 100644 --- a/tests/test_evidence_and_cli.py +++ b/tests/test_evidence_and_cli.py @@ -359,3 +359,123 @@ def test_bad_or_missing_anchor_file_exits_3(tmp_path): assert main(["verify-log", str(log.path), "--anchor", str(tmp_path / "missing.json")]) == 3 anchor.path.write_text('{"count": "3", "head": "x"}') assert main(["verify-log", str(log.path), "--anchor", str(anchor.path)]) == 3 + + +def test_new_log_is_readable_only_by_its_owner(tmp_path): + import os + import subprocess + + path = tmp_path / "log.jsonl" + EvidenceLog(path).append(verdict(0)) + if os.name != "nt": + assert path.stat().st_mode & 0o077 == 0 + return + acl = subprocess.run(["icacls", str(path)], capture_output=True, text=True, check=True).stdout + grants = [line for line in acl.splitlines() if ":(" in line] + assert len(grants) == 1 and "(I)" not in acl, acl # one explicit grant, nothing inherited + assert os.environ["USERNAME"].lower() in grants[0].lower() + for other in ("Everyone", "Users", "Authenticated Users", "Administrators", "SYSTEM"): + assert f"\\{other}:" not in acl and f" {other}:" not in acl + + +def test_log_still_written_when_owner_only_access_cannot_be_set(tmp_path, monkeypatch): + import os + import subprocess + + if os.name != "nt": + pytest.skip("owner-only access uses icacls on Windows only") + monkeypatch.setattr(subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 5, "", "Access is denied.")) + path = tmp_path / "log.jsonl" + with pytest.warns(RuntimeWarning, match="could not restrict"): + EvidenceLog(path).append(verdict(0)) + assert EvidenceLog(path).verify_chain() == (True, None) + + +def test_spoofed_username_cannot_lock_the_writer_out_of_its_own_log(tmp_path, monkeypatch): + import os + import subprocess + + if os.name != "nt": + pytest.skip("owner-only access uses icacls on Windows only") + me = os.environ["USERNAME"] + # A real, resolvable account that is not this process: the old code granted it the log. + monkeypatch.setenv("USERDOMAIN", "BUILTIN") + monkeypatch.setenv("USERNAME", "Guests") + monkeypatch.setenv("SystemRoot", str(tmp_path)) # a fake System32 here would have been run + path = tmp_path / "log.jsonl" + log = EvidenceLog(path) + log.append(verdict(0)) + log.append(verdict(1)) # failed with PermissionError when the grant went to the wrong account + assert EvidenceLog(path).verify_chain() == (True, None) + acl = subprocess.run(["icacls", str(path)], capture_output=True, text=True, check=True).stdout + assert "Guests" not in acl and me.lower() in acl.lower() + + +def test_log_is_restricted_before_its_first_record_is_written(tmp_path, monkeypatch): + from agent_readback import evidence + + sizes = [] + monkeypatch.setattr(evidence, "_owner_only", lambda path: sizes.append(path.stat().st_size)) + path = tmp_path / "log.jsonl" + log = EvidenceLog(path) + log.append(verdict(0)) + log.append(verdict(1)) + assert sizes == [0] # restricted once, while still empty; never again for an existing log + + +def test_icacls_failing_without_output_still_warns(tmp_path, monkeypatch): + import os + import subprocess + + if os.name != "nt": + pytest.skip("owner-only access uses icacls on Windows only") + + def fake_run(args, **kwargs): + if args[0].lower().endswith("whoami.exe"): + return subprocess.CompletedProcess(args, 0, '"host\\me","S-1-5-21-1-2-3-1001"\n', "") + return subprocess.CompletedProcess(args, 1, "", "") # icacls: failed, printed nothing + + monkeypatch.setattr(subprocess, "run", fake_run) + path = tmp_path / "log.jsonl" + with pytest.warns(RuntimeWarning, match="icacls exited with 1"): + EvidenceLog(path).append(verdict(0)) + assert EvidenceLog(path).verify_chain() == (True, None) + + +def test_explicit_access_entries_on_a_new_log_are_removed_too(tmp_path): + import os + import subprocess + + if os.name != "nt": + pytest.skip("owner-only access uses icacls on Windows only") + from agent_readback.evidence import _owner_only + + path = tmp_path / "log.jsonl" + path.touch() + icacls = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "icacls.exe") + # An explicit (not inherited) grant, as GitHub's Windows runners leave on new files. + subprocess.run([icacls, str(path), "/grant", "*S-1-5-32-545:R"], capture_output=True, check=True) # BUILTIN\Users + _owner_only(path) + acl = subprocess.run([icacls, str(path)], capture_output=True, text=True, check=True).stdout + grants = [line for line in acl.splitlines() if ":(" in line] + assert len(grants) == 1 and "BUILTIN\\Users" not in acl, acl # the path itself contains "Users" + + +def test_undecodable_tool_output_cannot_stop_the_first_append(tmp_path, monkeypatch): + import os + import subprocess + + if os.name != "nt": + pytest.skip("owner-only access uses icacls on Windows only") + calls = [] + + def run(args, **kwargs): + calls.append(kwargs) + raise UnicodeDecodeError("cp1252", b"\x81", 0, 1, "undefined byte in a localized message") + + monkeypatch.setattr(subprocess, "run", run) + path = tmp_path / "log.jsonl" + with pytest.warns(RuntimeWarning, match="could not restrict"): + EvidenceLog(path).append(verdict(0)) # used to raise out of append + assert EvidenceLog(path).verify_chain() == (True, None) + assert calls and calls[0].get("errors") == "replace" # real output is decoded tolerantly diff --git a/tests/test_langgraph_agent.py b/tests/test_langgraph_agent.py index 68b465d..52bdf5a 100644 --- a/tests/test_langgraph_agent.py +++ b/tests/test_langgraph_agent.py @@ -20,7 +20,7 @@ def test_every_done_is_verified_without_faults(tmp_path): def test_every_false_done_is_caught_when_the_server_lies(tmp_path): summary = run(runs=10, inject_faults=1.0, seed=1, log_path=tmp_path / "e.jsonl") - assert summary["outcomes"] == {"false_completion_caught": 10} and summary["chain_intact"] + assert summary["outcomes"] == {"false_completion": 10} and summary["chain_intact"] def test_cancel_through_tool_node_looks_up_patient_via_verifier(server, tools): @@ -68,7 +68,7 @@ def book(messages): chat = FakeChat([book, lambda m: AIMessage(content="DONE: booked.")]) summary = run(runs=1, inject_faults=1.0, seed=0, log_path=tmp_path / "e.jsonl", chat=chat) # every write is faulted (the server still answers ok), so the model's DONE must be caught - assert summary["outcomes"] == {"false_completion_caught": 1} and summary["chain_intact"] + assert summary["outcomes"] == {"false_completion": 1} and summary["chain_intact"] def test_failed_patient_lookup_still_logs_an_unverified_verdict(server, tmp_path): @@ -109,8 +109,10 @@ def test_outcome_labels_unclear_replies_and_retries(): bad = Verdict(Status.FAILED, claim, (Finding(FindingKind.MISSING, "gone"),)) assert outcome("I booked it.", [ok]) == "unclear_reply" assert outcome("DONE: booked", [bad, ok]) == "done_after_failed_write" - assert outcome("DONE: booked", [ok, bad]) == "false_completion_caught" + assert outcome("DONE: booked", [ok, bad]) == "false_completion" assert outcome("done: booked", [ok]) == "done_and_verified" + assert outcome("FAILED: no slot", [bad]) == "reported_failure" + assert outcome("FAILED: no slot", [ok]) == "said_failed_but_actually_done" assert text_of(AIMessage(content=["DONE:", {"type": "text", "text": "booked"}])) == "DONE: booked" @@ -138,4 +140,18 @@ def book_wrong_time(messages): chat = FakeChat([book_wrong_time, lambda m: AIMessage(content="DONE: booked.")]) summary = run(runs=1, inject_faults=0.0, seed=0, log_path=tmp_path / "e.jsonl", chat=chat) # the write itself verifies against the model's own arguments; the task check does not - assert summary["outcomes"] == {"false_completion_caught": 1} and summary["chain_intact"] + assert summary["outcomes"] == {"false_completion": 1} and summary["chain_intact"] + + +def test_failed_reply_is_classified_by_the_task_verdict_like_run_eval(): + from agent_readback import Claim, Finding, FindingKind, Verdict + from examples.healthcare.langgraph_agent import outcome + + claim = Claim("fhir.appointment.create", "", {}) + write_ok = Verdict(Status.VERIFIED, claim, ()) + task_failed = Verdict(Status.FAILED, claim, (Finding(FindingKind.WRONG_VALUE, "wrong time"),)) + task_ok = Verdict(Status.VERIFIED, claim, ()) + # The write held but at the wrong time, and the model said FAILED: the task did not complete. + assert outcome("FAILED: could not confirm", [write_ok], task_failed) == "reported_failure" + assert outcome("FAILED: could not confirm", [write_ok], task_ok) == "said_failed_but_actually_done" + assert outcome("FAILED: no slot", [write_ok]) == "said_failed_but_actually_done" # no task: write fallback diff --git a/tests/test_ratelimit.py b/tests/test_ratelimit.py new file mode 100644 index 0000000..a800468 --- /dev/null +++ b/tests/test_ratelimit.py @@ -0,0 +1,184 @@ +import asyncio +import sqlite3 +import threading +import time +from contextlib import closing + +import httpx +import pytest + +from agent_readback import Claim, FindingKind, RateLimit, RateLimitTimeout, Status, limit_reads, watch +from agent_readback.verifiers import FhirAppointmentVerifier, SqlRowVerifier + +from .conftest import DOCTOR, END, PATIENT, START, create_claim + + +class FakeClock: + def __init__(self): + self.now = 100.0 + self.slept = [] + + def __call__(self): + return self.now + + def sleep(self, seconds): + self.slept.append(round(seconds, 6)) + self.now += seconds + + +def test_burst_then_steady_rate_then_refill_after_idle(): + clock = FakeClock() + limit = RateLimit(per_second=5, burst=3, clock=clock, sleep=clock.sleep) + waits = [round(limit.acquire(), 6) for _ in range(5)] + assert waits == [0, 0, 0, 0.2, 0.2] # three at once, then one every 0.2 s + clock.now += 10 # idle: the bucket refills, but never beyond `burst` + assert [round(limit.acquire(), 6) for _ in range(4)] == [0, 0, 0, 0.2] + + +@pytest.mark.parametrize("per_second, burst", [(0, 1), (-1, 1), (float("nan"), 1), (1, 0), (1, 1.5)]) +def test_rejects_a_limit_that_would_never_or_wrongly_allow_reads(per_second, burst): + with pytest.raises(ValueError): + RateLimit(per_second, burst) + + +def test_fhir_verifier_waits_on_every_read_and_verdict_is_unchanged(server, tools): + clock = FakeClock() + limit = RateLimit(per_second=2, burst=1, clock=clock, sleep=clock.sleep) + sent = [] + + def handle(request): + sent.append(request.url.path) + return server._handle(request) + + client = limit_reads(httpx.Client(transport=httpx.MockTransport(handle), base_url="https://fhir.test"), limit) + with watch(FhirAppointmentVerifier(client), create_claim()) as watched: + tools["book_appointment"](PATIENT, DOCTOR, START, END) + assert watched.verdict.status is Status.VERIFIED + assert len(sent) >= 2 and len(clock.slept) == len(sent) - 1 # every read after the first waited + assert set(clock.slept) == {0.5} + + +def test_sql_connect_is_limited_and_reads_still_work(tmp_path): + path = tmp_path / "orders.db" + with closing(sqlite3.connect(path)) as db, db: + db.execute("CREATE TABLE orders (id TEXT, total INTEGER)") + clock = FakeClock() + limit = RateLimit(per_second=4, burst=1, clock=clock, sleep=clock.sleep) + verifier = SqlRowVerifier(limit_reads(lambda: sqlite3.connect(path), limit), "orders", "id", placeholder="?") + with watch(verifier, Claim("sql.row.insert", "DONE", {"id": "A1", "total": 5})) as watched: + with closing(sqlite3.connect(path)) as db, db: + db.execute("INSERT INTO orders VALUES ('A1', 5)") + assert watched.verdict.status is Status.VERIFIED + assert clock.slept == [0.25] # snapshot connection free, check connection waited + + +def test_threads_sharing_one_limit_never_exceed_it(): + limit = RateLimit(per_second=50, burst=1) # real clock: 10 reads must span at least 9 intervals + starts = [] + lock = threading.Lock() + + def read(): + limit.acquire() + with lock: + starts.append(time.monotonic()) + + threads = [threading.Thread(target=lambda: [read() for _ in range(2)]) for _ in range(5)] + began = time.monotonic() + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert len(starts) == 10 + assert max(starts) - began >= 9 * 0.02 * 0.9 # 10% slack for timer resolution, lower bound only + + +def test_wrong_targets_are_refused(): + limit = RateLimit(1) + async_client = httpx.AsyncClient() + try: + with pytest.raises(TypeError, match="AsyncClient"): + limit_reads(async_client, limit) + finally: + asyncio.run(async_client.aclose()) + with pytest.raises(TypeError, match="cannot rate-limit"): + limit_reads("https://fhir.test", limit) + + +def test_existing_request_hooks_are_kept(): + seen = [] + client = httpx.Client( + transport=httpx.MockTransport(lambda request: httpx.Response(200)), + event_hooks={"request": [lambda request: seen.append("mine")]}, + ) + clock = FakeClock() + limit_reads(client, RateLimit(1, clock=clock, sleep=clock.sleep)).get("https://x.test/") + client.get("https://x.test/") + assert seen == ["mine", "mine"] and clock.slept == [1.0] + + +def test_a_read_that_would_wait_past_max_wait_fails_fast_and_uses_no_slot(): + clock = FakeClock() + limit = RateLimit(1, clock=clock, sleep=clock.sleep, max_wait=0.5) + assert limit.acquire() == 0 + with pytest.raises(RateLimitTimeout, match="would wait 1.00s"): + limit.acquire() # next slot is 1 s away: more than max_wait + assert clock.slept == [] # it did not sleep first + clock.now += 1.0 + assert limit.acquire() == 0 # the refused read did not take the slot + + +def test_max_wait_makes_a_starved_verifier_unverified_instead_of_stalling(server, tools, tmp_path): + clock = FakeClock() # never advances on its own, so the second read always has to wait + limit = RateLimit(1, clock=clock, sleep=clock.sleep, max_wait=0) + client = limit_reads(httpx.Client(transport=httpx.MockTransport(server._handle), base_url="https://fhir.test"), limit) + with watch(FhirAppointmentVerifier(client), create_claim()) as watched: + tools["book_appointment"](PATIENT, DOCTOR, START, END) + assert watched.verdict.status is Status.UNVERIFIED # not FAILED, and no hang + assert [f.kind for f in watched.verdict.findings] == [FindingKind.UNREACHABLE] + assert clock.slept == [] + + path = tmp_path / "orders.db" + with closing(sqlite3.connect(path)) as db, db: + db.execute("CREATE TABLE orders (id TEXT, total INTEGER)") + sql_limit = RateLimit(1, clock=clock, sleep=clock.sleep, max_wait=0) + verifier = SqlRowVerifier(limit_reads(lambda: sqlite3.connect(path), sql_limit), "orders", "id", placeholder="?") + with watch(verifier, Claim("sql.row.insert", "DONE", {"id": "A1", "total": 5})) as watched: + with closing(sqlite3.connect(path)) as db, db: + db.execute("INSERT INTO orders VALUES ('A1', 5)") + assert watched.verdict.status is Status.UNVERIFIED + + +@pytest.mark.parametrize("max_wait", [-1, float("nan")]) +def test_rejects_a_negative_or_nan_max_wait(max_wait): + with pytest.raises(ValueError, match="max_wait"): + RateLimit(1, max_wait=max_wait) + + +def test_clock_and_sleep_still_work_by_position(): + clock = FakeClock() + limit = RateLimit(2, 1, clock, clock.sleep) + limit.acquire() + limit.acquire() + assert clock.slept == [0.5] and limit.max_wait is None + + +def test_limiting_the_same_target_twice_is_refused(): + limit = RateLimit(10) + with httpx.Client() as client, httpx.Client() as other: + limit_reads(client, limit) + with pytest.raises(ValueError, match="already rate-limited"): + limit_reads(client, limit) + limit_reads(other, limit) # a second client sharing the same limit is fine + connect = limit_reads(lambda: None, limit) + with pytest.raises(ValueError, match="already rate-limited"): + limit_reads(connect, limit) + + +@pytest.mark.parametrize("now", [100.0, 1e6, 1e7, 1e9]) # monotonic() counts from boot: months of uptime is ~1e7 s +def test_float_rounding_never_refuses_a_read_inside_a_fresh_burst(now): + for per_second in (0.3, 0.7, 3, 7, 9, 13, 30, 1000): + for burst in (1, 9, 10, 15, 25, 40): + limit = RateLimit(per_second, burst, clock=lambda: now, sleep=lambda s: None, max_wait=0) + assert [limit.acquire() for _ in range(burst)] == [0.0] * burst, (per_second, burst) + with pytest.raises(RateLimitTimeout): + limit.acquire() # one more than the burst still waits, so is still refused diff --git a/tests/test_stripe_sql_alerts.py b/tests/test_stripe_sql_alerts.py index 6abf02a..ca731ac 100644 --- a/tests/test_stripe_sql_alerts.py +++ b/tests/test_stripe_sql_alerts.py @@ -342,3 +342,58 @@ def test_alert_created_before_the_log_takes_its_key_is_not_sent(monkeypatch, tmp with watch(StripeRefundVerifier(stripe.client()), REFUND, on_verdict=[alert]): pass assert sent == [] and "evidence-log key" in str(alert.last_error) + + +def test_stripe_verifier_refuses_a_secret_key_that_could_also_create_refunds(): + transport = httpx.MockTransport(lambda request: httpx.Response(200, json={"data": [], "has_more": False})) + for key in ("sk_live_x", "sk_test_x"): + with pytest.raises(ValueError, match="restricted read-only key"): + StripeRefundVerifier(httpx.Client(transport=transport, auth=(key, ""))) # Basic, as Stripe documents + with pytest.raises(ValueError, match="restricted read-only key"): + StripeRefundVerifier(httpx.Client(transport=transport, headers={"Authorization": f"Bearer {key}"})) + StripeRefundVerifier(httpx.Client(transport=transport, auth=("rk_live_x", ""))) # restricted key accepted + StripeRefundVerifier(httpx.Client(transport=transport)) # no key at all (mocks, custom auth) still works + + +def test_sql_rejects_a_placeholder_that_smuggles_in_sql(tmp_path): + path = tmp_path / "orders.db" + with closing(sqlite3.connect(path)) as db, db: + db.execute("CREATE TABLE orders (id TEXT, total INTEGER)") + for hostile in ("? OR 1=1", "?; DROP TABLE orders", "'x' --", ""): + with pytest.raises(ValueError, match="unsafe SQL placeholder"): + SqlRowVerifier(lambda: sqlite3.connect(path), "orders", "id", placeholder=hostile) + for ok in ("?", "%s", ":id", ":1", "$1"): # every DB-API paramstyle still works + SqlRowVerifier(lambda: sqlite3.connect(path), "orders", "id", placeholder=ok) + with closing(sqlite3.connect(path)) as db: + assert db.execute("SELECT name FROM sqlite_master WHERE name = 'orders'").fetchone() # table survived + + +def test_stripe_key_check_never_runs_a_custom_auth_flow(): + calls = [] + + class TokenFetchingAuth(httpx.Auth): # e.g. OAuth: would make a network call per flow + def sync_auth_flow(self, request): + calls.append("sync") + raise RuntimeError("network call during construction") + yield request + + async def async_auth_flow(self, request): + calls.append("async") + yield request + + transport = httpx.MockTransport(lambda request: httpx.Response(200, json={"data": [], "has_more": False})) + StripeRefundVerifier(httpx.Client(transport=transport, auth=TokenFetchingAuth())) + StripeRefundVerifier(httpx.Client(transport=transport, auth=lambda request: request)) # function auth + assert calls == [] + with pytest.raises(ValueError, match="restricted read-only key"): # static secret keys are still refused + StripeRefundVerifier(httpx.Client(transport=transport, auth=httpx.BasicAuth("sk_live_x", ""))) + + +def test_stripe_key_check_does_not_run_a_basic_auth_subclass_flow(): + class CustomBasic(httpx.BasicAuth): # overrides the flow, so it is not "just a header" + def sync_auth_flow(self, request): + raise RuntimeError("custom flow ran during construction") + yield request + + transport = httpx.MockTransport(lambda request: httpx.Response(200, json={"data": [], "has_more": False})) + StripeRefundVerifier(httpx.Client(transport=transport, auth=CustomBasic("rk_live_x", "")))