HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
conformance: cover session sharing, the one Full chapter nothing tests (#44)
Hashem Aldhaheriaf30eb3994b6
diff --git a/protocol/conformance/README.md b/protocol/conformance/README.mdindex eb60f495..374a928d 100644--- a/protocol/conformance/README.md+++ b/protocol/conformance/README.md@@ -37,13 +37,13 @@ anything that only inspects a schema.## What it checks-52 checks across three classes.+59 checks across three classes.| Class | Checks | Covers ||---|---|---|| **Core** | 37 | Discovery, version negotiation, authentication, the error envelope, harnesses, models, task execution (streaming and not), the event stream, sessions, cancellation || **Extended** | +8 | Session listing and inspection, file input, artifacts, download headers, path-traversal probes |-| **Full** | +7 | Harness create / update / delete, refusal of an unsupported base, skill-folder round trip, MCP and disabled-tool persistence |+| **Full** | +14 | Harness create / update / delete, refusal of an unsupported base, skill-folder round trip, MCP and disabled-tool persistence, session sharing |Every check names the section of the specification it enforces, so a failure points at the sentenceit violates rather than at a test name.@@ -64,6 +64,15 @@ A few of them are worth calling out, because they catch things a schema check neown origin.- **X-08** — artifact ids do not traverse out of their container. Probes for `../` and itspercent-encoded form.+- **R-01…R-07** — session sharing, which is mostly a set of refusals. Sessions §5 requires that a+ shared view be read-only, revocable, and free of credentials, and a check that merely opens a+ link and reads the conversation passes against a server that also lets that link continue the+ task, cancel the run, or upload into the working directory. §5 makes sharing optional, so these+ skip rather than fail on a server that does not implement it; and because §5 names no endpoint+ for the view or for revocation, they discover both from what the server returned and skip with+ the missing sentence as the reason. `tests/test_session_sharing_checks.py` runs the series+ against a deliberately wrong server, one defect at a time, so each of them is known to fail on+ the mistake it describes.- **F-03/F-04** — a skill is a folder, and it survives an unrelated edit. A server that stores only`SKILL.md`, or that empties a bundle when the harness is renamed, passes every other check: theconfig still looks right, and the loss only shows up later as an agent behaving oddly.@@ -104,6 +113,9 @@ a live instance on 2026-08-11:CONFORMANT — UHP 2026-08-11 (full)```+That run predates the `R-` series, so it is a 52-check result and has not been re-measured+against the 59.+The suite is developed against that implementation, which is exactly why the specification saysconformance is defined by the suite and not by the implementation: anything the reference does thatthe suite does not require is a HarnessRouter behaviour, not a UHP requirement, and anotherdiff --git a/protocol/conformance/tests/share_defect_stub.py b/protocol/conformance/tests/share_defect_stub.pynew file mode 100644index 00000000..dedf4bda--- /dev/null+++ b/protocol/conformance/tests/share_defect_stub.py@@ -0,0 +1,212 @@+"""A deliberately wrong UHP server, with one toggleable defect per rule in Sessions §5.++The R-series checks what a shared view REFUSES, and a check that only ever passes proves+nothing about a refusal. So this stub implements just enough of the protocol for those checks+to run, and takes a DEFECT environment variable naming one thing to get wrong.+test_session_sharing_checks.py drives it once per defect and asserts the diagonal.++It answers every task itself, so the matrix needs no credentials, no network and no agent+tokens, and finishes in seconds.++ DEFECT=revoke_lies PORT=8931 python3 share_defect_stub.py+"""+from __future__ import annotations++import json+import os+import time+import uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlsplit++DEFECT = os.environ.get("DEFECT", "none")+PORT = int(os.environ.get("PORT", "8931"))+KEY = "stub-key"++DEFECTS = {+ "none",+ "view_needs_auth", # the "published" view demands the owner's credential+ "get_share_disagrees", # GET /share reports a different link from the one POST minted+ "share_id_is_token", # the share id authenticates the real API+ "view_accepts_writes", # the shared view accepts a write from a link holder+ "leaks_credentials", # the view carries the harness's MCP auth and headers+ "revoke_lies", # revocation answers 200 and revokes nothing+ "multi_mint", # every POST mints a new link; revocation kills only the newest+ "share_outlives_session", # the link survives the deletion of its session+}+assert DEFECT in DEFECTS, f"unknown defect {DEFECT!r}; one of {sorted(DEFECTS)}"++SESSIONS: dict[str, dict] = {} # session_id -> {"deleted": bool}+SHARES: dict[str, str] = {} # share_id -> session_id+BY_SESSION: dict[str, list[str]] = {} # session_id -> [share_id] in mint order+++def view_of(session_id: str) -> dict:+ v = {"object": "session.shared", "session": {"id": session_id, "object": "session"},+ "harness": {"id": "h1", "name": "stub", "base": "stub"}}+ if DEFECT == "leaks_credentials":+ v["harness"]["mcpServers"] = [{"name": "internal", "url": "https://mcp.example.invalid",+ "auth": {"type": "bearer", "token": "sk-live-not-yours"},+ "headers": {"x-api-key": "sk-live-not-yours"}}]+ return v+++class H(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *a): # quiet+ pass++ # ── plumbing ──────────────────────────────────────────────────────────────────────+ def send(self, status: int, payload=None):+ body = b"" if payload is None else json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("content-type", "application/json")+ self.send_header("uhp-version", "2026-08-11")+ self.send_header("content-length", str(len(body)))+ self.end_headers()+ if body:+ self.wfile.write(body)++ def bearer(self) -> str:+ return (self.headers.get("authorization") or "").removeprefix("Bearer ").strip()++ def authed(self) -> bool:+ tok = self.bearer()+ if tok == KEY:+ return True+ return DEFECT == "share_id_is_token" and tok in SHARES++ def read_body(self):+ n = int(self.headers.get("content-length") or 0)+ if n:+ self.rfile.read(n)++ def path_parts(self):+ return [p for p in urlsplit(self.path).path.split("/") if p]++ # ── routing ───────────────────────────────────────────────────────────────────────+ def do_GET(self):+ self.route("GET")++ def do_POST(self):+ self.route("POST")++ def do_PUT(self):+ self.route("PUT")++ def do_PATCH(self):+ self.route("PATCH")++ def do_DELETE(self):+ self.route("DELETE")++ def route(self, method: str):+ self.read_body()+ p = self.path_parts()++ # Discovery, unauthenticated.+ if method == "GET" and p == ["v1", "uhp"]:+ return self.send(200, {+ "object": "uhp.discovery", "versions": ["2026-08-11"],+ "default_version": "2026-08-11", "conformance_class": "full",+ "capabilities": {"streaming": True, "sessions": True, "cancellation": True,+ "files_input": True, "files_output": True,+ "session_listing": True, "harness_management": True,+ "session_sharing": True}})++ # The shared view: reached by whoever holds the link.+ if p[:2] == ["v1", "shares"] and len(p) >= 3:+ return self.shared_view(method, p[2])++ # Everything else needs the API credential.+ if not self.authed():+ return self.send(401, {"error": {"code": "unauthorized", "message": "no credential"}})++ if method == "GET" and p == ["v1", "harnesses"]:+ return self.send(200, {"harnesses": [{"id": "h1", "name": "stub", "base": "stub"}]})+ if method == "GET" and p in (["v1", "sessions"], ["v1", "responses"]):+ return self.send(200, {p[1]: []})+ if method == "POST" and p == ["v1", "responses"]:+ sid = f"sess_{uuid.uuid4().hex[:10]}"+ SESSIONS[sid] = {"deleted": False}+ return self.send(200, {+ "id": f"resp_{uuid.uuid4().hex[:10]}", "object": "response", "status": "completed",+ "model": "stub-1", "usage": None, "created_at": int(time.time()),+ "output": [{"type": "message", "role": "assistant",+ "content": [{"type": "output_text", "text": "ok"}]}],+ "metadata": {"session_id": sid, "harness_id": "h1"}})+ if p[:2] == ["v1", "sessions"] and len(p) >= 4 and p[3] == "share":+ return self.share_endpoint(method, p[2], p[4:])+ if method == "DELETE" and p[:2] == ["v1", "traces"] and len(p) == 3:+ return self.delete_session(p[2])+ return self.send(404, {"error": {"code": "not_found", "message": "no such endpoint"}})++ # ── Sessions §5 ───────────────────────────────────────────────────────────────────+ def share_endpoint(self, method: str, sid: str, rest: list[str]):+ if sid not in SESSIONS or SESSIONS[sid]["deleted"]:+ return self.send(404, {"error": {"code": "session_not_found", "message": "gone"}})+ existing = BY_SESSION.get(sid) or []++ if method == "POST" and not rest:+ if existing and DEFECT != "multi_mint":+ return self.send(200, self.share_body(existing[-1], sid))+ share_id = f"share_{uuid.uuid4().hex[:12]}"+ SHARES[share_id] = sid+ BY_SESSION.setdefault(sid, []).append(share_id)+ return self.send(200, self.share_body(share_id, sid))++ if method == "GET" and not rest:+ if not existing:+ return self.send(404, {"error": {"code": "share_not_found", "message": "none"}})+ if DEFECT == "get_share_disagrees":+ return self.send(200, {**self.share_body(existing[-1], sid),+ "url": f"http://127.0.0.1:{PORT}/v1/shares/share_elsewhere"})+ return self.send(200, self.share_body(existing[-1], sid))++ if method == "DELETE" and not rest:+ if not existing:+ return self.send(404, {"error": {"code": "share_not_found", "message": "none"}})+ newest = existing[-1]+ if DEFECT != "revoke_lies":+ doomed = [newest] if DEFECT == "multi_mint" else list(existing)+ for s in doomed:+ SHARES.pop(s, None)+ BY_SESSION[sid] = [s for s in existing if s not in doomed]+ return self.send(200, {"id": newest, "object": "session.share", "deleted": True})++ return self.send(405, {"error": {"code": "method_not_allowed", "message": "no"}})++ def share_body(self, share_id: str, sid: str) -> dict:+ return {"id": share_id, "object": "session.share", "session_id": sid,+ "url": f"http://127.0.0.1:{PORT}/v1/shares/{share_id}",+ "created_at": int(time.time())}++ def shared_view(self, method: str, share_id: str):+ if DEFECT == "view_needs_auth" and self.bearer() != KEY:+ return self.send(401, {"error": {"code": "unauthorized", "message": "sign in"}})+ sid = SHARES.get(share_id)+ if not sid:+ return self.send(404, {"error": {"code": "not_found", "message": "no such share"}})+ if SESSIONS.get(sid, {}).get("deleted") and DEFECT != "share_outlives_session":+ return self.send(404, {"error": {"code": "not_found", "message": "no such share"}})+ if method == "GET":+ return self.send(200, view_of(sid))+ if DEFECT == "view_accepts_writes":+ return self.send(200, {"ok": True})+ return self.send(405, {"error": {"code": "method_not_allowed", "message": "read-only"}})++ # ── Sessions §6 ───────────────────────────────────────────────────────────────────+ def delete_session(self, sid: str):+ if sid not in SESSIONS:+ return self.send(404, {"error": {"code": "session_not_found", "message": "gone"}})+ SESSIONS[sid]["deleted"] = True+ if DEFECT != "share_outlives_session":+ for s in BY_SESSION.pop(sid, []):+ SHARES.pop(s, None)+ return self.send(200, {"id": sid, "object": "session", "deleted": True})+++if __name__ == "__main__":+ print(f"stub: defect={DEFECT} port={PORT}", flush=True)+ ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()diff --git a/protocol/conformance/tests/test_session_sharing_checks.py b/protocol/conformance/tests/test_session_sharing_checks.pynew file mode 100644index 00000000..139348bb--- /dev/null+++ b/protocol/conformance/tests/test_session_sharing_checks.py@@ -0,0 +1,121 @@+"""The R-series is tested the way it asks servers to be tested: by being shown to fail.++Sessions §5 is mostly a list of refusals, and a check that only ever passes cannot tell a+server that refuses from one that does not — D-05 passed against real servers for months while+being vacuous, which is the failure this file exists to avoid repeating.++So every R- check is run against a deliberately wrong server (share_defect_stub.py) carrying+one defect at a time. Each defect must be caught by the check that claims to cover it, and a+clean server must pass all seven. The stub answers every task itself, so this needs no+credentials, no network and no agent tokens.+"""+from __future__ import annotations++import pathlib+import socket+import subprocess+import sys+import time+import urllib.error+import urllib.request++import pytest++from uhp_conformance import checks # noqa: F401 — importing populates the registry+from uhp_conformance.client import Client+from uhp_conformance.context import Context+from uhp_conformance.registry import REGISTRY, Outcome++STUB = pathlib.Path(__file__).parent / "share_defect_stub.py"++# Each defect, and the check whose message names exactly that mistake.+CAUGHT_BY = {+ "view_needs_auth": "R-01",+ "get_share_disagrees": "R-02",+ "share_id_is_token": "R-03",+ "view_accepts_writes": "R-04",+ "leaks_credentials": "R-05",+ "revoke_lies": "R-06",+ "multi_mint": "R-06",+ "share_outlives_session": "R-07",+}+++def _free_port() -> int:+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def _run_series(defect: str) -> dict[str, Outcome]:+ """Every R- check against a stub carrying `defect`, in registration order."""+ port = _free_port()+ srv = subprocess.Popen([sys.executable, str(STUB)],+ env={"DEFECT": defect, "PORT": str(port), "PATH": "/usr/bin:/bin"},+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ deadline = time.time() + 10+ while time.time() < deadline:+ try:+ urllib.request.urlopen(f"http://127.0.0.1:{port}/v1/uhp", timeout=1).read()+ break+ except (urllib.error.URLError, OSError):+ time.sleep(0.05)+ else:+ pytest.fail(f"the stub did not start for defect {defect!r}")++ # A fresh context per defect: the checks cache the share they minted, and a cache carried+ # between servers would test the previous one.+ ctx = Context(client=Client(f"http://127.0.0.1:{port}", "stub-key"), task_timeout=30.0)+ return {c.id: c.run(ctx).outcome for c in REGISTRY if c.id.startswith("R-")}+ finally:+ srv.terminate()+ srv.wait(timeout=5)+++def test_the_series_is_registered_at_full():+ ids = [c.id for c in REGISTRY if c.id.startswith("R-")]+ assert ids == [f"R-0{i}" for i in range(1, 8)]+ assert {c.cls for c in REGISTRY if c.id.startswith("R-")} == {"full"}+++def test_a_conformant_server_passes_every_check():+ out = _run_series("none")+ assert all(o is Outcome.PASS for o in out.values()), out++[email protected]("defect,expected", sorted(CAUGHT_BY.items()))+def test_each_defect_is_caught_by_its_own_check(defect, expected):+ out = _run_series(defect)+ assert out[expected] is Outcome.FAIL, (+ f"{defect!r} was not caught by {expected}: {out}")++[email protected]("defect,expected", sorted(CAUGHT_BY.items()))+def test_no_other_check_reports_a_failure_for_that_defect(defect, expected):+ """One defect, one red check.++ A second failure elsewhere is not extra safety — it is a misleading diagnosis, and it is how+ a reviewer ends up chasing the wrong sentence of the specification. Where a defect genuinely+ makes another check unrunnable (a view that never resolved cannot be observed to stop+ resolving), the check is expected to skip rather than to guess.+ """+ out = _run_series(defect)+ also_failed = [i for i, o in out.items() if o is Outcome.FAIL and i != expected]+ assert not also_failed, f"{defect!r} also failed {also_failed}, which diagnoses one bug twice"+++def test_a_view_that_never_resolved_makes_the_later_checks_skip():+ out = _run_series("view_needs_auth")+ assert out["R-01"] is Outcome.FAIL+ for i in ("R-04", "R-05", "R-06", "R-07"):+ assert out[i] is Outcome.SKIP, (+ f"{i} should skip when the view never resolved, got {out[i]}: 'stops resolving' and "+ "'never resolved' are indistinguishable there")+++def test_no_check_errors_on_any_defect():+ """An ERROR is a bug in the suite. It must never be how a defect gets reported."""+ for defect in ["none", *CAUGHT_BY]:+ out = _run_series(defect)+ assert Outcome.ERROR not in out.values(), f"{defect}: {out}"diff --git a/protocol/conformance/uhp_conformance/checks.py b/protocol/conformance/uhp_conformance/checks.pyindex bf47eb36..a4c0ee71 100644--- a/protocol/conformance/uhp_conformance/checks.py+++ b/protocol/conformance/uhp_conformance/checks.py@@ -825,3 +825,298 @@ def f02(ctx):"accepts a base it cannot run fails at task time instead, after the client has committed.")if r.status == 200: # defensive: clean up if the server accepted it after allctx.client.delete(f"/v1/harnesses/{(r.json or {}).get('id')}")+++# ══════════════════════════════════════════════════════════════════════════════════════+# Full — session sharing+# ══════════════════════════════════════════════════════════════════════════════════════+# Sessions §5 is the Full requirement this suite could not see, and it is the one where a+# happy-path check would be worse than no check at all: almost every sentence in §5 is about+# what the server REFUSES. A check that minted a link and read the conversation back would+# pass against a server that also let that link continue the task, cancel the run, or upload+# into the working directory — and an unauthenticated write path into someone's working+# directory is about as bad as a defect in this protocol gets.+#+# §5 says a server MAY publish a shared view, so every check below skips — never fails — on a+# server that does not implement sharing. What is not optional is the shape of it once it does.+#+# §5 names two endpoints and no others: it does not say where the view is served, and it does+# not name a revocation path. So these checks discover both from what the server itself+# returned, rather than assuming any one implementation's URLs. Where discovery is impossible+# the check skips and names the missing sentence, because that is a gap in the specification+# rather than a defect in the server being tested.++# Keys whose non-empty presence in a shared view would breach §5's third bullet. `headers` and+# `env` are here because that is where an MCP server's credentials live (Harnesses §4.1).+_SECRET_KEYS = {"auth", "authorization", "api_key", "apikey", "token", "access_token",+ "refresh_token", "secret", "password", "credentials", "env", "headers"}+++def _walk(node, path="$"):+ """Every (json-path, key, value) pair in a document, so a finding can say where it is."""+ if isinstance(node, dict):+ for k, v in node.items():+ here = f"{path}.{k}"+ yield here, k, v+ yield from _walk(v, here)+ elif isinstance(node, list):+ for i, v in enumerate(node):+ yield from _walk(v, f"{path}[{i}]")+++def _view_path(ctx, url: str) -> str:+ """The client-relative path for a URL the server handed back.++ The share URL may be absolute or relative, and the base URL may carry a path prefix+ (`https://host/api/harness`), so neither can simply be concatenated. A view on a different+ origin is not something this suite can attest, and says so rather than guessing.+ """+ from urllib.parse import urlsplit+ base, u = urlsplit(ctx.client.base_url), urlsplit(url)+ if u.netloc and u.netloc != base.netloc:+ raise Skip(f"the shared view is served on another origin ({u.netloc}), which this suite "+ "cannot reach or attest")+ prefix = base.path.rstrip("/")+ path = u.path if not prefix or not u.path.startswith(prefix) else u.path[len(prefix):]+ return path + (f"?{u.query}" if u.query else "")+++def _shared_session_id(ctx) -> str:+ sid = ctx.state.get("session_id")+ if sid:+ return sid+ sid = ((_run_blocking(ctx).json or {}).get("metadata") or {}).get("session_id")+ if not sid:+ raise Skip("no session id from an earlier task, so there is nothing to share")+ return sid+++def _share(ctx) -> dict:+ """Mint the share once and cache it, or skip with the reason it could not be minted."""+ if "share" in ctx.state:+ got = ctx.state["share"]+ if isinstance(got, str): # a cached skip reason: do not re-POST on every check+ raise Skip(got)+ return got++ def _skip(reason):+ ctx.state["share"] = reason+ raise Skip(reason)++ caps = (ctx.state.get("discovery") or {}).get("capabilities") or {}+ if caps.get("session_sharing") is False:+ _skip("this server reports session_sharing false, and Sessions §5 is a MAY")+ sid = _shared_session_id(ctx)+ r = ctx.client.post(f"/v1/sessions/{sid}/share")+ if r.status in (404, 405, 501):+ _skip(f"POST /v1/sessions/{{id}}/share returned HTTP {r.status}: this server does not "+ "publish shared views, which Sessions §5 permits")+ if r.status != 200 or not isinstance(r.json, dict):+ _skip(f"POST /v1/sessions/{{id}}/share returned HTTP {r.status}, which is neither a share "+ f"nor a refusal this check can read: {r.body[:160]!r}")+ d = r.json+ url = next((d[k] for k in ("url", "share_url", "href", "link", "location")+ if isinstance(d.get(k), str) and d[k]), "") or r.header("location")+ if not url:+ _skip("the share carries no URL, and Sessions §5 does not say where a shared view is "+ f"served, so this check cannot locate it (keys: {sorted(d)[:8]}). The specification "+ "should name the view's endpoint, or the share object should be schema'd with a "+ "field that does.")+ share = {"id": d.get("id") or "", "url": url, "path": _view_path(ctx, url), "session_id": sid,+ "body": d}+ ctx.state["share"] = share+ return share+++@check("R-01", "A shared session is published, and the link alone opens it", "full",+ f"{SPEC}/sessions.md#5-session-sharing")+def r01(ctx):+ sh = _share(ctx)+ r = ctx.client.get(sh["path"], auth=False)+ assert r.status == 200, (+ f"the URL the server published for this share returned HTTP {r.status} when opened with no "+ "credential. Sessions §5 is about publishing a view: one that only the principal who minted "+ "it can open has not been published to anyone.")+ ctx.state["share_readable"] = True+ body = r.json+ assert body is not None, f"the shared view is not JSON: {r.body[:120]!r}"+ return f"readable unauthenticated at {sh['path']}"+++@check("R-02", "The share can be read back from the endpoint that minted it", "full",+ f"{SPEC}/sessions.md#5-session-sharing")+def r02(ctx):+ sh = _share(ctx)+ r = ctx.client.get(f"/v1/sessions/{sh['session_id']}/share")+ assert r.status == 200, (+ f"GET /v1/sessions/{{id}}/share returned HTTP {r.status} for a session that has a share. §5 "+ "names this endpoint, and a client that has lost the link has nowhere else to ask.")+ d = r.json or {}+ got = next((d[k] for k in ("url", "share_url", "href", "link", "location")+ if isinstance(d.get(k), str) and d[k]), "")+ assert got, f"the share read back carries no URL (keys: {sorted(d)[:8]})"+ assert _view_path(ctx, got) == sh["path"], (+ f"GET reports a different view ({_view_path(ctx, got)}) from the one POST published "+ f"({sh['path']}). A client cannot revoke, or even name, a link it is told two versions of.")+ if sh["id"] and d.get("id"):+ assert d["id"] == sh["id"], f"share id changed between POST and GET: {sh['id']} → {d['id']}"+ return "GET agrees with POST"+++@check("R-03", "A share id is not a credential for the API", "full",+ f"{SPEC}/sessions.md#5-session-sharing")+def r03(ctx):+ sh = _share(ctx)+ ident = sh["id"] or sh["path"].rstrip("/").rsplit("/", 1)[-1]+ if not ident:+ raise Skip("the share exposes no id to present as a token")+ # Only endpoints this server actually serves to the real credential can say anything about a+ # wrong one: a 404 or a 405 is the router declining a path, not the guard declining a token.+ guarded = [p for p in ("/v1/sessions", "/v1/responses", "/v1/harnesses")+ if 200 <= ctx.client.get(p).status < 300]+ if not guarded:+ raise Skip("no authenticated GET endpoint answered the real credential, so nothing here "+ "can distinguish a refused token from an absent route")+ accepted = [f"{p} → HTTP {r.status}" for p, r in+ ((p, ctx.client.get(p, headers={"authorization": f"Bearer {ident}"}))+ for p in guarded)+ if 200 <= r.status < 300]+ assert not accepted, (+ "the share id is accepted as a bearer token: " + "; ".join(accepted) + ". §5 forbids a "+ "shared view exposing another principal's data, and a link that authenticates the API "+ "exposes all of it — every session, every response, every configured harness.")+ return f"refused on {len(guarded)} endpoint(s)"+++@check("R-04", "The shared view is read-only", "full", f"{SPEC}/sessions.md#5-session-sharing")+def r04(ctx):+ sh = _share(ctx)+ if not ctx.state.get("share_readable"):+ raise Skip("the shared view did not resolve (see R-01), so what it refuses cannot be read")+ view = sh["path"].split("?")[0].rstrip("/")+ probes = [("POST", view), ("PUT", view), ("PATCH", view), ("DELETE", view),+ # The three §5 names outright, at the paths this protocol uses for them elsewhere.+ ("POST", f"{view}/cancel"), ("POST", f"{view}/responses"), ("POST", f"{view}/files")]+ accepted = []+ for method, path in probes:+ body = {} if method != "DELETE" else None+ r = ctx.client.request(method, path, body=body, auth=False)+ if 200 <= r.status < 300:+ accepted.append(f"{method} {path} → HTTP {r.status}")+ assert not accepted, (+ "the shared view accepted a write from a caller holding only the link: "+ + "; ".join(accepted) + ". §5: the view MUST NOT permit continuing, cancelling, or "+ "uploading. This is an unauthenticated write into someone else's session.")+ return f"{len(probes)} write probes refused"+++@check("R-05", "The shared view exposes no credentials", "full",+ f"{SPEC}/sessions.md#5-session-sharing")+def r05(ctx):+ sh = _share(ctx)+ if not ctx.state.get("share_readable"):+ raise Skip("the shared view did not resolve (see R-01), so its contents cannot be read")+ r = ctx.client.get(sh["path"], auth=False)+ raw = r.body.decode("utf-8", "replace")+ if ctx.client.api_key:+ assert ctx.client.api_key not in raw, (+ "the shared view contains this client's API key verbatim. §5: a shared view MUST NOT "+ "expose provider credentials or tokens.")+ leaks = [p for p, k, v in _walk(r.json)+ if k.lower() in _SECRET_KEYS and v not in (None, "", {}, [], False)]+ assert not leaks, (+ f"the shared view carries credential-shaped fields with values: {leaks[:5]}. §5 forbids "+ "exposing provider credentials or tokens; Harnesses §4.1 puts an MCP server's `auth` and "+ "`headers` among them, and the holder of a link is a client that presented nothing.")+ return "no credential-shaped fields"+++@check("R-06", "Revocation kills every link minted for the session", "full",+ f"{SPEC}/sessions.md#5-session-sharing")+def r06(ctx):+ sh = _share(ctx)+ if not ctx.state.get("share_readable"):+ raise Skip("the shared view never resolved (see R-01), so 'stops resolving' cannot be "+ "distinguished from 'never resolved'")+ sid = sh["session_id"]++ # Share the session a second time before revoking. §5 does not say whether a second POST+ # returns the first link or mints another, and this check does not require either — but+ # whichever it did, revocation has to reach what it produced. A server that hands out a+ # second link and then revokes only the newest has told the operator the session is private+ # while a live link to it is still in someone's hands.+ live = [sh["path"]]+ again = ctx.client.post(f"/v1/sessions/{sid}/share")+ if again.status == 200 and isinstance(again.json, dict):+ url = next((again.json[k] for k in ("url", "share_url", "href", "link", "location")+ if isinstance(again.json.get(k), str) and again.json[k]), "")+ if url and _view_path(ctx, url) not in live:+ live.append(_view_path(ctx, url))++ # §5 requires revocation and names no path, so the endpoint has to be searched for.+ attempts = [("DELETE", f"/v1/sessions/{sid}/share"),+ ("POST", f"/v1/sessions/{sid}/share/revoke"),+ ("DELETE", f"/v1/shares/{sh['id']}" if sh["id"] else "")]+ done = ""+ for method, path in attempts:+ if not path:+ continue+ r = ctx.client.request(method, path)+ if 200 <= r.status < 300:+ done = f"{method} {path}"+ break+ if not done:+ raise Skip(+ "Sessions §5 requires that a share be revocable and names no endpoint for it, so this "+ "check cannot locate one. The specification should name a path: a MUST with no "+ "endpoint is a MUST that every implementation satisfies differently, and no portable "+ "check can confirm it.")++ ctx.state["share"] = "the share minted for this run was revoked by R-06"+ ctx.state["share_readable"] = False+ alive = [(p, ctx.client.get(p, auth=False).status) for p in live]+ bad = [f"{p} → HTTP {s}" for p, s in alive if s not in (404, 410)]+ assert not bad, (+ f"a published link still resolves after {done} reported success: " + "; ".join(bad) ++ ". A revocation that answers 200 and leaves a link live is worse than none, because the "+ "operator has been told the session is no longer published.")+ return (f"revoked via {done}; {len(live)} link(s) minted, all now "+ f"{'/'.join(str(s) for _, s in alive)}")+++@check("R-07", "Deleting a session takes its shared view with it", "full",+ f"{SPEC}/sessions.md#6-deleting")+def r07(ctx):+ # A session this check may destroy: deleting the one the rest of the suite shares would make+ # every later check fail for the wrong reason. That costs one extra agent run on a full pass.+ h = _harness(ctx)+ body = {"input": PROMPT, "metadata": {"harness_id": h["id"]}, "stream": False}+ if ctx.model:+ body["model"] = ctx.model+ started = ctx.client.post("/v1/responses", body=body)+ sid = ((started.json or {}).get("metadata") or {}).get("session_id")+ if started.status != 200 or not sid:+ raise Skip(f"could not start a disposable session (HTTP {started.status})")++ minted = ctx.client.post(f"/v1/sessions/{sid}/share")+ if minted.status != 200 or not isinstance(minted.json, dict):+ raise Skip(f"could not share the disposable session (HTTP {minted.status})")+ url = next((minted.json[k] for k in ("url", "share_url", "href", "link", "location")+ if isinstance(minted.json.get(k), str) and minted.json[k]), "")+ if not url:+ raise Skip("the share carries no URL, so the view cannot be located (see R-01)")+ path = _view_path(ctx, url)+ if ctx.client.get(path, auth=False).status != 200:+ raise Skip("the disposable share's view did not resolve, so its disappearance proves nothing")++ gone = ctx.client.delete(f"/v1/traces/{sid}")+ if gone.status in (404, 405, 501):+ raise Skip(f"DELETE /v1/traces/{{id}} returned HTTP {gone.status}, so a session cannot be "+ "deleted here and this check has nothing to observe")+ assert 200 <= gone.status < 300, f"deleting the session returned HTTP {gone.status}"+ after = ctx.client.get(path, auth=False)+ assert after.status in (404, 410), (+ f"the shared link still returns HTTP {after.status} for a session that was deleted. §6 "+ "requires the session be unreadable after deletion, and a published link is the one way "+ "in that its owner is least likely to remember.")+ return f"session deleted, then HTTP {after.status}"