Skip to content

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.

A credential scoped to one harness is held to that harness everywhere, before anything is written (#416)

github-actions[bot]5f1e8a840991
diff --git a/gateway/app.py b/gateway/app.py
index f91befdc..9569ca38 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1004,6 +1004,29 @@ def _calibration_route_allowed(method: str, path: str, inner: str) -> bool:
return any(m == method.upper() and re.fullmatch(pat, path) for m, pat in allowed)
+def _calibration_inner(principal: dict) -> str:
+ """The one harness a calibration credential drives; "" for every other caller."""
+ c = principal.get("calibration")
+ return str(c.get("inner") or "") if c else ""
+
+
+async def _calibration_holds_session(inner: str, sid: str) -> bool:
+ """Whether a session already belongs to the harness a calibration credential drives. The route
+ list above says which doors the credential may knock on; this is what it may touch behind them:
+ a session of that harness, and a response of such a session, and nothing else in the org. A
+ session that names no harness is not its harness's (an ordinary caller's turn may claim a blank
+ one; this credential may not, or a known id would be a way into any unnamed conversation)."""
+ v = await _vertex_get(sid) if sid else None
+ return bool(v) and bool(inner) and str(v.get("harness_id") or "") == inner
+
+
+async def _calibration_holds_response(inner: str, rec: dict | None) -> bool:
+ """...and a response is its harness's when the session that produced it is."""
+ rec = rec or {}
+ sid = str(rec.get("_session_id") or (rec.get("metadata") or {}).get("session_id") or "")
+ return await _calibration_holds_session(inner, sid)
+
+
def _calibration_env(hv: dict | None, org: str, sid: str, timeout_s: int | None) -> dict | None:
"""What a turn of a harness that drives another one is handed, or None: the platform's own
API and a credential scoped to the harness it names, good for the turn's wall-clock cap plus
@@ -8422,6 +8445,36 @@ async def create_response(body: CreateResponseBody, request: Request):
raise HTTPException(400, "no org resolved for this principal")
meta = body.metadata or {}
probe = {"systemone": meta["systemone"]} if isinstance(meta.get("systemone"), dict) else None
+ # harness id: request metadata, else the X-Harness-Id header (set by a front proxy that maps
+ # {harness_id}/v1/* -> /v1/*, or by the native public-shape route above).
+ harness_id = str(meta.get("harness_id") or request.headers.get("x-harness-id") or "")
+ if not harness_id and body.previous_response_id:
+ # A continuation belongs to its session's harness. A client that does not repeat harness_id
+ # on a follow-up (the protocol asks only for previous_response_id) used to be routed by the
+ # inherited MODEL NAME, and for a base whose models no chat backend serves that fell to the
+ # default backend: a systemone follow-up asked claude for jev-1.13 (measured 2026-09-19).
+ # The session vertex records the harness the conversation started on; that is the harness.
+ _pr = await _resp_get(body.previous_response_id)
+ _psid = str(((_pr or {}).get("metadata") or {}).get("session_id") or "")
+ _pv = await _vertex_get(_psid) if _psid else None
+ harness_id = str((_pv or {}).get("harness_id") or "")
+ harness_name = str(meta.get("harness_name") or "")
+ # A calibration credential is held to its one harness HERE, before the idempotency replay below
+ # hands back a stored response and before any session is touched: a refusal that comes after a
+ # read or a write is not a refusal. It starts runs on that harness, and continues only a
+ # conversation that is already that harness's. Naming its own harness and another harness's
+ # response or session used to pass (the check looked at the harness id alone), and the turn then
+ # ran in the other conversation's workspace.
+ _cal = principal.get("calibration")
+ if _cal and harness_id != str(_cal.get("inner") or ""):
+ raise uhp_error(403, "forbidden", "This credential starts runs on the one harness it drives.",
+ "metadata.harness_id", {"harness_id": _cal.get("inner")})
+ if _cal and body.previous_response_id and not await _calibration_holds_response(
+ _calibration_inner(principal), await _resp_get(body.previous_response_id)):
+ raise uhp_error(404, "response_not_found", "No response with that id.", "previous_response_id")
+ if _cal and str(meta.get("session_id") or "") and not await _calibration_holds_session(
+ _calibration_inner(principal), str(meta.get("session_id") or "")):
+ raise uhp_error(404, "session_not_found", "No session with that id.", "metadata.session_id")
# Request idempotency: the durable control store is the SINGLE authority (create_item = atomic
# reservation). No in-process/blob/Redis fallback — a keyed request without the store fails
# closed (503), never runs a divergent degraded path. idem_sha_v/idem_rhash are computed here
@@ -8442,24 +8495,6 @@ async def create_response(body: CreateResponseBody, request: Request):
if str(existing.get("req_hash") or "") not in ("", idem_rhash):
raise HTTPException(409, "Idempotency-Key reused with a different request payload")
return await _idem_replay(str(existing.get("resp_id") or ""), bool(body.stream))
- # harness id: request metadata, else the X-Harness-Id header (set by a front proxy that maps
- # {harness_id}/v1/* -> /v1/*, or by the native public-shape route above).
- harness_id = str(meta.get("harness_id") or request.headers.get("x-harness-id") or "")
- if not harness_id and body.previous_response_id:
- # A continuation belongs to its session's harness. A client that does not repeat harness_id
- # on a follow-up (the protocol asks only for previous_response_id) used to be routed by the
- # inherited MODEL NAME, and for a base whose models no chat backend serves that fell to the
- # default backend: a systemone follow-up asked claude for jev-1.13 (measured 2026-09-19).
- # The session vertex records the harness the conversation started on; that is the harness.
- _pr = await _resp_get(body.previous_response_id)
- _psid = str(((_pr or {}).get("metadata") or {}).get("session_id") or "")
- _pv = await _vertex_get(_psid) if _psid else None
- harness_id = str((_pv or {}).get("harness_id") or "")
- harness_name = str(meta.get("harness_name") or "")
- _cal = principal.get("calibration")
- if _cal and harness_id != str(_cal.get("inner") or ""):
- raise uhp_error(403, "forbidden", "This credential starts runs on the one harness it drives.",
- "metadata.harness_id", {"harness_id": _cal.get("inner")})
hv = await _harness_vertex(harness_id) if harness_id else None
# A deleted harness cannot run new turns (same 404 as the read endpoints), and a harness runs
# only for the organization and workspace that own it: see _turn_harness_owned.
@@ -9019,6 +9054,9 @@ async def get_response(response_id: str, request: Request):
# so a cross-org id probe can't confirm existence. Legacy records with no _org stay readable.
if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", ""):
raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")
+ _inner = _calibration_inner(principal)
+ if _inner and not await _calibration_holds_response(_inner, rec):
+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id") # not its harness's
# Durable settler for async/background polling: never leave a poller stuck at 'running' if the
# owning turn actually finished/died (reconciled from the session vertex + trace).
rec = await _reconcile_response(response_id, rec)
@@ -9438,6 +9476,9 @@ async def cancel_response(response_id: str, request: Request):
# so a cross-org probe can't even confirm the id exists.
if str(rec.get("_org") or "") != org:
raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")
+ _inner = _calibration_inner(principal)
+ if _inner and not await _calibration_holds_response(_inner, rec):
+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id") # not its harness's
sid = str(rec.get("_session_id") or "")
# PRIMARY (safe, cross-replica): a durable per-RESPONSE monotonic terminal latch. The turn's
# own loop checks resp_is_cancelled(its resp_id) at every stage and self-terminates within
@@ -17704,9 +17745,6 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
if db_in and not decl:
raise uhp_error(400, "connection_not_used",
f"The '{kit_id}' kit does not read a database.", "database")
- # Checked before anything is provisioned: a typo in a connection string should cost the person
- # a corrected form, not a half-configured Harness to find and fix.
- checked = await _db_validate(db_in.engine, db_in.connection_string) if db_in else None
# Per workspace (see list_kits): launching in a second workspace makes that workspace its own
# Harness rather than handing back the first workspace's, which its members could not see.
@@ -17716,6 +17754,19 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
and _workspace_keep(str(r.get("workspace") or ""), ws, wsd)),
None)
want_h = (body_in.harness if body_in else "").strip()
+ # A calibration credential relaunches the kit on the harness it drives and does nothing else
+ # here: the kit must already run on that harness, and it may name no other. Decided NOW, from
+ # what was read, before the connection check below opens a socket and before anything is
+ # written. This check used to sit after the two writes that move a kit to the harness named in
+ # the request, so the credential (which carries no workspace and so sees every harness of the
+ # organization) could name any of them: the answer was 403 and the kit had already been taken
+ # off its harness and put on that one (reported privately, twice).
+ _inner = _calibration_inner(p)
+ if _inner and (str((existing or {}).get("id") or "") != _inner or (want_h and want_h != _inner)):
+ raise uhp_error(403, "forbidden", "This credential relaunches the kit on the harness it drives only.", "harness")
+ # Checked before anything is provisioned: a typo in a connection string should cost the person
+ # a corrected form, not a half-configured Harness to find and fix.
+ checked = await _db_validate(db_in.engine, db_in.connection_string) if db_in else None
if want_h and want_h != str((existing or {}).get("id") or ""):
# Run the kit on a Harness the person already has. One kit, one Harness: the previous kit
# Harness keeps its sessions and its package but is no longer the one the app talks to,
@@ -17733,8 +17784,6 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
await _vg_upsert("Harness", want_h, {"kit": kit_id, "updated_at": now0})
existing = await _vertex_get(want_h) or {**target, "kit": kit_id}
print(f"[kits] {kit_id} now runs on {want_h}", flush=True)
- if p.get("calibration") and str((existing or {}).get("id") or "") != str(p["calibration"].get("inner") or ""):
- raise uhp_error(403, "forbidden", "This credential relaunches the kit on the harness it drives only.", "harness")
if decl and not db_in and not existing:
# Declaring launch.database is what makes it required: every panel this kit builds would
# have nothing to read, so a launch without a connection is not a partial success.
diff --git a/gateway/tests/test_calibration_scope.py b/gateway/tests/test_calibration_scope.py
new file mode 100644
index 00000000..c7bdf89b
--- /dev/null
+++ b/gateway/tests/test_calibration_scope.py
@@ -0,0 +1,247 @@
+"""A calibration credential touches only what belongs to the harness it drives, and is refused
+before anything is read back or written.
+
+The route list (test_dual_loop.py) says which doors the credential may knock on. These are the
+rooms behind them. Reported privately, twice: the kit launch moved a kit between two harnesses and
+THEN answered 403; reading and cancelling a response checked the organization alone; and starting a
+run checked the harness named in the request but not whose conversation it continued.
+"""
+import asyncio
+import inspect
+import pathlib
+import sys
+
+import pytest
+from fastapi import HTTPException
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+ORG = "org-a"
+INNER = "chrn_" + "a" * 32
+OTHER = "chrn_" + "b" * 32
+CAL = {"org": ORG, "member": "calibrator:hsess_outer", "calibration": {"inner": INNER, "org": ORG, "sid": "hsess_outer"}}
+MEMBER = {"org": ORG, "member": "[email protected]", "workspace": "", "workspace_default": False}
+
+SESSIONS = {
+ "hsess_inner": {"tenant": ORG, "harness_id": INNER, "status": "idle"},
+ "hsess_other": {"tenant": ORG, "harness_id": OTHER, "status": "idle"},
+ "hsess_blank": {"tenant": ORG, "harness_id": "", "status": "idle"},
+}
+RESPONSES = {
+ "resp_inner": {"id": "resp_inner", "_org": ORG, "_session_id": "hsess_inner", "status": "completed"},
+ "resp_other": {"id": "resp_other", "_org": ORG, "_session_id": "hsess_other", "status": "completed"},
+ "resp_blank": {"id": "resp_blank", "_org": ORG, "_session_id": "hsess_blank", "status": "completed"},
+}
+
+
+class _Req:
+ def __init__(self, headers=None, path="/v1/responses", method="POST"):
+ self.headers = headers or {}
+ self.method = method
+ self.url = type("U", (), {"path": path})()
+
+
+def _refused(coro) -> HTTPException:
+ with pytest.raises(HTTPException) as e:
+ asyncio.run(coro)
+ return e.value
+
+
+def world(monkeypatch):
+ """The graph a handler reads, and a record of everything it writes or reaches out to."""
+ did = {"writes": [], "db_checks": [], "idem": [], "sessions_resolved": [], "cancelled": []}
+ harnesses = {
+ INNER: {"id": INNER, "org": ORG, "workspace": "", "kit": "", "deleted": "0"},
+ OTHER: {"id": OTHER, "org": ORG, "workspace": "space.b", "kit": "", "deleted": "0"},
+ }
+
+ async def vertex_get(vid):
+ return dict(SESSIONS[vid]) if vid in SESSIONS else (dict(harnesses[vid]) if vid in harnesses else None)
+
+ async def resp_get(rid):
+ return dict(RESPONSES[rid]) if rid in RESPONSES else None
+
+ async def list_by_org(label, org):
+ return [dict(h) for h in harnesses.values()]
+
+ async def upsert(label, vid, props, **kw):
+ did["writes"].append((label, vid, dict(props)))
+ harnesses.setdefault(vid, {"id": vid, "org": ORG}).update(props)
+
+ async def db_validate(engine, conn):
+ did["db_checks"].append(conn)
+ return {"ok": True}
+
+ monkeypatch.setattr(gw, "_vertex_get", vertex_get)
+ monkeypatch.setattr(gw, "_resp_get", resp_get)
+ monkeypatch.setattr(gw, "_vg_list_by_org", list_by_org)
+ monkeypatch.setattr(gw, "_vg_upsert", upsert)
+ monkeypatch.setattr(gw, "_db_validate", db_validate)
+ monkeypatch.setattr(gw, "_kits", lambda: {"mario": {"id": "mario", "title": "Mario", "harness": {}, "app": {"route": "/kits/mario"}}})
+ monkeypatch.setattr(gw, "_kit_launch_database", lambda kit: {"name": "database", "id": "mcp.database"})
+ monkeypatch.setattr(gw, "_kit_launch_media", lambda kit: None)
+ did["harnesses"] = harnesses
+ return did
+
+
+def _as(monkeypatch, principal):
+ async def who(request):
+ return principal
+ monkeypatch.setattr(gw, "_principal", who)
+
+
+def _launch(body=None):
+ return gw.launch_kit("mario", _Req(path="/v1/kits/mario/launch"), gw.KitLaunchBody(**body) if body else None)
+
+
+# ── the kit launch: refused before anything happens ────────────────────────────────────────────
+
[email protected]("kit_on, names", [
+ (INNER, OTHER), # the reported case: move the kit off its own harness onto another one
+ (OTHER, INNER), # take a kit away from a harness it does not drive
+ (OTHER, ""), # relaunch a kit that runs somewhere else
+ (OTHER, OTHER),
+ ("", ""), # nothing runs the kit: it does not get to create a harness either
+ ("", OTHER),
+], ids=["onto-another", "take-from-another", "another-s-kit", "another-s-kit-named", "no-harness", "no-harness-named"])
+def test_a_refused_launch_changes_nothing_and_reaches_nowhere(world, monkeypatch, kit_on, names):
+ if kit_on:
+ world["harnesses"][kit_on]["kit"] = "mario"
+ before = {k: dict(v) for k, v in world["harnesses"].items()}
+ _as(monkeypatch, CAL)
+ body = {"database": {"engine": "postgres", "connection_string": "postgres://10.0.0.5:5432/x"}}
+ if names:
+ body["harness"] = names
+ e = _refused(_launch(body))
+ assert e.status_code == 403
+ assert world["writes"] == [] and world["harnesses"] == before # the 403 means nothing happened
+ assert world["db_checks"] == [] # and no socket was opened for it
+
+
+def test_the_credential_relaunches_the_kit_where_it_already_runs(world, monkeypatch):
+ world["harnesses"][INNER]["kit"] = "mario"
+ _as(monkeypatch, CAL)
+ monkeypatch.setattr(gw, "_kit_launch_database", lambda kit: None)
+ monkeypatch.setattr(gw, "_kit_plugin", lambda kit: None)
+
+ async def no_plugs(org, hid):
+ return False
+ monkeypatch.setattr(gw, "_plugs_ensure_required", no_plugs)
+ monkeypatch.setattr(gw, "_harness_out", lambda v: {"id": v.get("id")})
+ for body in (None, {"harness": INNER}):
+ out = asyncio.run(_launch(body))
+ assert out["harnessId"] == INNER and out["created"] is False
+ assert world["writes"] == [] # a relaunch of an unchanged kit rewrites nothing
+
+
+def test_a_member_still_moves_a_kit_between_two_of_their_harnesses(world, monkeypatch):
+ world["harnesses"][INNER]["kit"] = "mario"
+ _as(monkeypatch, MEMBER)
+ monkeypatch.setattr(gw, "_kit_launch_database", lambda kit: None)
+ monkeypatch.setattr(gw, "_kit_plugin", lambda kit: None)
+
+ async def no_plugs(org, hid):
+ return False
+ monkeypatch.setattr(gw, "_plugs_ensure_required", no_plugs)
+ monkeypatch.setattr(gw, "_harness_out", lambda v: {"id": v.get("id")})
+ out = asyncio.run(_launch({"harness": OTHER}))
+ assert out["harnessId"] == OTHER
+ assert [(v, p.get("kit")) for _, v, p in world["writes"]] == [(INNER, ""), (OTHER, "mario")]
+
+
+def test_in_the_handler_the_credential_is_judged_before_the_first_side_effect():
+ src = inspect.getsource(gw.launch_kit)
+ gate = src.index("_inner = _calibration_inner(p)")
+ assert gate < src.index("_db_validate(") and gate < src.index("_vg_upsert(")
+ assert src.count('p.get("calibration")') == 0 # one gate, not a second one further down
+
+
+# ── a response: read and cancelled only when it is its harness's ───────────────────────────────
+
[email protected]("rid", ["resp_other", "resp_blank"])
+def test_another_harness_s_response_is_not_found_to_read_or_to_cancel(world, monkeypatch, rid):
+ _as(monkeypatch, CAL)
+
+ def must_not(*a, **k):
+ raise AssertionError("the response was touched after it should have been refused")
+ monkeypatch.setattr(gw, "_reconcile_response", must_not)
+ monkeypatch.setattr(gw.control_store, "enabled", must_not)
+ e = _refused(gw.get_response(rid, _Req(path=f"/v1/responses/{rid}", method="GET")))
+ assert e.status_code == 404 and "No response with that id." in str(e.detail)
+ e = _refused(gw.cancel_response(rid, _Req(path=f"/v1/responses/{rid}/cancel")))
+ assert e.status_code == 404
+
+
+def test_its_own_harness_s_response_is_read(world, monkeypatch):
+ _as(monkeypatch, CAL)
+
+ async def settle(rid, rec):
+ return rec
+ monkeypatch.setattr(gw, "_reconcile_response", settle)
+ assert asyncio.run(gw.get_response("resp_inner", _Req(path="/v1/responses/resp_inner", method="GET")))["id"] == "resp_inner"
+
+
+def test_a_member_reads_any_response_of_the_organization_as_before(world, monkeypatch):
+ _as(monkeypatch, MEMBER)
+
+ async def settle(rid, rec):
+ return rec
+ monkeypatch.setattr(gw, "_reconcile_response", settle)
+ assert asyncio.run(gw.get_response("resp_other", _Req(path="/v1/responses/resp_other", method="GET")))["id"] == "resp_other"
+
+
+# ── a run: on its harness, and in a conversation that is already its harness's ─────────────────
+
+def _start(world, monkeypatch, **body):
+ """create_response as the credential, with every later stage rigged to shout if it is reached."""
+ _as(monkeypatch, CAL)
+
+ async def idem_get(org, sha):
+ world["idem"].append(sha)
+ return {"resp_id": "resp_other", "req_hash": ""}
+
+ async def resolve(*a, **k):
+ world["sessions_resolved"].append((a, k))
+ raise AssertionError("a session was resolved for a run that should have been refused")
+ monkeypatch.setattr(gw.control_store, "enabled", lambda: True)
+ monkeypatch.setattr(gw.control_store, "idem_get", idem_get)
+ monkeypatch.setattr(gw, "_resp_resolve_session", resolve)
+ return gw.create_response(gw.CreateResponseBody(input="hello", **body), _Req(headers={"Idempotency-Key": "k-1"}))
+
+
[email protected]("body, status", [
+ ({"metadata": {"harness_id": OTHER}}, 403), # another harness
+ ({"metadata": {"harness_id": INNER}, "previous_response_id": "resp_other"}, 404), # its harness, another's conversation
+ ({"metadata": {"harness_id": INNER}, "previous_response_id": "resp_blank"}, 404), # a conversation that names no harness
+ ({"metadata": {"harness_id": INNER}, "previous_response_id": "resp_missing"}, 404),
+ ({"metadata": {"harness_id": INNER, "session_id": "hsess_other"}}, 404),
+ ({"metadata": {"harness_id": INNER, "session_id": "hsess_blank"}}, 404),
+], ids=["another-harness", "another-s-response", "unnamed-response", "missing-response", "another-s-session", "unnamed-session"])
+def test_a_run_outside_its_harness_is_refused_before_a_stored_answer_is_replayed(world, monkeypatch, body, status):
+ e = _refused(_start(world, monkeypatch, **body))
+ assert e.status_code == status
+ assert world["idem"] == [] # refused before the idempotency replay could hand a response back
+ assert world["sessions_resolved"] == [] and world["writes"] == []
+
+
+def test_a_run_on_its_harness_in_its_own_conversation_gets_past_the_gate(world, monkeypatch):
+ # past the gate the next thing asked is the idempotency store: reaching it is the proof
+ coro = _start(world, monkeypatch, metadata={"harness_id": INNER, "session_id": "hsess_inner"},
+ previous_response_id="resp_inner")
+
+ async def replay(resp_id, stream):
+ return {"replayed": resp_id}
+ monkeypatch.setattr(gw, "_idem_replay", replay)
+ assert asyncio.run(coro) == {"replayed": "resp_other"} and len(world["idem"]) == 1
+
+
+def test_what_belongs_to_the_harness_it_drives(world):
+ holds = lambda sid: asyncio.run(gw._calibration_holds_session(INNER, sid)) # noqa: E731
+ assert holds("hsess_inner")
+ assert not holds("hsess_other") and not holds("hsess_blank") and not holds("hsess_nope") and not holds("")
+ assert not asyncio.run(gw._calibration_holds_session("", "hsess_blank")) # no harness named: nothing is held
+ assert asyncio.run(gw._calibration_holds_response(INNER, RESPONSES["resp_inner"]))
+ assert not asyncio.run(gw._calibration_holds_response(INNER, None))
+ assert gw._calibration_inner(CAL) == INNER and gw._calibration_inner(MEMBER) == ""