Raven-1/tests/test_rpc_bugreport.py
江国庆/Forrest 55c145ceb8
feat(*): probe the bug report receiver and gate uploads with a challenge (#1015)
## Summary

Adds two things to bug reporting, on the Bug Report Receiver and on the
Raven clients that send to it.

**A hello probe.** The receiver answers `GET /v1/hello` with its service
name and protocol version, and Raven asks it before a report starts, so
a person learns that the receiver is down (or that the URL leads to
something else) before spending a redaction review on the report:

- `raven trajectory report-bug` and the trajectory browser's *Report a
bug* probe before collecting anything. On a TTY without `--yes` they ask
whether to continue (default no; declining collects and pins nothing).
With `--yes` they say they are continuing and keep the package if the
upload then fails. Without a TTY and without `--yes` the existing rule
still refuses first.
- The WebUI's *Report a problem* wizard asks the new RPC
`bugreport.probe` when it opens. When the receiver does not answer, the
report does not start: the wizard shows the reason and *Check again*,
and the primary button becomes *Continue anyway*, so going on is the
reader's explicit choice and never a dead end. A start pressed while the
check runs waits for it (at most 8 s) and then checks the form again.
- The probe runs under one deadline for the whole exchange (5 s), does
not follow redirects, and the new requests never echo credentials or
query tokens from a redirect target.
- `/healthz` stays as the operator's liveness check. It was not reused
for the probe because anything alive answers ok there, and it is not
under a base URL's path prefix.

**An upload challenge.** The receiver now takes only uploads that answer
its Upload Challenge: the client gets a challenge from `POST
/v1/challenge` and sends back an HMAC, under a constant built into
Raven, of the challenge and the package's report id, sha256 and size.
Key decisions:

- Shallow by design. The goal is that an HTTP client that is not Raven,
written without reading Raven's source, cannot upload. The constant is
published with the (public) source and is not configurable, so there are
no credentials to manage. The docs say so, with a table of what the gate
stops and what it does not.
- Stateless. Challenges are sealed with a per-process random key, are
valid for 300 s and are not consumed; a restart retires them all.
Replaying a captured upload as it was only re-delivers the same package,
which the receiver already answers as a duplicate; replaying it with
another package fails because the answer is bound to the package.
- Checked from the headers alone, after the existing header checks and
before the daily budget is reserved: a refused upload gets 401
(`unauthorized` or `challenge_expired`) with `WWW-Authenticate:
Raven-Challenge`, writes nothing, and still spends a rate-limit token.
Package checks, rate limits, budgets and timeouts are unchanged.
- The client fetches the challenge inside the upload's existing total
deadline. A 404 there means a receiver older than this Raven; a 401 is
retryable only when the challenge expired.

Uploading has not shipped in a release yet (it is under `Unreleased` in
the CHANGELOG), so no released client breaks. A receiver deployed from
main must be upgraded together with its clients, and a proxy in front of
it must forward all of `/v1/`; the docs and the CHANGELOG entry say so.

Commits, in order: the hello route and the client probe; the challenge
end to end (new `raven/trajectory/receiver_auth.py`, and the Upload
Challenge term in `CONTEXT.md`); the CLI probe; the WebUI probe (RPC,
wizard, i18n, regenerated ui-web and ui-tui bindings); a fix that checks
the form again after the wizard waits on the probe; the docs in both
languages; integration tests against real processes.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- `uv run --no-sync pytest tests/test_trajectory_receiver_auth.py
tests/test_trajectory_receiver.py tests/test_trajectory_upload.py
tests/test_rpc_bugreport.py tests/test_cli_trajectory_commands.py
tests/test_cli_trajectory_browse.py
tests/test_trajectory_report_session.py tests/test_rpc_schema_match.py
-q --idle-ceiling-strict --cov=raven --cov-branch
--cov-report=json:coverage.json`: 1190 passed.
- `make coverage-diff COVERAGE_BASE_REF=origin/main`: 99.53% of changed
lines (213/214), threshold 90%.
- `uv run --no-sync pytest
tests/integration/test_bug_report_upload_e2e.py
tests/integration/test_web_bugreport_e2e.py -m integration -n 0 -q`: 10
passed, three runs in a row.
- `uv run --no-sync pytest tests/ -q`: 102 failed, 33527 passed. All 102
are in 14 files this PR does not touch (code tools, code flow, subagent
probe and backends, a2a, whatsapp, provider config and rates, security
network, everos, tracing command), and the same 102 fail on the base
commit (checked on a worktree of `main`; the two failure sets are
identical).
- `make lint-python`, `make lint-imports` (10 contracts kept), `deptry
raven`: pass. `make lint-types`: only two `pyflakes.checker` unresolved
imports in
`agents/raven-code/plugins/code-flow/code_flow/tools/diagnostics.py`,
because pyflakes is not installed in the local environment (CI installs
all extras); every changed Python file passes `ty check`.
- `mkdocs build -f docs-site/mkdocs.yml --strict`: pass.
- ui-web: `gen:check`, `lint` (0 errors), `type-check`, `npx vitest run
--maxWorkers=8` (251 files, 4176 tests), `build` + `build.py` +
`check-page` / `check-css` / `check-class-namespace`: pass.
- ui-tui: `lint`, `lint:rpc`, `lint:i18n`, `type-check`, vitest (2242
tests), `build`: pass.
- `make check-source-language check-large-files check-commits`: pass.
- Manual, on real processes: a receiver plus curl (hello and challenge
answer; an upload without an answer, or with a forged one, gets 401 and
nothing is stored); the CLI (an upload while the receiver runs; while it
is down, the warning, continuing and the kept package; declining on a
TTY leaves nothing); a real gateway walked with Playwright in English
and Chinese at 1280 and 360 px (the warning while the receiver is down,
Check again after it starts, a report through to its receipt, no page
errors, no overflow).

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

User-visible changes:

- With an upload URL configured, `report-bug` and the browser's *Report
a bug* start with a probe of at most 5 s, and ask one more question when
the receiver does not answer. The WebUI wizard shows a warning and
*Continue anyway* in that case.
- The receiver refuses uploads that do not answer the challenge. A
receiver deployed from main must be upgraded together with its clients
(no released client uploads yet). A proxy that only forwarded
`/v1/bugreports` must forward all of `/v1/`.
- No change to package formats, `record.json`, or anything stored on
either side.

Rollback: revert the squash commit; there is nothing to migrate.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-10-20 10:22:53 +08:00

325 lines
14 KiB
Python

"""Tests for the ``bugreport.*`` RPC handlers (`raven.rpc.methods.bugreport`)."""
from __future__ import annotations
import json
import time
from pathlib import Path
from typing import Any
import pytest
from raven.rpc.dispatcher import Dispatcher
from raven.rpc.methods import bugreport as rpc_bugreport
from raven.rpc.methods import system as rpc_system
from raven.rpc.methods import trajectory_export as rpc_export
from raven.rpc.methods.bugreport import register_bugreport_methods
from raven.rpc.models import BugReportItemResult, BugReportStatusResult
from raven.session.manager import SessionManager
from raven.trajectory import bugreport as breport
from raven.trajectory import policy as tpol
from raven.trajectory import redaction_history as rhistory
from raven.trajectory import report_session as rs
from raven.trajectory.upload import UploadReceipt
SESSION = "tui:s1"
TOKEN = "aB3xK9mQ7pL2vR8sT4wZ6yN1"
@pytest.fixture(autouse=True)
def _isolated(tmp_path: Path, monkeypatch):
state = tmp_path / "traces"
(state / "logs").mkdir(parents=True)
monkeypatch.setenv("RAVEN_TRACING_DIR", str(state))
monkeypatch.setenv("RAVEN_BUGREPORT_URL", "https://receiver.example")
monkeypatch.setattr(breport, "collect_known_secrets", lambda _p: ([], True))
tpol._reset_for_tests()
manager = SessionManager(tmp_path / "workspace")
monkeypatch.setattr(rpc_export, "_manager", lambda _factory: manager)
monkeypatch.setattr(rpc_export, "_answering", lambda _key: False)
monkeypatch.setattr(rpc_bugreport, "_answering", lambda _key: False)
reports = rs.ReportSessions(history=lambda: rhistory.RedactionHistory(tmp_path / "history.json"))
monkeypatch.setattr(rs, "REPORTS", reports)
yield
reports.shutdown(timeout=10)
tpol._reset_for_tests()
def _turn(trace: str, minute: int, *, checkpoint: bool = False, dispatched_in: str | None = None) -> dict[str, Any]:
attrs: dict[str, Any] = {"session.key": SESSION, "turn.in_progress": checkpoint, "turn.input_preview": trace}
if dispatched_in:
attrs["trace.dispatched_in_trace_id"] = dispatched_in
return {
"traceId": trace,
"spanId": f"span-{trace}",
"name": "session.turn",
"startTime": f"2026-10-01T10:{minute:02d}:00+00:00",
"endTime": f"2026-10-01T10:{minute:02d}:30+00:00",
"attributes": attrs,
}
def _write(tmp_path: Path, *records: dict[str, Any]) -> None:
log = tmp_path / "traces" / "logs" / "audit-spans.log"
with log.open("a", encoding="utf-8") as handle:
for record in records:
handle.write(json.dumps(record) + "\n")
def _dispatcher() -> Dispatcher:
dispatcher = Dispatcher()
register_bugreport_methods(dispatcher)
return dispatcher
async def _call(dispatcher: Dispatcher, method: str, params: dict) -> dict:
response = await dispatcher.dispatch({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
assert response is not None
return response
def _start_params(trace_ids: list[str], description: str = f"the token {TOKEN} leaked") -> dict[str, Any]:
return {
"session_key": SESSION,
"trace_ids": trace_ids,
"problem": {"description": description, "severity": "medium"},
}
async def _wait(dispatcher: Dispatcher, report_id: str, phase: str) -> dict:
deadline = time.monotonic() + 10
while True:
status = (await _call(dispatcher, "bugreport.status", {"report_id": report_id}))["result"]
if status["phase"] == phase:
return status
assert time.monotonic() < deadline, status
time.sleep(0.02)
# -- a report through the rpc ----------------------------------------------------
async def test_a_report_is_decided_and_frozen_over_rpc(tmp_path):
_write(tmp_path, _turn("trace-a", 1))
dispatcher = _dispatcher()
started = await _call(dispatcher, "bugreport.start", _start_params(["trace-a"]))
rid = started["result"]["report_id"]
status = await _wait(dispatcher, rid, "deciding")
BugReportStatusResult.model_validate(status)
[item] = status["items"]
assert item["value"] == TOKEN and TOKEN not in item["masked_sample"]
contexts = (await _call(dispatcher, "bugreport.item", {"report_id": rid, "item_id": item["id"]}))["result"]
BugReportItemResult.model_validate(contexts)
decided = await _call(
dispatcher,
"bugreport.decide",
{"report_id": rid, "decisions": [{"item_id": item["id"], "action": "redacted"}], "acknowledged": []},
)
assert decided["result"] == {"ok": True}
status = await _wait(dispatcher, rid, "ready")
BugReportStatusResult.model_validate(status)
assert TOKEN not in json.dumps(status)
refused = await _call(dispatcher, "bugreport.upload", {"report_id": rid, "risk_accepted": False})
assert refused["error"]["code"] == -32028 and refused["error"]["data"]["reason"] == "risk_not_accepted"
assert (await _call(dispatcher, "bugreport.cancel", {"report_id": rid}))["result"] == {"ok": True}
# -- validation before the report exists ---------------------------------------------
@pytest.mark.parametrize(
"params",
[
{"session_key": SESSION, "trace_ids": ["trace-a"], "problem": {"description": "x", "severity": "urgent"}},
{"session_key": SESSION, "trace_ids": ["trace-a"], "problem": {"description": "x", "extra": 1}},
{"session_key": SESSION, "trace_ids": ["trace-a"]},
{"session_key": SESSION, "trace_ids": ["trace-a"], "problem": {"description": " "}},
],
)
async def test_bad_problem_fields_are_refused(params, tmp_path):
_write(tmp_path, _turn("trace-a", 1))
assert (await _call(_dispatcher(), "bugreport.start", params))["error"]["code"] == -32602
assert rs.REPORTS._reports == {}
async def test_the_running_turn_is_refused_before_any_report_exists(tmp_path, monkeypatch):
_write(tmp_path, _turn("trace-a", 1), _turn("trace-b", 3, checkpoint=True))
monkeypatch.setattr(rpc_bugreport, "_answering", lambda _key: True)
response = await _call(_dispatcher(), "bugreport.start", _start_params(["trace-b"]))
assert response["error"]["code"] == -32602
assert response["error"]["data"]["invalid"] == [{"trace_id": "trace-b", "why": "in_progress"}]
assert rs.REPORTS._reports == {}
assert not (tmp_path / "traces" / "bugreports").exists(), "no staging was created"
async def test_a_checkpoint_left_by_a_dead_process_can_be_reported(tmp_path):
_write(tmp_path, _turn("trace-a", 1), _turn("trace-b", 3, checkpoint=True))
dispatcher = _dispatcher()
started = await _call(dispatcher, "bugreport.start", _start_params(["trace-b"], "plain words only"))
await _wait(dispatcher, started["result"]["report_id"], "ready")
async def test_no_receiver_means_no_report(tmp_path, monkeypatch):
_write(tmp_path, _turn("trace-a", 1))
monkeypatch.delenv("RAVEN_BUGREPORT_URL")
assert (await _call(_dispatcher(), "bugreport.start", _start_params(["trace-a"])))["error"]["code"] == -32026
async def test_the_probe_reports_a_reachable_receiver(tmp_path, monkeypatch):
from aiohttp.test_utils import TestServer
from raven.trajectory import receiver as rcv
from tests.bug_report_receiver_stub import clear_proxy_env
clear_proxy_env(monkeypatch)
server = TestServer(rcv.build_app(rcv.ReceiverConfig(save_dir=tmp_path / "inbox")))
await server.start_server(**rcv.RUNNER_OPTIONS)
url = f"http://{server.host}:{server.port}"
monkeypatch.setenv("RAVEN_BUGREPORT_URL", url)
try:
response = await _call(_dispatcher(), "bugreport.probe", {})
finally:
await server.close()
assert response["result"] == {"reachable": True, "target": url, "reason": ""}
async def test_the_probe_reports_an_unreachable_receiver_as_an_answer(monkeypatch):
import socket
from tests.bug_report_receiver_stub import clear_proxy_env
clear_proxy_env(monkeypatch)
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
url = f"http://127.0.0.1:{sock.getsockname()[1]}"
sock.close()
monkeypatch.setenv("RAVEN_BUGREPORT_URL", url)
response = await _call(_dispatcher(), "bugreport.probe", {})
assert "error" not in response
result = response["result"]
assert result["reachable"] is False and result["target"] == url
assert "could not reach" in result["reason"]
async def test_the_probe_needs_a_receiver(monkeypatch):
monkeypatch.delenv("RAVEN_BUGREPORT_URL")
assert (await _call(_dispatcher(), "bugreport.probe", {}))["error"]["code"] == -32026
async def test_the_policy_off_refuses_every_method(tmp_path):
tpol.arm(False)
dispatcher = _dispatcher()
assert (await _call(dispatcher, "bugreport.start", _start_params(["trace-a"])))["error"]["code"] == -32020
for method, params in (
("bugreport.probe", {}),
("bugreport.status", {"report_id": "x"}),
("bugreport.item", {"report_id": "x", "item_id": "y"}),
("bugreport.decide", {"report_id": "x", "decisions": [], "acknowledged": []}),
("bugreport.upload", {"report_id": "x", "risk_accepted": True}),
("bugreport.retry_upload", {"report_id": "x"}),
("bugreport.cancel", {"report_id": "x"}),
):
assert (await _call(dispatcher, method, params))["error"]["code"] == -32020, method
# -- errors carry what the page needs ------------------------------------------------
@pytest.mark.parametrize(
("method", "params"),
[
("bugreport.status", {"report_id": "rs-nope"}),
("bugreport.item", {"report_id": "rs-nope", "item_id": "x"}),
("bugreport.decide", {"report_id": "rs-nope", "decisions": [], "acknowledged": []}),
("bugreport.upload", {"report_id": "rs-nope", "risk_accepted": True}),
("bugreport.retry_upload", {"report_id": "rs-nope"}),
("bugreport.cancel", {"report_id": "rs-nope"}),
],
)
async def test_an_unknown_report_is_named(method, params):
response = await _call(_dispatcher(), method, params)
assert response["error"]["code"] == -32024 and response["error"]["data"]["id"] == "rs-nope"
async def test_a_full_registry_names_its_limit(tmp_path, monkeypatch):
_write(tmp_path, _turn("trace-a", 1))
monkeypatch.setattr(rs, "REPORTS", rs.ReportSessions(limit=0))
response = await _call(_dispatcher(), "bugreport.start", _start_params(["trace-a"]))
assert response["error"]["code"] == -32025 and response["error"]["data"]["limit"] == 0
async def test_disagreeing_linked_items_come_back_as_a_conflict(tmp_path):
inner = "Hj5tR8uE3iO7pA1sD4fGk9lZ"
_write(tmp_path, _turn("trace-a", 1))
dispatcher = _dispatcher()
started = await _call(dispatcher, "bugreport.start", _start_params(["trace-a"], f"{inner} and {inner}W6xC2v"))
rid = started["result"]["report_id"]
items = (await _wait(dispatcher, rid, "deciding"))["items"]
response = await _call(
dispatcher,
"bugreport.decide",
{
"report_id": rid,
"decisions": [
{"item_id": items[0]["id"], "action": "kept"},
{"item_id": items[1]["id"], "action": "redacted"},
],
"acknowledged": [],
},
)
assert response["error"]["code"] == -32027
assert sorted(response["error"]["data"]["item_ids"]) == sorted(i["id"] for i in items)
async def test_a_wrong_phase_says_which(tmp_path):
_write(tmp_path, _turn("trace-a", 1))
dispatcher = _dispatcher()
started = await _call(dispatcher, "bugreport.start", _start_params(["trace-a"]))
rid = started["result"]["report_id"]
await _wait(dispatcher, rid, "deciding")
response = await _call(dispatcher, "bugreport.retry_upload", {"report_id": rid})
assert response["error"]["code"] == -32028
assert response["error"]["data"]["phase"] == "deciding" and response["error"]["data"]["reason"] == "not_retryable"
async def test_an_uploaded_report_answers_its_status_but_takes_no_more_steps(tmp_path, monkeypatch):
def delivered(record_dir: Path, *, base_url: str):
record = breport.load_record(record_dir)
return record, UploadReceipt("rcpt-1", record["report_id"], record["package"]["sha256"], 1, "now", False)
monkeypatch.setattr(rs, "upload_record", delivered)
_write(tmp_path, _turn("trace-a", 1))
dispatcher = _dispatcher()
started = await _call(dispatcher, "bugreport.start", _start_params(["trace-a"], "plain words only"))
rid = started["result"]["report_id"]
await _wait(dispatcher, rid, "ready")
await _call(dispatcher, "bugreport.upload", {"report_id": rid, "risk_accepted": True})
await _wait(dispatcher, rid, "uploaded")
deadline = time.monotonic() + 10
while rs.REPORTS._reports:
assert time.monotonic() < deadline
time.sleep(0.02)
status = (await _call(dispatcher, "bugreport.status", {"report_id": rid}))["result"]
BugReportStatusResult.model_validate(status)
assert status["receipt"]["receipt_id"] == "rcpt-1"
response = await _call(dispatcher, "bugreport.retry_upload", {"report_id": rid})
assert response["error"]["code"] == -32028 and response["error"]["data"]["phase"] == "uploaded"
assert (await _call(dispatcher, "bugreport.cancel", {"report_id": rid}))["result"] == {"ok": True}
assert (await _call(dispatcher, "bugreport.status", {"report_id": rid}))["error"]["code"] == -32024
# -- the handshake --------------------------------------------------------------------
def test_the_handshake_announces_bug_reports_only_with_a_valid_receiver(monkeypatch, caplog):
assert rpc_system.BUGREPORT_CAPABILITY in rpc_system.server_capabilities()
monkeypatch.delenv("RAVEN_BUGREPORT_URL")
assert rpc_system.BUGREPORT_CAPABILITY not in rpc_system.server_capabilities()
monkeypatch.setattr(rpc_system, "_bugreport_url_warned", False)
warnings: list[str] = []
monkeypatch.setattr(rpc_system.logger, "warning", lambda message, *args: warnings.append(message))
monkeypatch.setenv("RAVEN_BUGREPORT_URL", "http://receiver.example")
assert rpc_system.BUGREPORT_CAPABILITY not in rpc_system.server_capabilities()
assert rpc_system.BUGREPORT_CAPABILITY not in rpc_system.server_capabilities()
assert len(warnings) == 1, "an invalid receiver is logged once"