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
A workspace's API key reaches that workspace and nothing else of the organization (#417)
github-actions[bot]249c6cc9ab51
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex a40b2546..c12399f3 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -988,9 +988,11 @@ variables. It is a setup check, not a technical prerequisite for the API.3. Copy the secret shown once. Store it in your product backend's secret store or environment. The examples call this variable `HARNESSROUTER_API_KEY`.The key is scoped to the selected workspace and can be rotated or revoked on the same page.-A harness runs with a key of its own workspace: a task that names a harness of another workspace,-or of another organization, is answered `404 harness_not_found`, the same as an id that does not-exist. A built-in base (`codex`, `claude-code`, ...) runs with any key.+A key made in a workspace other than the Default Workspace reaches that workspace and nothing else:+a harness, a task, a file or a response of another workspace is answered `404`, the same as an id+that does not exist, and such a key makes new keys for its own workspace only. A key made in the+Default Workspace, and an organization key (the **Reach** choice when you create a key), reach every+workspace of the organization. A built-in base (`codex`, `claude-code`, ...) runs with any key.It is created in this self-hosted instance and authenticates requests to that CE deployment. It isneither a Cloud key, your Console password, nor the model-provider key configuredin **Integrations**. Never put it in browser-side code or commit it to Git.diff --git a/gateway/app.py b/gateway/app.pyindex 9569ca38..e1f68e29 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -4468,6 +4468,8 @@ async def list_traces(request: Request, org: str, limit: int = 20, cursor: str =p = await _principal(request)if (p.get("org") or "") != org:raise HTTPException(403, "trace access is limited to your organization")+ if _key_scope(p): # a key held to a workspace lists that workspace, whatever it asks for+ workspace, workspace_default = _key_scope(p), 0return await _session_cards(org, limit, cursor, member, harness,workspace=workspace, ws_default=bool(workspace_default))@@ -4631,12 +4633,72 @@ async def list_sessions(request: Request, limit: int = 20, cursor: str = "",ws_default=bool(p.get("workspace_default")))+def _key_scope(p: dict) -> str:+ """The one workspace an API key is held to, or "" when the caller is not narrowed. Not narrowed:+ a person through the console (the workspace it names is a view, not a wall), a key for the+ whole organization, and a Default Workspace key, which is what an organization's keys were+ before workspaces existed and keeps that reach (Richard, 2026-10-06; the same function and the+ same answer on the hosted service)."""+ if p.get("via") != "api_key":+ return ""+ ws = str(p.get("workspace") or "")+ if not ws or p.get("workspace_default") or ws == f"{p.get('org') or ''}__hr_default":+ return ""+ return ws+++def _scope_keeps(p: dict, item_ws) -> bool:+ """THE workspace rule, in one place: whether this caller may touch something stamped with+ `item_ws`. A key held to a workspace (_key_scope) reaches what is stamped with that workspace+ and nothing else of the organization; what was made before workspaces existed carries no stamp+ and is the Default Workspace's, so it is not such a key's either. Every other caller reaches+ everything of its organization.++ The lists always narrowed a workspace's key. The routes that take an id did not: they checked+ the organization and stopped, so a workspace's key that knew an id read, changed and deleted+ another workspace's harnesses, sessions and responses, revoked its keys, and could mint itself a+ key with no workspace at all (reported privately three times). Every route that takes an id now+ asks here, through _harness_in_reach, _owned_session or _response_in_reach, and a test reads+ the routes to keep it so."""+ held = _key_scope(p)+ return not held or str(item_ws or "") == held+++async def _harness_in_reach(p: dict, hid: str, *, deleted_ok: bool = False) -> dict:+ """The harness record behind an id, for this caller, or the same 404 an unknown id gets: its+ organization's, not deleted, and inside the caller's workspace."""+ v = await _vertex_get(hid)+ if (not v or not p.get("org") or str(v.get("org") or "") != str(p.get("org"))+ or (not deleted_ok and str(v.get("deleted")) in ("1", "true", "True"))+ or not _scope_keeps(p, v.get("workspace"))):+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ return v+++async def _response_in_reach(p: dict, rec: dict | None) -> bool:+ """Whether a response of the caller's organization is the caller's to read, cancel or delete.+ A response belongs to the session that produced it, so the answer is the session's: its+ workspace for a caller narrowed to one, its harness for a calibration credential. A caller with+ neither limit is not made to pay for the read."""+ inner = _calibration_inner(p)+ if not inner and not _key_scope(p):+ return True+ rec = rec or {}+ sid = str(rec.get("_session_id") or (rec.get("metadata") or {}).get("session_id") or "")+ v = await _vertex_get(sid) if sid else None+ if not v or (inner and str(v.get("harness_id") or "") != inner):+ return False+ return _scope_keeps(p, v.get("workspace"))++async def _owned_session(request: Request, sid: str) -> tuple[str, dict]:p = await _principal(request)org = p.get("org", "")v = await _vertex_get(sid)if not v or str(v.get("tenant") or "") != org or str(v.get("status")) == "deleted":raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")+ if not _scope_keeps(p, v.get("workspace")):+ raise uhp_error(404, "session_not_found", "No session with that id.", "session_id") # another workspace'sc = p.get("calibration")if c and str(v.get("harness_id") or "") != str(c.get("inner") or ""):raise uhp_error(404, "session_not_found", "No session with that id.", "session_id") # not its harness's@@ -4920,7 +4982,7 @@ async def delete_trace(sid: str, request: Request) -> dict:p = await _principal(request)org = str(p.get("org") or "")v = await _vertex_get(sid)- if not v or str(v.get("tenant") or "") != org:+ if not v or str(v.get("tenant") or "") != org or not _scope_keeps(p, v.get("workspace")):raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")# A tombstoned session may be deleted again. A card of it can outlive the first delete (a# follow-up that reached the tombstone rewrote the card as "?", 2026-09-07), and this button@@ -7558,7 +7620,8 @@ async def _collect_produced(sid: str, exclude: set[str] | None = None) -> list[d# ── session resolution (previous_response_id → reuse prior session for continuity) ──────async def _resp_resolve_session(org: str, member: str, prev: str | None, backend_hint: str,harness_id: str = "", harness_name: str = "",- session_hint: str = "", workspace: str = "") -> tuple[str, str | None]:+ session_hint: str = "", workspace: str = "",+ caller: dict | None = None) -> tuple[str, str | None]:# Continue an existing conversation by (1) the response-id chain, or (2) an explicit session id.# (2) is the robust path: the client always knows which conversation it's in, so a follow-up never# forks a new empty session just because previous_response_id was momentarily unavailable.@@ -7606,6 +7669,9 @@ async def _resp_resolve_session(org: str, member: str, prev: str | None, backendexcept Exception as e: # noqa: BLE001raise uhp_error(503, "server_error", "The session could not be read right now. Try again.") from eif v and str(v.get("tenant") or "") == org and str(v.get("status") or "") != "deleted":+ if caller is not None and not _scope_keeps(caller, v.get("workspace")):+ # another workspace's conversation: the same answer as an id that does not exist+ raise uhp_error(404, "session_not_found", "No session with that id.")return await _continue(sid, v)if v:# a leaked/stored id of another org's session must not let a caller continue it; nor a@@ -8135,13 +8201,13 @@ async def _apikey_resolve(tok: str) -> dict | None:_touch_apikey(sha)return {"org": doc.get("org", ""), "member": doc.get("member", ""),"workspace": doc.get("workspace", "") or "",- "workspace_default": bool(doc.get("workspace_default"))}+ "workspace_default": bool(doc.get("workspace_default")), "via": "api_key"}v = await _vertex_get(sha)if v and v.get("kind") == "harness_api_key" and str(v.get("revoked")) not in ("1", "true", "True"):_touch_apikey(sha)p = {"org": v.get("org", ""), "member": v.get("member", ""),"workspace": v.get("workspace", "") or "",- "workspace_default": str(v.get("workspace_default") or "") in ("1", "true", "True")}+ "workspace_default": str(v.get("workspace_default") or "") in ("1", "true", "True"), "via": "api_key"}if control_store.enabled():try:# create_only: never overwrite an existing doc — a revoke tombstone may have landed@@ -8634,7 +8700,8 @@ async def create_response(body: CreateResponseBody, request: Request):sid, resume = await _resp_resolve_session(org, member, body.previous_response_id, backend,harness_id=harness_id, harness_name=harness_name,session_hint=str(meta.get("session_id") or ""),- workspace=str(principal.get("workspace") or ""))+ workspace=str(principal.get("workspace") or ""),+ caller=principal)# Bill the harness OWNER's org (resolved above), not the caller's — stamp it on the in-process# session trace so trace-finalize meters usage against the same org the gate admitted. The turn# executes + finalizes on THIS replica, so this in-process stamp is authoritative for metering;@@ -8870,6 +8937,10 @@ async def harness_events(harness_id: str, request: Request):org, member = principal.get("org", ""), principal.get("member", "")if not org:raise HTTPException(400, "no org resolved for this principal")+ if harness_id not in _BASE_CATALOG:+ # a harness with a record is listened to by a caller it is in reach of; a built-in base+ # has no record and no owner, and its stream stays filtered per member as before+ await _harness_in_reach(principal, harness_id)topic = _bus_topic(org, harness_id)q: asyncio.Queue = asyncio.Queue(maxsize=_BUS_Q_MAX)_bus.setdefault(topic, set()).add(q)@@ -9054,9 +9125,8 @@ 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+ if not await _response_in_reach(principal, rec):+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id") # another workspace's, or 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)@@ -9179,7 +9249,7 @@ async def delete_response(response_id: str, request: Request):raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")# V1C02-004: object-level ownership — one org must not delete another's response. 404 (not# 403) so a cross-org id probe can't confirm existence. Legacy records with no _org stay owned.- if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", ""):+ if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", "") or not await _response_in_reach(principal, rec):raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")rec["_deleted"] = Truetry:@@ -9291,7 +9361,7 @@ async def artifact_by_path(sid: str, path: str, request: Request) -> Response:"""Authenticated artifact-by-path: org members open workspace files directly (inline)."""p = await _principal(request)v = await _vertex_get(sid)- if not v or str(v.get("tenant") or "") != p.get("org"):+ if not v or str(v.get("tenant") or "") != p.get("org") or not _scope_keeps(p, v.get("workspace")):raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")return await _serve_workspace_path(sid, path)@@ -9325,7 +9395,7 @@ async def set_session_share(sid: str, request: Request, body: ShareBody | None =suite among them)."""p = await _principal(request)v = await _vertex_get(sid)- if not v or str(v.get("tenant") or "") != p.get("org"):+ if not v or str(v.get("tenant") or "") != p.get("org") or not _scope_keeps(p, v.get("workspace")):raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")if body is None or body.enabled:token = str(v.get("share_token") or "") or ("shr" + uuid.uuid4().hex)@@ -9345,7 +9415,7 @@ async def revoke_session_share(sid: str, request: Request) -> dict:was answering 405 while the real revocation hid inside POST {"enabled": false}. Both work."""p = await _principal(request)v = await _vertex_get(sid)- if not v or str(v.get("tenant") or "") != p.get("org"):+ if not v or str(v.get("tenant") or "") != p.get("org") or not _scope_keeps(p, v.get("workspace")):raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")await _vertex_upsert(sid, {"shared": "0"})_SHARE_TOKEN_CACHE.clear()@@ -9356,7 +9426,7 @@ async def revoke_session_share(sid: str, request: Request) -> dict:async def get_session_share(sid: str, request: Request) -> dict:p = await _principal(request)v = await _vertex_get(sid)- if not v or str(v.get("tenant") or "") != p.get("org"):+ if not v or str(v.get("tenant") or "") != p.get("org") or not _scope_keeps(p, v.get("workspace")):raise uhp_error(404, "session_not_found", "No session with that id.", "session_id")return _share_out(str(v.get("shared") or "") == "1", str(v.get("share_token") or ""))@@ -9452,7 +9522,7 @@ async def list_input_items(response_id: str, request: Request, limit: int = 20,rec = await _resp_get(response_id)if not rec:raise uhp_error(404, "response_not_found", "No response with that id.", "response_id")- if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", ""):+ if str(rec.get("_org") or principal.get("org", "")) != principal.get("org", "") or not await _response_in_reach(principal, rec):raise uhp_error(404, "response_not_found", "No response with that id.", "response_id") # LIVE-B: object-level ownershipdata = list(rec.get("_input") or [])if order == "desc":@@ -9476,9 +9546,8 @@ 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+ if not await _response_in_reach(principal, rec):+ raise uhp_error(404, "response_not_found", "No response with that id.", "response_id") # another workspace's, or not its harness'ssid = 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@@ -10283,7 +10352,17 @@ class KeyBody(BaseModel):@app.post("/v1/orgs/{org}/keys")async def mint_key(org: str, body: KeyBody, request: Request) -> dict:- await _owned_org(request, org)+ p = await _owned_org(request, org)+ # A key held to a workspace mints keys for that workspace and no wider, under its own name. The+ # body used to decide both: a workspace's key asked for a key with no workspace and was handed+ # one for the whole organization, under any member name it liked (reported privately three+ # times). A person in the console, and a key that already reaches the organization, choose.+ held = _key_scope(p)+ if held:+ if (body.workspace or "").strip() not in ("", held):+ raise uhp_error(403, "forbidden", "A key held to one workspace makes keys for that workspace only.", "workspace")+ body.workspace, body.workspace_default = held, False+ body.member_id = str(p.get("member") or "")tok = "sk-hr-" + uuid.uuid4().hex + uuid.uuid4().hexh = _hash_key(tok)# Graph FIRST and it must succeed (raise_on_fail): the graph is the source of truth + the@@ -10311,7 +10390,7 @@ async def mint_key(org: str, body: KeyBody, request: Request) -> dict:@app.get("/v1/orgs/{org}/keys")async def list_keys(org: str, request: Request) -> dict:- await _owned_org(request, org)+ p = await _owned_org(request, org)try:rows = await BACKING.graph.find("HarnessApiKey", {"org": org})except Exception: # noqa: BLE001@@ -10320,16 +10399,18 @@ async def list_keys(org: str, request: Request) -> dict:"revoked": str(x.get("revoked")) in ("1", "true", "True"), "member": x.get("member"),"workspace": x.get("workspace") or "", "last_used": x.get("last_used") or "", "tail": x.get("tail") or ""}for x in rows]+ if _key_scope(p): # a key held to a workspace sees that workspace's keys+ keys = [k for k in keys if _scope_keeps(p, k["workspace"])]return {"keys": keys}@app.delete("/v1/orgs/{org}/keys/{kid}")async def revoke_key(org: str, kid: str, request: Request) -> dict:- await _owned_org(request, org)+ p = await _owned_org(request, org)# V1C02-005: the key must belong to THIS org — otherwise a caller could revoke another org's# key by id. Verify org ownership on the vertex before writing the tombstone.kv = await _vertex_get(kid)- if kv and str(kv.get("org") or "") != org:+ if kv and (str(kv.get("org") or "") != org or not _scope_keeps(p, kv.get("workspace"))):raise HTTPException(404, "key not found")# Graph revoke FIRST and it MUST succeed (raise_on_fail): the graph is the backstop the hot# read falls to when the store doc expires. A silently-failed graph revoke would let the key@@ -10822,14 +10903,11 @@ async def _hosted_resolve(server: str, hid: str, org: str, servers: list[dict],return entry, rec-async def _harness_for_route(hid: str, org: str) -> dict:- """The harness a /servers/{sid} route is addressed to: owned by this org, not deleted, and- converted off any earlier shape first — which is the reason this is a helper rather than the- three inline lines every other route carries."""- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")- return await _mcp_migrate(org, hid, v)+async def _harness_for_route(hid: str, caller: dict) -> dict:+ """The harness a /servers/{sid} route is addressed to: in the caller's reach (its organization,+ its workspace, not deleted) and converted off any earlier shape first."""+ v = await _harness_in_reach(caller, hid)+ return await _mcp_migrate(str(caller.get("org") or ""), hid, v)# ── migration: two earlier shapes of "the harness's database" ─────────────────────────────────@@ -11137,8 +11215,9 @@ async def get_harness_server(hid: str, sid: str, request: Request) -> dict:The server that owns the connection is the one that names it, exactly as tools/list is athird-party server describing itself. Connection state does not ride a harness read."""- org, _ = await _pub_org_member(request)- v = await _harness_for_route(hid, org)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_for_route(hid, _caller)# WHICH server this is comes from the record, not from a field on the entry and not from the# route. One route, because "the server describing itself" is one question — and the entry has# nothing on it to branch on, which is the property this whole shape exists to keep.@@ -11179,8 +11258,9 @@ async def _hosted_resolve_any(hid: str, org: str, servers: list[dict], *,@app.post("/v1/harnesses/{hid}/servers/{sid}/query", include_in_schema=False)async def run_server_query(hid: str, sid: str, body: SqlQueryBody, request: Request) -> dict:"""Run one SELECT — what refreshing a dashboard panel does."""- org, _ = await _pub_org_member(request)- v = await _harness_for_route(hid, org)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_for_route(hid, _caller)_entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v), entry_id=sid)want = int(body.max_rows or sql_plane.DEFAULT_MAX_ROWS)max_rows = max(1, min(want, sql_plane.DEFAULT_MAX_ROWS))@@ -11194,8 +11274,9 @@ async def run_server_query(hid: str, sid: str, body: SqlQueryBody, request: Requasync def get_server_schema(hid: str, sid: str, request: Request) -> dict:"""The shape of the connected database: tables, columns, types — and a few rows per table whenthe person left sample rows on. `sampled` in the response says which they got."""- org, _ = await _pub_org_member(request)- v = await _harness_for_route(hid, org)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_for_route(hid, _caller)_entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v), entry_id=sid)try:return await sql_plane.introspect(rec["engine"], rec["dsn"],@@ -13821,8 +13902,9 @@ async def _media_route(hid: str, sid: str, eid: str, request: Request,still offers them. The app that owns that screen has to say so and offer the way back, which iswhy the kit renders this 404 as a video that cannot be opened rather than as a bare canvas."""- org, _ = await _pub_org_member(request)- v = await _harness_for_route(hid, org)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_for_route(hid, _caller)if servers:# the bytes route only: a screenshot the browser plug stored is the session's media tooentry, rec0 = await _hosted_resolve_any(hid, org, _mcp_list(v), entry_id=eid)@@ -14387,10 +14469,12 @@ async def _plug_lookup_local(org: str, workspace: str, plug_type: str) -> tuple[return (rec["status"] if rec["status"] in _PLUG_STATUSES else "needs_auth"), rec-def _plug_workspace(request: Request) -> str:- """The workspace a plug route is about: the console names it; a bare API call means the- instance's default workspace, the one the console's own harnesses are in."""- return str(request.headers.get("x-harness-workspace") or "default")+def _plug_workspace(request: Request, caller: dict) -> str:+ """The workspace a plug route is about. A key held to a workspace gets its own, whatever header+ it sends (it used to be able to name any workspace there). Any other caller names it: the+ console always does, and a bare API call means the instance's default workspace, the one the+ console's own harnesses are in."""+ return _key_scope(caller) or str(request.headers.get("x-harness-workspace") or "default")class PlugBody(BaseModel):@@ -14415,8 +14499,9 @@ def _plug_public(org: str, workspace: str, plug_type: str, rec: dict | None, staasync def list_plugs(request: Request) -> dict:"""The plugin catalog for the caller's workspace: every type this instance serves, with itsstate here (connected, disabled, needs_auth, missing)."""- org, _ = await _pub_org_member(request)- workspace = _plug_workspace(request)+ _caller = await _pub_principal(request)+ org, _ = _caller["org"], _caller.get("member", "")+ workspace = _plug_workspace(request, _caller)out = []for t in _PLUG_FORMS:status, rec = await _plug_lookup(org, workspace, t)@@ -14429,14 +14514,15 @@ async def put_plug(plug_type: str, body: PlugBody, request: Request) -> dict:"""Connect a plugin for the caller's workspace, change its settings, or turn it off. Acredential goes to the instance's secret store, never onto the record; a plug that needs oneand has none yet reads needs_auth until it is given."""- org, _ = await _pub_org_member(request)+ _caller = await _pub_principal(request)+ org = _caller["org"]if PLUGS_REGISTRY_URL:raise uhp_error(409, "registry_elsewhere", "Plugins on this deployment are managed on the Plugins page of the workspace.", "plug_type")form = _PLUG_FORMS.get(plug_type)if not form:raise uhp_error(404, "plug_not_found", f"No plugin of type {plug_type!r}.", "plug_type",{"supported": sorted(_PLUG_FORMS)})- workspace = _plug_workspace(request)+ workspace = _plug_workspace(request, _caller)_status, prev = await _plug_lookup_local(org, workspace, plug_type)config = dict((prev or {}).get("config") or {})for k, v in (body.config or {}).items():@@ -14569,10 +14655,11 @@ class MicrosoftCompleteBody(BaseModel):@app.post("/v1/plugs/microsoft365/microsoft/start")async def microsoft_start(body: MicrosoftStartBody, request: Request) -> dict:"""Where the person goes to sign in with Microsoft for this workspace's application."""- org, member = await _pub_org_member(request)+ _caller = await _pub_principal(request)+ org, member = _caller["org"], _caller.get("member", "")if PLUGS_REGISTRY_URL:raise uhp_error(409, "registry_elsewhere", "Plugins on this deployment are managed on the Plugins page of the workspace.", "plug_type")- workspace = _plug_workspace(request)+ workspace = _plug_workspace(request, _caller)rec = await _m365_plug(org, workspace)config = rec.get("config") or {}if plugs_plane.m365_mode({}, config) != "delegated":@@ -14638,8 +14725,9 @@ async def microsoft_complete(body: MicrosoftCompleteBody, request: Request) -> dasync def microsoft_signout(request: Request) -> dict:"""Forget this person's sign-in: their refresh token and their account on the record. Withnobody signed in a delegated plug waits for a sign-in again."""- org, member = await _pub_org_member(request)- workspace = _plug_workspace(request)+ _caller = await _pub_principal(request)+ org, member = _caller["org"], _caller.get("member", "")+ workspace = _plug_workspace(request, _caller)rec = await _m365_plug(org, workspace)config = dict(rec.get("config") or {})field = plugs_plane.m365_person_field(member)@@ -14673,10 +14761,11 @@ async def microsoft_signout(request: Request) -> dict:@app.get("/v1/plugs/{plug_type}/attachments")async def plug_attachments_public(plug_type: str, request: Request) -> dict:"""How many of the caller's workspace's harnesses include this plugin, from the bindings."""- org, _ = await _pub_org_member(request)+ _caller = await _pub_principal(request)+ org, _ = _caller["org"], _caller.get("member", "")if plug_type not in _PLUG_FORMS:raise uhp_error(404, "plug_not_found", f"No plugin of type {plug_type!r}.", "plug_type")- workspace = _plug_workspace(request)+ workspace = _plug_workspace(request, _caller)rows = _plugs_harness_rows(org, workspace, await BACKING.graph.find("Harness", {"org": org}))attached = []for r in rows:@@ -14705,12 +14794,13 @@ async def delete_plug(plug_type: str, request: Request) -> dict:"""Remove a plugin from the workspace: the record goes and the credential it kept is deletedfrom the secret store. A harness that includes it keeps its entry and loses the tools on itsnext task; nothing at the service changes, and the workspace can connect it again."""- org, _ = await _pub_org_member(request)+ _caller = await _pub_principal(request)+ org = _caller["org"]if PLUGS_REGISTRY_URL:raise uhp_error(409, "registry_elsewhere", "Plugins on this deployment are managed on the Plugins page of the workspace.", "plug_type")if plug_type not in _PLUG_FORMS:raise uhp_error(404, "plug_not_found", f"No plugin of type {plug_type!r}.", "plug_type")- workspace = _plug_workspace(request)+ workspace = _plug_workspace(request, _caller)_status, rec = await _plug_lookup_local(org, workspace, plug_type)if not rec:raise uhp_error(404, "plug_not_connected", f"No {plugs_plane.TYPES[plug_type]} plugin is connected for this workspace.", "plug_type")@@ -14820,8 +14910,9 @@ async def _plugs_server_out(org: str, entry: dict, rec: dict) -> dict:async def attach_plugs(hid: str, body: PlugsBody, request: Request) -> dict:"""Attach the workspace's plugs to one of the caller's harnesses. Idempotent: attaching againreplaces the list of plugs and tools and rewrites nothing else."""- org, _ = await _pub_org_member(request)- v = await _harness_for_route(hid, org)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_for_route(hid, _caller)plugs = _plugs_types_ok(body.plugs)await _plugs_attach(org, hid, v, plugs, _plugs_tools_ok(body.tools, plugs))entry, rec = await _hosted_resolve(_PLUGS_SERVER, hid, org, _mcp_list(await _vertex_get(hid) or v),@@ -14833,8 +14924,9 @@ async def attach_plugs(hid: str, body: PlugsBody, request: Request) -> dict:async def detach_plugs(hid: str, request: Request) -> dict:"""Detach them: the entry goes and its binding record is scrubbed. The plugs themselves stayconnected to the workspace for every other harness."""- org, _ = await _pub_org_member(request)- v = await _harness_for_route(hid, org)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_for_route(hid, _caller)cur = _mcp_list(v)after = [e for e in cur if str(e.get("id") or "") != _PLUGS_ENTRY["id"]]if len(after) == len(cur):@@ -17314,7 +17406,8 @@ def _workspace_keep(item_ws: str, workspace: str, ws_default: bool) -> bool:async def create_harness(org: str, body: HarnessBody, request: Request) -> dict:p = await _owned_org(request, org)member = p.get("member") or request.headers.get("x-harness-member", "")- workspace = request.headers.get("x-harness-workspace", "")+ # a key held to a workspace stamps its own, whatever header it sends; any other caller names it+ workspace = _key_scope(p) or request.headers.get("x-harness-workspace", "")body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)await _environment_check_ref(org, body.environment)@@ -17338,7 +17431,9 @@ async def list_harnesses(org: str, request: Request,vs empty for org keys); GET-by-id never filtered by member anyway. The member propis still recorded on the vertex for attribution. Optional `workspace` narrows to oneworkspace (Space id); `workspace_default=1` lets unstamped legacy records through."""- await _owned_org(request, org)+ p = await _owned_org(request, org)+ if _key_scope(p): # a key held to a workspace lists that workspace, whatever it asks for+ workspace, workspace_default = _key_scope(p), 0rows = await _vg_list_by_org("Harness", org)items = [_harness_out(await _mcp_migrate(org, str(r.get("id") or ""), r)) for r in rowsif str(r.get("deleted")) not in ("1", "true", "True")]@@ -17350,10 +17445,7 @@ async def list_harnesses(org: str, request: Request,@app.get("/v1/orgs/{org}/harnesses/{hid}")async def get_harness(org: str, hid: str, request: Request) -> dict:- await _owned_org(request, org)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _harness_in_reach(await _owned_org(request, org), hid)return _harness_out(await _mcp_migrate(org, hid, v))@@ -17361,10 +17453,7 @@ async def get_harness(org: str, hid: str, request: Request) -> dict:async def get_harness_models(org: str, hid: str, request: Request) -> dict:"""Model-capability view for a harness (internal / console BFF): allowed models, default, andthe authorized fallback. The console populates its model selector from this."""- await _owned_org(request, org)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _harness_in_reach(await _owned_org(request, org), hid)backend = (_backend_of_harness(v) or _backend_of_builtin(hid)or _route_backend(str(v.get("default_model") or ""), None))return {"harness_id": hid,@@ -17375,10 +17464,7 @@ async def get_harness_models(org: str, hid: str, request: Request) -> dict:async def get_harness_skill_files(org: str, hid: str, skill_id: str, request: Request) -> dict:"""Full files of one harness skill, resolving the blob offload — the console uses this tohydrate a folder skill for editing (large bundles round-trip as {name, enabled, blob})."""- await _owned_org(request, org)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _harness_in_reach(await _owned_org(request, org), hid)try:skills = json.loads(v.get("skills") or "[]")except Exception: # noqa: BLE001@@ -17394,10 +17480,7 @@ async def get_harness_skill_files(org: str, hid: str, skill_id: str, request: Re@app.get("/v1/orgs/{org}/harnesses/{hid}/plugins/{name}/files")async def get_harness_plugin_files(org: str, hid: str, name: str, request: Request) -> dict:"""The complete package of one installed plugin (Plugins §3.1), byte-for-byte."""- await _owned_org(request, org)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _harness_in_reach(await _owned_org(request, org), hid)pe = _plugin_entry(v, name)files = await _plugin_files_of(pe, org)if not files:@@ -17408,20 +17491,15 @@ async def get_harness_plugin_files(org: str, hid: str, name: str, request: Reque@app.get("/v1/orgs/{org}/harnesses/{hid}/plugin")async def export_harness_plugin(org: str, hid: str, request: Request) -> dict:"""The harness's own tools and skills as an Agent Plugins package (Plugins §5)."""- await _owned_org(request, org)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _harness_in_reach(await _owned_org(request, org), hid)return await _harness_export_plugin(await _mcp_migrate(org, hid, v) or v)@app.put("/v1/orgs/{org}/harnesses/{hid}")async def update_harness(org: str, hid: str, body: HarnessBody, request: Request) -> dict:- await _owned_org(request, org)+ _caller = await _owned_org(request, org)# V1C02-005: bind the mutation to the caller's org — a foreign harness id must not be editable.- cur = await _vertex_get(hid)- if not cur or str(cur.get("org") or "") != org or str(cur.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ cur = await _harness_in_reach(_caller, hid)cur = await _mcp_migrate(org, hid, cur)# Harnesses §5.2: id, base and createdAt are immutable. A body naming a different base is# refused rather than applied, because applying it would change the behaviour of every@@ -17447,11 +17525,9 @@ async def update_harness(org: str, hid: str, body: HarnessBody, request: Request@app.delete("/v1/orgs/{org}/harnesses/{hid}")async def delete_harness(org: str, hid: str, request: Request) -> dict:- await _owned_org(request, org)+ _caller = await _owned_org(request, org)# V1C02-005: only delete a harness that belongs to the caller's org.- cur = await _vertex_get(hid)- if not cur or str(cur.get("org") or "") != org:- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ cur = await _harness_in_reach(_caller, hid, deleted_ok=True)cur = await _mcp_migrate(org, hid, cur)await _vg_upsert("Harness", hid, {"deleted": "1"})# a deleted agent must not still be holding a database password, and must not still be@@ -17523,7 +17599,10 @@ class WorkspaceBody(BaseModel):@app.post("/v1/hr/workspaces")async def workspaces_create(body: WorkspaceBody, request: Request) -> dict:- org, member = await _pub_org_member(request)+ _caller = await _pub_principal(request)+ org, member = _caller["org"], _caller.get("member", "")+ if _key_scope(_caller):+ raise uhp_error(403, "forbidden", "A key held to one workspace does not make workspaces.")name = (body.name or "").strip()if not name:raise HTTPException(400, "a workspace needs a name")@@ -17552,7 +17631,10 @@ async def workspaces_create(body: WorkspaceBody, request: Request) -> dict:@app.patch("/v1/hr/workspaces/{wid}")async def workspaces_update(wid: str, body: WorkspaceBody, request: Request) -> dict:- org, _member = await _pub_org_member(request)+ _caller = await _pub_principal(request)+ org = _caller["org"]+ if _key_scope(_caller) and _key_scope(_caller) != wid:+ raise uhp_error(403, "forbidden", "A key held to one workspace changes that workspace only.")rows = await _workspace_rows(org)v = next((r for r in rows if str(r.get("ws_id")) == wid), None)if v is None:@@ -17567,6 +17649,15 @@ async def workspaces_update(wid: str, body: WorkspaceBody, request: Request) -># ── PUBLIC harness CRUD (Bearer sk-hr-... API key; org resolved from the key) ──────────# This is what a vibe coder's agent (driven by AGENTS.md) calls — no org id, no internal header.+async def _pub_principal(request: Request) -> dict:+ """The caller of a public route, whole: its organization AND the workspace it is narrowed to,+ which a route that takes an id needs and (org, member) alone left behind."""+ p = await _principal(request)+ if not p.get("org"):+ raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")+ return p++async def _pub_org_member(request: Request) -> tuple[str, str]:p = await _principal(request)org = p.get("org", "")@@ -18286,6 +18377,7 @@ class CloudUploadOneBody(BaseModel):@app.post("/v1/harnesses/{hid}/upload", include_in_schema=False)async def cloud_upload_one(hid: str, request: Request, body: CloudUploadOneBody | None = None) -> dict:p = await _principal(request)+ await _harness_in_reach(p, hid)target = await _cloud_pick_target((body.target if body else None))records = await _cloud_records()res = await _cloud_upload_one(p.get("org", ""), hid, target, records)@@ -18300,6 +18392,8 @@ async def cloud_upload_one(hid: str, request: Request, body: CloudUploadOneBodyasync def cloud_upload_status(hid: str, request: Request) -> dict:"""The chip on the harness page: never uploaded, uploaded, or changed since."""p = await _principal(request)+ if hid not in _BASE_CATALOG:+ await _harness_in_reach(p, hid)records = await _cloud_records()per = records.get("harnesses", {}).get(hid) or {}if not per:@@ -18330,10 +18424,9 @@ async def cloud_upload_status_all(request: Request) -> dict:@app.get("/v1/harnesses/{hid}")async def get_harness_public(hid: str, request: Request) -> dict:- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid)return _harness_out(await _mcp_migrate(org, hid, v))@@ -18455,10 +18548,9 @@ async def list_models(request: Request) -> dict:async def get_harness_models_public(hid: str, request: Request) -> dict:"""Model-capability view for a harness (public, Bearer): allowed models, default, authorizedfallback. A request for a model outside this set is replaced by the fallback at run time."""- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid)backend = (_backend_of_harness(v) or _backend_of_builtin(hid)or _route_backend(str(v.get("default_model") or ""), None))return {"harness_id": hid,@@ -18470,10 +18562,7 @@ async def get_harness_skill_files_public(hid: str, skill_id: str, request: Reque"""Full files of one skill (public, Bearer), resolving the server-side blob offload — largefolder bundles round-trip on the harness record as {name, enabled, blob}; this returns thereal files for editing or verification. `skill_id` matches the entry's id or name."""- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ v = await _harness_in_reach(await _pub_principal(request), hid)try:skills = json.loads(v.get("skills") or "[]")except Exception: # noqa: BLE001@@ -18489,10 +18578,9 @@ async def get_harness_skill_files_public(hid: str, skill_id: str, request: Reque@app.get("/v1/harnesses/{hid}/plugins/{name}/files")async def get_harness_plugin_files_public(hid: str, name: str, request: Request) -> dict:"""UHP Plugins §3.1: the complete package of one installed plugin."""- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid)pe = _plugin_entry(v, name)files = await _plugin_files_of(pe, org)if not files:@@ -18503,10 +18591,9 @@ async def get_harness_plugin_files_public(hid: str, name: str, request: Request)@app.get("/v1/harnesses/{hid}/plugin")async def export_harness_plugin_public(hid: str, request: Request) -> dict:"""UHP Plugins §5: the harness's own tools and skills as an Agent Plugins package."""- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid)return await _harness_export_plugin(await _mcp_migrate(org, hid, v) or v)@@ -18522,10 +18609,9 @@ async def publish_harness_plugin(hid: str, body: PluginPublishBody, request: Reqharness holds (a kit's, or one installed by hand) and every other package stays; the harness'snext turn runs it. This is `set_config` for a harness whose configuration lives in its package(docs/dual-loop.md, Appendix B), and the route a calibration credential publishes through."""- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid)v = await _mcp_migrate(org, hid, v)item = {k: getattr(body, k) for k in ("name", "files", "blob") if getattr(body, k)}if not item.get("files") and not item.get("blob"):@@ -18542,10 +18628,9 @@ async def publish_harness_plugin(hid: str, body: PluginPublishBody, request: Req@app.put("/v1/harnesses/{hid}")async def update_harness_public(hid: str, body: HarnessBody, request: Request) -> dict:- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid)_p = await _principal(request)if _p.get("calibration") and str(body.calibrates or "") != str(v.get("calibrates") or ""):raise uhp_error(403, "forbidden", "A calibration credential cannot grant calibration.", "calibrates")@@ -18568,10 +18653,9 @@ async def update_harness_public(hid: str, body: HarnessBody, request: Request) -@app.delete("/v1/harnesses/{hid}")async def delete_harness_public(hid: str, request: Request) -> dict:- org, _ = await _pub_org_member(request)- v = await _vertex_get(hid)- if not v or v.get("org") != org:- raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ _caller = await _pub_principal(request)+ org = _caller["org"]+ v = await _harness_in_reach(_caller, hid, deleted_ok=True)v = await _mcp_migrate(org, hid, v)await _vg_upsert("Harness", hid, {"deleted": "1"})# a deleted agent must not still be holding a database password, and must not still bediff --git a/gateway/tests/test_workspace_scope.py b/gateway/tests/test_workspace_scope.pynew file mode 100644index 00000000..ae87ab6c--- /dev/null+++ b/gateway/tests/test_workspace_scope.py@@ -0,0 +1,274 @@+"""A key held to a workspace reaches that workspace and nothing else of the organization.++The lists always held to this. The routes that take an id checked the organization and stopped, so a+workspace's key that knew an id read, changed and deleted another workspace's harnesses, sessions+and responses, and could mint itself a key with no workspace at all (reported privately three times).+The rule is one function, `_scope_keeps`; the last test reads every route to see that it is asked.++Who is held: an API key of a workspace other than the Default Workspace. Who is not (Richard,+2026-10-06, the same on the hosted service): a person in the console, a key for the whole+organization, and a Default Workspace key, which is what a key was before workspaces existed.+"""+import ast+import asyncio+import pathlib+import re+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"+KEY_A = {"org": ORG, "member": "svc-a", "workspace": "space.a", "workspace_default": False, "via": "api_key"}+KEY_DEFAULT = {"org": ORG, "member": "svc-d", "workspace": "default", "workspace_default": True, "via": "api_key"}+KEY_ORG = {"org": ORG, "member": "svc-o", "workspace": "", "workspace_default": False, "via": "api_key"}+CONSOLE_A = {"org": ORG, "member": "[email protected]", "workspace": "space.a", "workspace_default": False}++GRAPH = {+ "chrn_a": {"id": "chrn_a", "org": ORG, "workspace": "space.a", "deleted": "0"},+ "chrn_b": {"id": "chrn_b", "org": ORG, "workspace": "space.b", "deleted": "0"},+ "chrn_old": {"id": "chrn_old", "org": ORG, "workspace": "", "deleted": "0"},+ "chrn_gone": {"id": "chrn_gone", "org": ORG, "workspace": "space.a", "deleted": "1"},+ "chrn_x": {"id": "chrn_x", "org": "org-x", "workspace": "space.a", "deleted": "0"},+ "hsess_a": {"tenant": ORG, "workspace": "space.a", "status": "idle", "harness_id": "chrn_a"},+ "hsess_b": {"tenant": ORG, "workspace": "space.b", "status": "idle", "harness_id": "chrn_b"},+ "hsess_old": {"tenant": ORG, "workspace": "", "status": "idle", "harness_id": "chrn_old"},+ "key_a": {"org": ORG, "workspace": "space.a"},+ "key_b": {"org": ORG, "workspace": "space.b"},+}+RESP = {r: {"id": r, "_org": ORG, "_session_id": s} for r, s in (("resp_a", "hsess_a"), ("resp_b", "hsess_b"), ("resp_old", "hsess_old"))}+++class _Req:+ def __init__(self, headers=None, path="/", method="GET"):+ self.headers, self.method = headers or {}, method+ self.url = type("U", (), {"path": path})()+++def world(monkeypatch):+ writes = []++ async def vertex_get(vid):+ return dict(GRAPH[vid]) if vid in GRAPH else None++ async def resp_get(rid):+ return dict(RESP[rid]) if rid in RESP else None++ async def upsert(label, vid, props, **kw):+ writes.append((label, vid, dict(props)))+ monkeypatch.setattr(gw, "_vertex_get", vertex_get)+ monkeypatch.setattr(gw, "_resp_get", resp_get)+ monkeypatch.setattr(gw, "_vg_upsert", upsert)+ monkeypatch.setattr(gw.control_store, "enabled", lambda: False)+ return writes+++def _as(monkeypatch, principal):+ async def who(request):+ return dict(principal)+ monkeypatch.setattr(gw, "_principal", who)+++def _status(coro) -> int:+ with pytest.raises(HTTPException) as e:+ asyncio.run(coro)+ return e.value.status_code+++# ── the rule ───────────────────────────────────────────────────────────────────────────────────++def test_the_rule():+ keeps, held = gw._scope_keeps, gw._key_scope+ assert held(KEY_A) == "space.a"+ assert keeps(KEY_A, "space.a") and not keeps(KEY_A, "space.b")+ assert not keeps(KEY_A, "") and not keeps(KEY_A, None) # made before workspaces: the Default Workspace's+ # not held: a Default Workspace key, a key for the whole organization, a person in the console+ for p in (KEY_DEFAULT, KEY_ORG, CONSOLE_A, {"org": ORG, "workspace": "org-a__hr_default", "via": "api_key"}):+ assert held(p) == "" and all(keeps(p, ws) for ws in ("space.a", "space.b", "default", "", None)), p+ assert held({"org": ORG, "workspace": "other__hr_default", "via": "api_key"}) == "other__hr_default" # another organization's default is not this one's+++# ── harnesses ──────────────────────────────────────────────────────────────────────────────────++def test_a_harness_is_found_only_inside_a_held_keys_workspace(world):+ reach = lambda p, hid, **k: asyncio.run(gw._harness_in_reach(p, hid, **k)) # noqa: E731+ assert reach(KEY_A, "chrn_a")["id"] == "chrn_a"+ for hid in ("chrn_b", "chrn_old", "chrn_gone", "chrn_x", "chrn_nope"):+ assert _status(gw._harness_in_reach(KEY_A, hid)) == 404, hid+ for p in (KEY_DEFAULT, KEY_ORG, CONSOLE_A): # organization reach+ assert [reach(p, h)["id"] for h in ("chrn_a", "chrn_b", "chrn_old")] == ["chrn_a", "chrn_b", "chrn_old"]+ assert _status(gw._harness_in_reach(p, "chrn_x")) == 404 # ...of its own organization+ assert reach(KEY_A, "chrn_gone", deleted_ok=True)["id"] == "chrn_gone" # deleting again is allowed, in its own workspace+ assert _status(gw._harness_in_reach({"org": "", "workspace": ""}, "chrn_a")) == 404++[email protected]("call", [+ lambda: gw.get_harness_public("chrn_b", _Req()),+ lambda: gw.update_harness_public("chrn_b", gw.HarnessBody(name="HIJACKED", base="pi"), _Req()),+ lambda: gw.delete_harness_public("chrn_b", _Req()),+ lambda: gw.get_harness(ORG, "chrn_b", _Req()),+ lambda: gw.update_harness(ORG, "chrn_b", gw.HarnessBody(name="HIJACKED", base="pi"), _Req()),+ lambda: gw.delete_harness(ORG, "chrn_b", _Req()),+ lambda: gw.get_harness_models_public("chrn_b", _Req()),+ lambda: gw.export_harness_plugin_public("chrn_b", _Req()),+ lambda: gw.cloud_upload_status("chrn_b", _Req()),+ lambda: gw.harness_events("chrn_b", _Req()),+ lambda: gw.detach_plugs("chrn_b", _Req()),+], ids=["read", "overwrite", "delete", "read-org-path", "overwrite-org-path", "delete-org-path", "models", "package",+ "upload-status", "events", "detach-plugs"])+def test_another_workspaces_harness_is_not_found_on_any_route_and_nothing_is_written(world, monkeypatch, call):+ _as(monkeypatch, KEY_A)+ assert _status(call()) == 404+ assert world == []+++# ── sessions and responses ─────────────────────────────────────────────────────────────────────++def test_a_session_is_found_only_inside_a_held_keys_workspace(world, monkeypatch):+ _as(monkeypatch, KEY_A)+ assert asyncio.run(gw._owned_session(_Req(), "hsess_a"))[1]["harness_id"] == "chrn_a"+ assert _status(gw._owned_session(_Req(), "hsess_b")) == 404 and _status(gw._owned_session(_Req(), "hsess_old")) == 404+ for p in (KEY_DEFAULT, KEY_ORG, CONSOLE_A):+ _as(monkeypatch, p)+ assert [asyncio.run(gw._owned_session(_Req(), s))[0] for s in ("hsess_a", "hsess_b", "hsess_old")] == [ORG] * 3++[email protected]("call", [+ lambda: gw.delete_trace("hsess_b", _Req()),+ lambda: gw.artifact_by_path("hsess_b", "report.pdf", _Req()),+ lambda: gw.set_session_share("hsess_b", _Req()),+ lambda: gw.revoke_session_share("hsess_b", _Req()),+ lambda: gw.get_session_share("hsess_b", _Req()),+ lambda: gw.get_response("resp_b", _Req()),+ lambda: gw.delete_response("resp_b", _Req()),+ lambda: gw.list_input_items("resp_b", _Req()),+ lambda: gw.cancel_response("resp_b", _Req()),+], ids=["delete", "artifact", "publish", "unpublish", "share-state", "read-response", "delete-response", "input-items", "cancel"])+def test_another_workspaces_session_and_its_responses_are_not_found(world, monkeypatch, call):+ _as(monkeypatch, KEY_A)+ assert _status(call()) == 404+ assert world == []+++def test_a_response_is_reached_through_its_session(world):+ reach = lambda p, r: asyncio.run(gw._response_in_reach(p, RESP.get(r))) # noqa: E731+ assert reach(KEY_A, "resp_a") and not reach(KEY_A, "resp_b") and not reach(KEY_A, "resp_old")+ assert all(reach(p, r) for p in (KEY_DEFAULT, KEY_ORG, CONSOLE_A) for r in ("resp_a", "resp_b", "resp_old"))+ assert not asyncio.run(gw._response_in_reach(KEY_A, {"id": "resp_orphan", "_org": ORG})) # no session: not a narrowed caller's+ assert asyncio.run(gw._response_in_reach(KEY_ORG, {"id": "resp_orphan", "_org": ORG}))+++def test_a_conversation_of_another_workspace_is_not_continued(world):+ for prev, hint in (("resp_b", ""), ("", "hsess_b"), ("", "hsess_old")):+ assert _status(gw._resp_resolve_session(ORG, "svc-a", prev or None, "pi", session_hint=hint,+ workspace="space.a", caller=KEY_A)) == 404+ assert world == []+++def test_a_caller_with_organization_reach_continues_any_conversation_of_it(world, monkeypatch):+ seen = []++ async def trace_cursor(tr):+ seen.append(tr)+ monkeypatch.setattr(gw, "_recover_trace_cursor", trace_cursor)+ monkeypatch.setattr(gw, "_prefix_from_vertex", lambda sid, v: f"{ORG}/x_{sid}")++ async def vupsert(sid, props):+ pass+ monkeypatch.setattr(gw, "_vertex_upsert", vupsert)+ for p in (KEY_DEFAULT, KEY_ORG, CONSOLE_A):+ sid, _resume = asyncio.run(gw._resp_resolve_session(ORG, "m", None, "pi", session_hint="hsess_b", workspace="", caller=p))+ assert sid == "hsess_b"+++# ── keys ───────────────────────────────────────────────────────────────────────────────────────++def _mint(monkeypatch, caller, **body):+ _as(monkeypatch, caller)+ return asyncio.run(gw.mint_key(ORG, gw.KeyBody(**body), _Req()))+++def test_a_held_key_mints_keys_for_its_own_workspace_under_its_own_name(world, monkeypatch):+ out = _mint(monkeypatch, KEY_A, member_id="attacker@evil", workspace="")+ stored = world[-1][2]+ assert out["workspace"] == "space.a" and stored["workspace"] == "space.a" and stored["member"] == "svc-a"+ assert stored["workspace_default"] == ""+ assert _status(gw.mint_key(ORG, gw.KeyBody(workspace="space.b"), _Req())) == 403+++def test_a_person_and_a_key_with_organization_reach_choose_what_they_mint(world, monkeypatch):+ # a person in the console makes an organization key on purpose: the body says so, no header trick+ _mint(monkeypatch, CONSOLE_A, workspace="", member_id="[email protected]")+ assert world[-1][2]["workspace"] == "" and world[-1][2]["member"] == "[email protected]"+ _mint(monkeypatch, CONSOLE_A, workspace="space.b", member_id="[email protected]")+ assert world[-1][2]["workspace"] == "space.b"+ # a Default Workspace key mints a workspace's key for it, and may name whose it is+ _mint(monkeypatch, KEY_DEFAULT, workspace="space.b", member_id="company-b")+ assert world[-1][2]["workspace"] == "space.b" and world[-1][2]["member"] == "company-b"+ _mint(monkeypatch, KEY_ORG, workspace="", member_id="x")+ assert world[-1][2]["workspace"] == ""+++def test_a_held_key_revokes_and_lists_its_own_workspaces_keys(world, monkeypatch):+ _as(monkeypatch, KEY_A)+ assert _status(gw.revoke_key(ORG, "key_b", _Req())) == 404 and world == []+ assert asyncio.run(gw.revoke_key(ORG, "key_a", _Req()))["revoked"] is True++ class _Graph:+ async def find(self, label, where):+ return [{"id": "key_a", "workspace": "space.a"}, {"id": "key_b", "workspace": "space.b"}, {"id": "key_o", "workspace": ""}]+ monkeypatch.setattr(gw.BACKING, "graph", _Graph())+ assert [k["id"] for k in asyncio.run(gw.list_keys(ORG, _Req()))["keys"]] == ["key_a"]+ for p in (KEY_ORG, KEY_DEFAULT, CONSOLE_A):+ _as(monkeypatch, p)+ assert len(asyncio.run(gw.list_keys(ORG, _Req()))["keys"]) == 3+ assert asyncio.run(gw.revoke_key(ORG, "key_b", _Req()))["revoked"] is True # a company's key, retired by the organization's+++def test_a_held_key_does_not_make_or_rename_workspaces(world, monkeypatch):+ _as(monkeypatch, KEY_A)+ assert _status(gw.workspaces_create(gw.WorkspaceBody(name="mine"), _Req())) == 403+ assert _status(gw.workspaces_update("space.b", gw.WorkspaceBody(name="theirs"), _Req())) == 403+++def test_a_held_keys_plug_routes_are_about_its_own_workspace_whatever_header_it_sends():+ named_b = _Req(headers={"x-harness-workspace": "space.b"})+ assert gw._plug_workspace(named_b, KEY_A) == "space.a"+ assert gw._plug_workspace(named_b, CONSOLE_A) == "space.b" and gw._plug_workspace(named_b, KEY_DEFAULT) == "space.b"+ assert gw._plug_workspace(_Req(), KEY_ORG) == "default"+++# ── every route that takes an id asks ──────────────────────────────────────────────────────────++IDS = {"hid", "harness_id", "sid", "response_id", "container_id", "kid", "env_id", "wid"}+ASKS = {"_owned_session", "_owned_environment", "_harness_in_reach", "_harness_for_route", "_media_route",+ "_response_in_reach", "_scope_keeps"}+# A route that takes an id and is not held to a workspace, with the reason it is not.+EXEMPT = {+ "recycle_session_sandbox": "behind the internal key: the platform's own call, no caller to narrow",+ "workspace_by_path": "the public artifact address: one unguessable link, its own check, no caller at all",+ "workspaces_update": "the id IS a workspace: refuses a workspace's key that names another one",+}+++def test_every_route_that_takes_an_id_asks_whether_it_is_in_the_callers_workspace():+ tree = ast.parse(pathlib.Path(gw.__file__).read_text())+ missing, seen = [], 0+ for fn in [n for n in tree.body if isinstance(n, (ast.AsyncFunctionDef, ast.FunctionDef))]:+ for d in fn.decorator_list:+ if not (isinstance(d, ast.Call) and isinstance(d.func, ast.Attribute) and getattr(d.func.value, "id", "") == "app"+ and d.args and isinstance(d.args[0], ast.Constant) and isinstance(d.args[0].value, str)):+ continue+ if not set(re.findall(r"\{(\w+)", d.args[0].value)) & IDS:+ continue+ seen += 1+ called = {c.func.id for c in ast.walk(fn) if isinstance(c, ast.Call) and isinstance(c.func, ast.Name)}+ if not called & ASKS and fn.name not in EXEMPT:+ missing.append(f"{d.func.attr.upper()} {d.args[0].value} ({fn.name})")+ assert seen > 60, "the scan found too few routes, which means it stopped working"+ assert not missing, "routes that take an id and never ask about the workspace:\n " + "\n ".join(sorted(set(missing)))+ assert set(EXEMPT) <= {n.name for n in tree.body if isinstance(n, (ast.AsyncFunctionDef, ast.FunctionDef))}diff --git a/ui/src/app/(app)/keys/page.tsx b/ui/src/app/(app)/keys/page.tsxindex 5f4d7355..8fa67cc0 100644--- a/ui/src/app/(app)/keys/page.tsx+++ b/ui/src/app/(app)/keys/page.tsx@@ -44,6 +44,9 @@ export default function KeysPage() {const [search, setSearch] = useState('');const [sheet, setSheet] = useState<Sheet>(null);const [name, setName] = useState('');+ // What a new key reaches. Only asked outside the Default Workspace: a key made there reaches the+ // whole organization already, which the dialog says instead of asking.+ const [reach, setReach] = useState<'workspace' | 'organization'>('workspace');const [busy, setBusy] = useState(false);const [copied, setCopied] = useState(false);const [menuFor, setMenuFor] = useState<string | null>(null);@@ -85,8 +88,13 @@ export default function KeysPage() {setBusy(true); setErr('');try {const r = await harnessFetch(base, { method: 'POST', headers: { 'content-type': 'application/json' },- body: JSON.stringify({ name: keyName, member_id: member, workspace: current.id || '',- workspace_name: current.name || '', workspace_default: isDefaultWs }) });+ // A rotated key keeps the reach it had. A new one is this workspace's, or, when the person+ // chose it, an organization key: no workspace at all, said in the body.+ body: JSON.stringify((() => {+ const ws = rotateFrom ? (rotateFrom.workspace || '') : (reach === 'organization' ? '' : (current.id || ''));+ return { name: keyName, member_id: member, workspace: ws,+ workspace_name: ws ? (current.name || '') : '', workspace_default: !!ws && isDefaultWs };+ })()) });const d = await r.json();if (!r.ok) throw new Error(d.detail || JSON.stringify(d));if (rotateFrom) {@@ -129,7 +137,7 @@ export default function KeysPage() {};const menuKey = rows.find((r) => r.k.id === menuFor)?.k || null;- const openCreate = () => { setName(''); setErr(''); setCopied(false); setSheet({ kind: 'create' }); };+ const openCreate = () => { setName(''); setReach('workspace'); setErr(''); setCopied(false); setSheet({ kind: 'create' }); };return (<section className="ak-root" id="view-api-keys">@@ -137,7 +145,7 @@ export default function KeysPage() {<div className="ak-head-row"><div><h1>API keys</h1>- <p className="ak-sub">Create and revoke credentials scoped to {current.name}.</p>+ <p className="ak-sub">{isDefaultWs ? <>Create and revoke credentials. A key made in {current.name} reaches every workspace of the organization.</> : <>Create and revoke credentials for {current.name}.</>}</p></div><button className="ak-primary" type="button" disabled={!org} onClick={openCreate}>Create API key</button></div>@@ -204,13 +212,28 @@ export default function KeysPage() {<><div className="ak-modal-body"><h2 id="akTitle">Create API key</h2>- <p className="ak-modal-sub">Scoped to {current.name}. Name it after where it will live, so an unused key is easy to trace later.</p>+ <p className="ak-modal-sub">{isDefaultWs+ ? <>A key made in {current.name} reaches every workspace of the organization. To hold a key to one workspace, switch to that workspace first.</>+ : <>Name it after where it will live, so an unused key is easy to trace later.</>}</p><div className="ak-field"><div className="ak-field-k">Name</div><input value={name} placeholder="e.g. video-service · staging" autoFocus aria-label="Key name"onChange={(e) => setName(e.target.value)}onKeyDown={(e) => { if (e.key === 'Enter') void mint(name.trim() || 'Untitled key'); }} /></div>+ {!isDefaultWs && (+ <div className="ak-field">+ <div className="ak-field-k">Reach</div>+ <select id="ak-reach" value={reach} aria-label="What the key can reach"+ onChange={(e) => setReach(e.target.value === 'organization' ? 'organization' : 'workspace')}>+ <option value="workspace">{current.name} only</option>+ <option value="organization">Organization key: every workspace</option>+ </select>+ <div className="ak-field-help">{reach === 'organization'+ ? 'It reaches every workspace of the organization, and is listed under the Default Workspace.'+ : `It reaches what belongs to ${current.name} and nothing else.`}</div>+ </div>+ )}<div className="ak-warn"><i>!</i><span>The secret is shown once, on the next screen. Paste it into your server environment or the secure modal your coding agent opens, never into chat, source files, or logs.</span></div>{err && <div className="ak-err" style={{ marginTop: 14 }} role="alert">Could not create the key. {err}</div>}</div>diff --git a/ui/src/app/v2.css b/ui/src/app/v2.cssindex b92819c5..9947560b 100644--- a/ui/src/app/v2.css+++ b/ui/src/app/v2.css@@ -418,6 +418,9 @@ body {.ak-field-k { font-family: var(--v2-mono); font-size: 9.5px; letter-spacing: .14em; text-transform: uppercase; color: var(--v2-cap); margin-bottom: 7px; }.ak-field input { width: 100%; box-sizing: border-box; font: inherit; font-size: 14px; padding: 11px 13px; background: #fff; border: 1px solid #e0dcd9; border-radius: 8px; color: var(--v2-ink); }.ak-field input:focus { outline: none; border-color: var(--v2-accent); }+.ak-field select { width: 100%; box-sizing: border-box; font: inherit; font-size: 14px; padding: 11px 13px; background: #fff; border: 1px solid #e0dcd9; border-radius: 8px; color: var(--v2-ink); }+.ak-field select:focus { outline: none; border-color: var(--v2-accent); }+.ak-field-help { margin-top: 7px; font-size: 12.5px; line-height: 1.45; color: var(--v2-cap); }.ak-warn { display: flex; gap: 11px; margin-top: 18px; padding: 13px 15px; border: 1px solid #f0e2d4; border-radius: 8px; background: #fdf9f4; }.ak-warn i { font-style: normal; color: var(--v2-orange); font-size: 13px; line-height: 1.5; flex: none; font-weight: 700; }.ak-warn span { font-size: 12.5px; line-height: 1.6; color: #8a6a3c; }