Skip to content

refactor(gateway): check HTTP request authority once at admission - #203590

Merged
obviyus merged 3 commits into
mainfrom
refactor/http-authority-check-once
Nov 22, 2026
Merged

obviyus merged 3 commits into
mainfrom
refactor/http-authority-check-once

Conversation

@obviyus

@obviyus obviyus commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

What problem this solves

HTTP routes checked the caller's authority when the request was admitted, then checked it again during the request. captureHttpRequestAuthority took a snapshot of auth policy, role policy, role revision, profile alias revision and shared auth generation. bindHttpResponseAuthority then made assertCurrent(), revalidate() and hasCurrentClientAuthority() compare against that snapshot, and against operator access and profile authority, at many points inside each route. Device-token routes re-verified the token in revalidate(). Plugin-cookie routes re-read the cookie grants and role policy. Because of this, an admitted request could stop halfway with 401/403 after an unrelated settings save or role edit.

The one-admission rule is: check authority once, when the request starts. A started request finishes. Revocation, removal and reload apply to the next request.

What changed

  • src/gateway/http-request-authority.ts: deleted captureHttpRequestAuthority, bindHttpResponseAuthority, assertGatewayHttpRequestCurrent, GatewayHttpRequestAuthorityError and the GatewayHttp{Request,Response}Authority types. runGatewayHttpRequest (request abort scope) and finishGatewayHttpAuthorityError stay.
  • http-auth-utils.ts: HTTP auth results no longer carry assertCurrent or revalidate. The admission-time early refusals that compared against the snapshot are gone. The device-token revalidate overrides are gone.
  • http-auth-plugin-cookie.ts: deleted bindControlUiPluginCookieRequestAuthority (the cookie/role re-check). control-ui-plugin-assets.ts authorizes the cookie one time.
  • Route handlers no longer call those methods: Control UI bootstrap/avatar/session entry, channel/plugin/provider/workspace/project icons, managed media, user profile avatars and backgrounds, session kill, models, embeddings, OpenAI and OpenResponses, tools invoke, and plugin routes. rememberResponseSession lost its authority assertCurrent parameter (its only production caller passed the request guard).
  • Removed both names from LIFETIME_CHECK_CALLS.

Kept:

  • Request abort (Stop / client disconnect). The runGatewayHttpRequest scope signal and finishGatewayHttpAuthorityError still end the response. Response-ended checks (res.writableEnded || res.destroyed) stay where routes had them.
  • Data fences: session lifecycle revision and avatar reference (channel avatars), session row generation (workspace icons), image replacement (prepared.isCurrent()), assistant media policy, managed-media grant and ingress-session reads, and session actor readability for session kill.

Production code: 29 files, +65 / −524.

Decisions (recorded per the program rules)

  • Cut less at the WebSocket seam. AuthorizedGatewayHttpRequest.hasCurrentClientAuthority stays as an optional field (profile + operator access only). The OpenAI, OpenResponses and tools-invoke routes pass it to the agent-turn and plugin-runtime scopes. There, whether the field is present changes behavior: operator-run-authority isHttpOwner needs === true, and in-process approval dispatch checks presence. Removing it here would change owner attribution for OpenClaw ID HTTP callers. The session-mutation-guard and run-authority PRs remove it together with those readers. Plugin route scopes keep presence requestAuth || operatorAccessAuthority || ingress, so for gateway-auth routes the field is present whether the request came in by bearer or by cookie, as before.
  • Not in scope, left for later PRs: sessions-history-http re-authenticates on each SSE publish through checkGatewayHttpRequestAuth. tools-invoke-http still adds operatorAccessAuthority.signal to the request signal. operator-access-policy aborts that signal on revocation (PR 7/8).

Tests deleted (they assert a refusal after admission)

  • http-request-authority.test.ts (role-policy fence on the snapshot)
  • http-auth-utils.openclaw-id-tunnel.test.ts (device removed or role changed after admission → refusal)
  • channel-avatar-http: "rejects revoked authority while channel avatar bytes are loading"
  • managed-image-attachments.authority: revoked worker ownership read and revoked media authority after preparation
  • plugin-icon-http: revoked authority during normalization or favicon fetch
  • workspace-icon-http: changed authority during icon preparation (the workspace replacement case, a data fence, stays)
  • http-endpoint-helpers: "does not admit a parsed body after its authority was revoked while reading"
  • http-utils.authorize-request: trusted-proxy override revalidation
  • tools-invoke-http.abort: "rejects a tool when policy authority changes during its awaited hook"
  • control-ui-assistant-media-metadata: reader authority recheck variants
  • server-http.authority-outcomes: nine client-expired / role / operator-revoked / unavailable variants. The disconnect and unexpected-error variants stay, and still prove Stop through the real HTTP router
  • openresponses-session-store and the OpenResponses continuation support: revoked caller before commit / during the continuation lookup
  • control-ui-assistant-media-policy, control-ui-plugin-assets, control-ui-session-entry(.real-auth.e2e), control-ui.response-authority, http-auth-utils.paired-device, http-session-control.incognito (revoked=true rows), server.plugin-http-role-scopes, server/plugins-http (re-check before the next matched route), session-kill-http (policy-revocation and credential-rotation rows), sessions-history-http.revocation (ingress-policy row), user-background-http.authority, user-profiles-http.auth (credential rotation and device revocation during preparation), team-reports-http.gateway (expiry, generation and role change before delivery). Data-fence, admission-time and abort cases in those files stay.

Evidence

  • Plugin HTTP route, through the real HTTP router (new test): server.plugin-http-auth.test.ts › "finishes an admitted gateway-auth plugin request after its credential rotates". The plugin handler is blocked, the Gateway token rotates, then the handler calls the scope's revalidate(). The admitted request gets 200, and the next request with the old token gets 401. The same test copied onto base 3cd3a3118668 fails with expected 401 to be 200: base revalidate() re-checks the shared generation and refuses the admitted request. Stop through the real router: server-http.authority-outcomes › "cancels disconnected plugin reads without logging a handler failure". The one-admission E2E journey does not reach plugin HTTP routes, so this integration test is the plugin-route proof.
  • Pre-push tests (vitest-source): one ocx test call over the 291 importer test files, with OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1. It hit the 1 h tool deadline, so the 17 files it did not reach and every failed file ran again in two more calls. Everything passes except files that also fail on base 3cd3a3118668: cron/service.pr-automation (13), server-methods/question.own-run (4), server.config-security-policy (3-4, timeouts), server.sessions.create.projects (1), and operator-admission.table › token > principal > before-start.
  • pnpm tsgo:core and pnpm tsgo:test are clean. oxfmt and oxlint are clean on the changed files. The lifetime-check ratchet passes.
  • E2E (one-admission-e2e/run.sh): Q, R and S pass on 1d9bc6d06222 and on the final head 33a643a42c77. The live Gateway pid did not change.

- Delete captureHttpRequestAuthority, bindHttpResponseAuthority, assertGatewayHttpRequestCurrent
  and the device-token and plugin-cookie revalidate overrides. HTTP auth results no longer carry
  assertCurrent or revalidate; route handlers stop re-checking authority after admission.
- Keep request abort and data fences (session lifecycle, row generation, record replacement).
- Keep the optional hasCurrentClientAuthority pass-through for agent-turn and plugin-runtime
  scopes, where its presence still selects behavior.
- Drop both names from LIFETIME_CHECK_CALLS; delete tests that assert a refusal after admission.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: XL labels Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 33a643a42c77046ae8ee3bdc13cc01f550be2936
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/http-auth-plugin-cookie.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/http-auth-utils.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/http-request-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

…ty-check-once

# Conflicts:
#	scripts/check-lifetime-check-ratchet.mts
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 22, 2026
- Delete provider-icon device-token revalidation, the embeddings provider-acquisition revocation
  row and the revoked post-deploy session-entry handoff; prune the timeout-race baseline.

Co-authored-by: obviyus <[email protected]>
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 22, 2026
@clawsweeper

clawsweeper Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR removes repeated HTTP authority checks so admitted requests can finish after credentials or policy change.

Example: A request to /secure-hook authenticates with test-token before the Gateway rotates to rotated-token.

  • Before: Revalidation can reject the admitted request with 401.
  • After: The admitted request finishes with 200, while the next request using test-token receives 401.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The direction is supported and the production reduction is coherent, but runtime proof is pending and the consumer migration leaves required checks failing; persisted continuation fields, namespace, TTL, and lookup identity remain unchanged.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: An authenticated HTTP request can fail halfway through after a settings save or policy change.
Reason: The maintainer-authored direction matches the explicit repository admission contract, with later SSE and run-authority work clearly excluded.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep open: this maintainer-authored PR implements the documented admission contract, but its test migration leaves concrete CI failures.

Priority: P2
Reviewed head: 1d9bc6d06222f257587daadeab68b2d515a31b05

Before merge

  • Update the remaining consumer tests to the admission contract (P2) - Removing revalidation changes the held provider-icon request to 200, permits embeddings after provider acquisition, and permits an admitted session-entry handoff to finish. The unchanged tests still require 401/403 in src/gateway/provider-icon-http.server.test.ts:96, src/gateway/embeddings-http.test.ts:595, and ui/src/e2e/post-deploy-session-entry.e2e.test.ts:519. All three fail in exact-head CI with those responses. Update these consumers alongside the production change, retaining next-request refusal, cancellation, cache, and session-data assertions rather than restoring the removed rechecks.
  • Prune the removed timeout reference from its baseline (P2) - Deleting the Team Reports revocation cases removes that file's final withTestTimeout reference, but config/test-timeout-race-baseline.txt still records one reference. runPerFileCountRatchet explicitly returns failure for such stale entries, matching the timeout-race CI annotation. Regenerate the reduced baseline so this deletion does not leave the required ratchet failing.

Findings

  • [P2] Update the remaining consumer tests to the admission contract — src/gateway/provider-icon-http.ts:171-172
  • [P2] Prune the removed timeout reference from its baseline — config/test-timeout-race-baseline.txt:98

Tests

  • Missing end-to-end proof: Attach redacted runtime output showing an admitted HTTP request finishing after credential rotation, a subsequent old-credential request being refused, and disconnect cancellation remaining effective.
Agent review details

How this fits together

Gateway HTTP authentication admits callers and supplies scopes to route handlers, which perform operations and return responses under request cancellation and operation-specific data fences.

flowchart TD
  A[HTTP request] --> B[Credential and scope admission]
  B --> C[Gateway route handler]
  C --> D[Cancellation and data fences]
  D --> E[Operation owner]
  E --> F[HTTP response]
Loading

Technical review

Best possible solution:

Retain the existing admission and cancellation owners, finish migrating affected consumer tests, and regenerate the reduced timeout baseline.

Do we have a high-confidence way to reproduce the issue?

Base source shows the repeated snapshot checks, and exact-head CI demonstrates the changed responses; no target code was executed during this review.

Is this the best way to solve the issue?

Removing the redundant checks at their existing owner is a focused implementation of the approved contract; the documented retained callbacks serve downstream consumers outside this cutover.

Full review comments:

  • [P2] Update the remaining consumer tests to the admission contract — src/gateway/provider-icon-http.ts:171-172
    Removing revalidation changes the held provider-icon request to 200, permits embeddings after provider acquisition, and permits an admitted session-entry handoff to finish. The unchanged tests still require 401/403 in src/gateway/provider-icon-http.server.test.ts:96, src/gateway/embeddings-http.test.ts:595, and ui/src/e2e/post-deploy-session-entry.e2e.test.ts:519. All three fail in exact-head CI with those responses. Update these consumers alongside the production change, retaining next-request refusal, cancellation, cache, and session-data assertions rather than restoring the removed rechecks.
    Confidence: 1
  • [P2] Prune the removed timeout reference from its baseline — config/test-timeout-race-baseline.txt:98
    Deleting the Team Reports revocation cases removes that file's final withTestTimeout reference, but config/test-timeout-race-baseline.txt still records one reference. runPerFileCountRatchet explicitly returns failure for such stale entries, matching the timeout-race CI annotation. Regenerate the reduced baseline so this deletion does not leave the required ratchet failing.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 34ce936db81e.

Provenance checked

  • HTTP policy snapshots and route revalidation changes intended behavior with a stated reason (678cdf4: Apply live settings and prevent prepared HTTP responses or effects from using revoked policy.)
  • Settled HTTP authority outcomes changes intended behavior with a stated reason (76e32e9: Treat disconnects and settled authorization refusals as expected outcomes rather than unhandled server errors.)
  • Plugin route and remote-ingress runtime scopes changes intended behavior with a stated reason (2444aae: Bind trusted plugin requests to their authenticated principal and approved scopes.)
  • OpenResponses continuation persistence keeps the original intent (14f6562: Persist scoped continuation mappings across restarts and reject unresolved previous response identifiers.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 2444aae adds src/gateway/http-auth-plugin-cookie.ts:106 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2444aae8f8f9; files: src/gateway/http-auth-plugin-cookie.ts)
  • Josh Lehman: Raw commit 59b8a11 adds src/gateway/http-auth-utils.ts:199 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 59b8a114bf6d; files: src/gateway/http-auth-utils.ts)
  • Ayaan Zaidi: Raw commit 4dd1723 adds src/gateway/http-auth-utils.ts:261 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4dd1723ba02d; files: src/gateway/http-auth-utils.ts)

PR surface

Source -457, Tests -1549, Other -2. Total -2008 across 69 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 28 65 522 -457
Tests 40 220 1769 -1549
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 2 -2
Total 69 285 2293 -2008

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: The accepted HTTP behavior change needs focused consumer-test and ratchet repairs before its CI can pass.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The accepted HTTP behavior change needs focused consumer-test and ratchet repairs before its CI can pass.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 22, 2026, 1:56 PM ET / 18:56 UTC.

@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

One-admission E2E (one-admission-e2e/run.sh, isolated Gateway, real model) on head 1d9bc6d06222: pass.

  • R.running-turn-finishes: pass
  • Q.queued-input-refused-visibly: pass (accepted, 0 provider requests with the queued marker, visible refusal in the transcript)
  • S.stop-cancels: pass (abort ok, state aborted)

Evidence: verdict.json and results.jsonl in /tmp/one-admission-e2e.kmYKvP (elapsedMs 58697). The live Peanutto Gateway pid was the same before and after the run.

Plugin HTTP routes are outside this journey. They are covered through the real HTTP router by:

  • server.plugin-http-auth.test.ts › "finishes an admitted gateway-auth plugin request after its credential rotates": red on base (expected 401 to be 200), green on head.
  • server-http.authority-outcomes.test.ts › "cancels disconnected plugin reads without logging a handler failure": Stop / client abort still cancels a plugin route.

@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

One-admission E2E on the exact head 33a643a42c77 (test-only change from 1d9bc6d06222): pass. R.running-turn-finishes, Q.queued-input-refused-visibly and S.stop-cancels all pass. Evidence: verdict.json and results.jsonl in /tmp/one-admission-e2e.r6qH2Y. The live Peanutto Gateway pid was the same before and after the run. Local ClawSweeper review of this head: patch is correct, no findings.

@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the only red job on head 33a643a42c77 is checks-node-changed-compact-small-4. Its one failing test is test/scripts/ci-node-test-plan-hosted-tail.test.ts › "bounds hosted groups (full)" (expected 'runtime' to be undefined at line 159). This is MAIN-ALSO: the same test fails locally on an unmodified origin/main tip 34ce936db81e (ocx base merge-base --src), and this PR does not change the test or the CI planner. The PostgreSQL conformance jobs are still queued on the database runners; this PR changes no SQL or database code.

ci-triage:

# PR #203590 head 33a643a42c77; main run 45058055114

@obviyus
obviyus merged commit f1a6dbd into main Nov 22, 2026
151 of 154 checks passed
@obviyus
obviyus deleted the refactor/http-authority-check-once branch November 22, 2026 19:34
@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as f1a6dbd. HTTP routes now check authority once, at admission. An admitted request finishes, and revocation, rotation and policy changes apply to the next request. Request abort and data fences stay. Proof: a new plugin-route integration test (red on base, green on head), one-admission E2E Q/R/S pass on the exact head, local review clean. The only CI red is the MAIN-ALSO ci-node-test-plan-hosted-tail failure, overridden in the comment above.

obviyus added a commit that referenced this pull request Nov 23, 2026
…ttle-batch receipts (#203892)

## Problem

R2 of the one-admission receipt cluster. After #203760 (R1c), two receipt producers still returned a boolean, and the receipt boolean itself (`ReceiptAuthority = () => boolean | void`, the `composeReceiptAuthority` check loop, `assertAllowed` in `captureGatewayToolReceiptAssertion`) still hid permission re-checks from the lifetime-check ratchet:

- **MCP loopback grant receipt** (`mcp-http.ts`, `isGrantAndLineageCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the CLI grant row and the requester lineage.
- **Settle-batch receipt** (`agent-tools.caller.ts`, `settleBatch.isCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the subagent settle batch.

Both answer "may this requester still act?" in the middle of a call. R1c showed that turning them into throws is a new mid-request re-check (both ratchets went red), so they are deleted.

## Change

- **Deleted** the MCP grant receipt and the settle-batch receipt. The grant row and lineage are still checked once at each tool-call dispatch (`authorizeToolCall`); the settle batch is still checked at handoff admission (`subagent-announce-handoff.ts`). Stop still reaches the call through the grant's `abortSignal` and the run signal.
- **Deleted the receipt boolean:** the `ReceiptAuthority` type, the boolean check loop in `composeReceiptAuthority`, `captureGatewayToolReceiptAssertion` (and its lifetime-ratchet entry), and the `approvalAuthorityCheck` field (a duplicate of the receipt). `receiptAuthority` is now a plain `SessionSourceAssertion`: it throws or returns. `composeReceiptAuthority` only de-duplicates sources into `composeSessionSourceAssertion` and keeps its existing `assertScopeCurrent` forwarding.
- Readers that compared `receiptAuthority() === false` now call it and let it throw (or catch where the reader already returns `false`): before-tool-call decision receipt, cron tool, sessions access, terminal tool, session event target, node skill runtime, delegated approval, skill authoring, question broker, plugin hooks, cron management/owner bindings, harness host source and embedded tool authority.
- The "no delegated run" receipt `() => false` becomes a throw with the same message the boolean path already produced ("agent tool caller authority is no longer active").

Production: 17 files, +55/−173 (plus one session-identity allowlist entry pruned: `cron-tool.ts` lost its "no longer active" refusal string). No new export, name, hook, flag, guard, timer or state.

## Tests

- **Deleted (obsolete):** `mcp-http.test.ts` "fences caller authority when the grant is replaced during tool execution". It asserts that a started MCP tool call is refused at its commit after the grant row is replaced mid-call, i.e. the mid-call permission re-check this PR removes. Replacement is still refused at the next dispatch.
- About 60 test fixtures returned `false` from `receiptAuthority` to mean "run closed / revoked" (`() => validateAgentRunDelegatedAuthority(a)`, `() => current`, `() => !signal.aborted`, `() => false`). TypeScript accepts `() => boolean` as `() => void`, so these would silently stop refusing. Each now throws on the same condition (or uses `signal.throwIfAborted()`), so every refusal test keeps its meaning. Assertions on the boolean (`receiptAuthority()).toBe(false)`) became `toThrow`. The `hooks.before-tool-call.test.ts` "authority reports stale" row is gone (no boolean to report); both settlements now run with a throwing authority.
- `server.visible-spawn-fallback.product-proof.test.ts` no longer passes `currentGrant.isCurrent` as a receipt, matching production `mcp-http.ts`.
- Run-instance, claim, disconnect and stale-writer refusal tests keep their assertions. Two only changed the expected wording, because the refusal now comes from the run's own assertion instead of the deleted receipt wrapper: `session-event-handoff.test.ts` "rejects invocation retirement" (`no longer owns its invocation` → `no longer active`) and the retained-receipt check in `tool-authority.runtime.retention.test-support.ts` (`=== false` → throws).

## What users see

A tool call already running through a CLI (MCP loopback) or a subagent settle turn finishes when the grant or batch is replaced mid-call. The next call is refused before it starts, as before. Stop still cancels a running call. Error text for a closed run inside some tools (terminal, skill authoring, session events) now comes from the run's own assertion instead of the caller-specific wording.

## Evidence

- **Typecheck / lint / ratchets:** `pnpm tsgo:core`, `pnpm tsgo:test` clean on the head; oxfmt and oxlint clean on changed files; lifetime-check ratchet OK, session-identity ratchet OK (after prune).
- **Tests (pre-push):** importer set of every changed source and test-support file (816 files) with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`, run in lanes (the runner aborted once on a vitest resource-claim error after the gateway lanes, so the rest ran in a second call), then a focused rerun of every repaired file and a post-merge rerun after merging `main` for a ratchet-list conflict with #203847. Remaining reds, all not ours: red on the base locally (`dd56cf3d6457` / `49795c31df01`): `slack-download-read-authority` (claim at result), `github-pr-workspace-preparation`, `server.sessions.create.{durability,lifecycle,projects}`, `sessions-create-device-folder`, `provider-destroy-authority`, `service.pr-automation{,-feedback}`, `openclaw-tools.subagents.sessions-spawn.lifecycle`, `mcp-http.personal-authority`; known main reds from #203664/#203590/#203516: `server-cron-failure-repair.final-effect`, `cron.scheduled-policy-adoption`, `github-publication-imported-actions`, `question.communication`/`.recovery`, `mcp-http.async-scope`, `agent.test`, `plugin-reload-send-revocation.product`.
- **Local ClawSweeper review** on exact head `eb077c177329`: `review_status: complete`, "patch is correct", 0 findings.
- **One-admission E2E** (isolated Gateway, real model, exact head `eb077c177329`, `ocx build --dist`): `pass: true`. `results.jsonl` (28 rows) kept with the task proof. `verdict.json` checks:
  ```json
  [{"id":"R.running-turn-finishes","pass":true,"detail":{"state":"final","toolEnds":3,"toolEndsAfterRevoke":3}},{"id":"Q.queued-input-refused-visibly","pass":true,"detail":{"accepted":true,"providerRequestsWithQueuedMarker":0,"visibleRefusalInTranscript":true}},{"id":"S.stop-cancels","pass":true,"detail":{"abort":{"ok":true,"aborted":true},"state":"aborted","requestsWithStopMarker":1}}]
  ```

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…enclaw#203590)

## What problem this solves

HTTP routes checked the caller's authority when the request was admitted, then checked it again during the request. `captureHttpRequestAuthority` took a snapshot of auth policy, role policy, role revision, profile alias revision and shared auth generation. `bindHttpResponseAuthority` then made `assertCurrent()`, `revalidate()` and `hasCurrentClientAuthority()` compare against that snapshot, and against operator access and profile authority, at many points inside each route. Device-token routes re-verified the token in `revalidate()`. Plugin-cookie routes re-read the cookie grants and role policy. Because of this, an admitted request could stop halfway with 401/403 after an unrelated settings save or role edit.

The one-admission rule is: check authority once, when the request starts. A started request finishes. Revocation, removal and reload apply to the next request.

## What changed

- `src/gateway/http-request-authority.ts`: deleted `captureHttpRequestAuthority`, `bindHttpResponseAuthority`, `assertGatewayHttpRequestCurrent`, `GatewayHttpRequestAuthorityError` and the `GatewayHttp{Request,Response}Authority` types. `runGatewayHttpRequest` (request abort scope) and `finishGatewayHttpAuthorityError` stay.
- `http-auth-utils.ts`: HTTP auth results no longer carry `assertCurrent` or `revalidate`. The admission-time early refusals that compared against the snapshot are gone. The device-token `revalidate` overrides are gone.
- `http-auth-plugin-cookie.ts`: deleted `bindControlUiPluginCookieRequestAuthority` (the cookie/role re-check). `control-ui-plugin-assets.ts` authorizes the cookie one time.
- Route handlers no longer call those methods: Control UI bootstrap/avatar/session entry, channel/plugin/provider/workspace/project icons, managed media, user profile avatars and backgrounds, session kill, models, embeddings, OpenAI and OpenResponses, tools invoke, and plugin routes. `rememberResponseSession` lost its authority `assertCurrent` parameter (its only production caller passed the request guard).
- Removed both names from `LIFETIME_CHECK_CALLS`.

Kept:
- Request abort (Stop / client disconnect). The `runGatewayHttpRequest` scope signal and `finishGatewayHttpAuthorityError` still end the response. Response-ended checks (`res.writableEnded || res.destroyed`) stay where routes had them.
- Data fences: session lifecycle revision and avatar reference (channel avatars), session row generation (workspace icons), image replacement (`prepared.isCurrent()`), assistant media policy, managed-media grant and ingress-session reads, and session actor readability for session kill.

Production code: 29 files, +65 / −524.

## Decisions (recorded per the program rules)

- **Cut less at the WebSocket seam.** `AuthorizedGatewayHttpRequest.hasCurrentClientAuthority` stays as an optional field (profile + operator access only). The OpenAI, OpenResponses and tools-invoke routes pass it to the agent-turn and plugin-runtime scopes. There, *whether the field is present* changes behavior: `operator-run-authority` `isHttpOwner` needs `=== true`, and in-process approval dispatch checks presence. Removing it here would change owner attribution for OpenClaw ID HTTP callers. The session-mutation-guard and run-authority PRs remove it together with those readers. Plugin route scopes keep presence `requestAuth || operatorAccessAuthority || ingress`, so for gateway-auth routes the field is present whether the request came in by bearer or by cookie, as before.
- Not in scope, left for later PRs: `sessions-history-http` re-authenticates on each SSE publish through `checkGatewayHttpRequestAuth`. `tools-invoke-http` still adds `operatorAccessAuthority.signal` to the request signal. `operator-access-policy` aborts that signal on revocation (PR 7/8).

## Tests deleted (they assert a refusal after admission)

- `http-request-authority.test.ts` (role-policy fence on the snapshot)
- `http-auth-utils.openclaw-id-tunnel.test.ts` (device removed or role changed after admission → refusal)
- `channel-avatar-http`: "rejects revoked authority while channel avatar bytes are loading"
- `managed-image-attachments.authority`: revoked worker ownership read and revoked media authority after preparation
- `plugin-icon-http`: revoked authority during normalization or favicon fetch
- `workspace-icon-http`: changed authority during icon preparation (the workspace replacement case, a data fence, stays)
- `http-endpoint-helpers`: "does not admit a parsed body after its authority was revoked while reading"
- `http-utils.authorize-request`: trusted-proxy override revalidation
- `tools-invoke-http.abort`: "rejects a tool when policy authority changes during its awaited hook"
- `control-ui-assistant-media-metadata`: reader authority recheck variants
- `server-http.authority-outcomes`: nine client-expired / role / operator-revoked / unavailable variants. The disconnect and unexpected-error variants stay, and still prove Stop through the real HTTP router
- `openresponses-session-store` and the OpenResponses continuation support: revoked caller before commit / during the continuation lookup
- `control-ui-assistant-media-policy`, `control-ui-plugin-assets`, `control-ui-session-entry(.real-auth.e2e)`, `control-ui.response-authority`, `http-auth-utils.paired-device`, `http-session-control.incognito` (revoked=true rows), `server.plugin-http-role-scopes`, `server/plugins-http` (re-check before the next matched route), `session-kill-http` (policy-revocation and credential-rotation rows), `sessions-history-http.revocation` (ingress-policy row), `user-background-http.authority`, `user-profiles-http.auth` (credential rotation and device revocation during preparation), `team-reports-http.gateway` (expiry, generation and role change before delivery). Data-fence, admission-time and abort cases in those files stay.

## Evidence

- **Plugin HTTP route, through the real HTTP router (new test):** `server.plugin-http-auth.test.ts` › "finishes an admitted gateway-auth plugin request after its credential rotates". The plugin handler is blocked, the Gateway token rotates, then the handler calls the scope's `revalidate()`. The admitted request gets 200, and the next request with the old token gets 401. The same test copied onto base `c57ad28ba9b6` fails with `expected 401 to be 200`: base `revalidate()` re-checks the shared generation and refuses the admitted request. Stop through the real router: `server-http.authority-outcomes` › "cancels disconnected plugin reads without logging a handler failure". The one-admission E2E journey does not reach plugin HTTP routes, so this integration test is the plugin-route proof.
- **Pre-push tests (vitest-source):** one `ocx test` call over the 291 importer test files, with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`. It hit the 1 h tool deadline, so the 17 files it did not reach and every failed file ran again in two more calls. Everything passes except files that also fail on base `c57ad28ba9b6`: `cron/service.pr-automation` (13), `server-methods/question.own-run` (4), `server.config-security-policy` (3-4, timeouts), `server.sessions.create.projects` (1), and `operator-admission.table` › `token > principal > before-start`.
- `pnpm tsgo:core` and `pnpm tsgo:test` are clean. oxfmt and oxlint are clean on the changed files. The lifetime-check ratchet passes.
- E2E (`one-admission-e2e/run.sh`): Q, R and S pass on `1d9bc6d06222` and on the final head `33a643a42c77`. The live Gateway pid did not change.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…ttle-batch receipts (openclaw#203892)

## Problem

R2 of the one-admission receipt cluster. After openclaw#203760 (R1c), two receipt producers still returned a boolean, and the receipt boolean itself (`ReceiptAuthority = () => boolean | void`, the `composeReceiptAuthority` check loop, `assertAllowed` in `captureGatewayToolReceiptAssertion`) still hid permission re-checks from the lifetime-check ratchet:

- **MCP loopback grant receipt** (`mcp-http.ts`, `isGrantAndLineageCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the CLI grant row and the requester lineage.
- **Settle-batch receipt** (`agent-tools.caller.ts`, `settleBatch.isCurrent` as `receiptAuthority`): every effect inside a started tool call re-checked the subagent settle batch.

Both answer "may this requester still act?" in the middle of a call. R1c showed that turning them into throws is a new mid-request re-check (both ratchets went red), so they are deleted.

## Change

- **Deleted** the MCP grant receipt and the settle-batch receipt. The grant row and lineage are still checked once at each tool-call dispatch (`authorizeToolCall`); the settle batch is still checked at handoff admission (`subagent-announce-handoff.ts`). Stop still reaches the call through the grant's `abortSignal` and the run signal.
- **Deleted the receipt boolean:** the `ReceiptAuthority` type, the boolean check loop in `composeReceiptAuthority`, `captureGatewayToolReceiptAssertion` (and its lifetime-ratchet entry), and the `approvalAuthorityCheck` field (a duplicate of the receipt). `receiptAuthority` is now a plain `SessionSourceAssertion`: it throws or returns. `composeReceiptAuthority` only de-duplicates sources into `composeSessionSourceAssertion` and keeps its existing `assertScopeCurrent` forwarding.
- Readers that compared `receiptAuthority() === false` now call it and let it throw (or catch where the reader already returns `false`): before-tool-call decision receipt, cron tool, sessions access, terminal tool, session event target, node skill runtime, delegated approval, skill authoring, question broker, plugin hooks, cron management/owner bindings, harness host source and embedded tool authority.
- The "no delegated run" receipt `() => false` becomes a throw with the same message the boolean path already produced ("agent tool caller authority is no longer active").

Production: 17 files, +55/−173 (plus one session-identity allowlist entry pruned: `cron-tool.ts` lost its "no longer active" refusal string). No new export, name, hook, flag, guard, timer or state.

## Tests

- **Deleted (obsolete):** `mcp-http.test.ts` "fences caller authority when the grant is replaced during tool execution". It asserts that a started MCP tool call is refused at its commit after the grant row is replaced mid-call, i.e. the mid-call permission re-check this PR removes. Replacement is still refused at the next dispatch.
- About 60 test fixtures returned `false` from `receiptAuthority` to mean "run closed / revoked" (`() => validateAgentRunDelegatedAuthority(a)`, `() => current`, `() => !signal.aborted`, `() => false`). TypeScript accepts `() => boolean` as `() => void`, so these would silently stop refusing. Each now throws on the same condition (or uses `signal.throwIfAborted()`), so every refusal test keeps its meaning. Assertions on the boolean (`receiptAuthority()).toBe(false)`) became `toThrow`. The `hooks.before-tool-call.test.ts` "authority reports stale" row is gone (no boolean to report); both settlements now run with a throwing authority.
- `server.visible-spawn-fallback.product-proof.test.ts` no longer passes `currentGrant.isCurrent` as a receipt, matching production `mcp-http.ts`.
- Run-instance, claim, disconnect and stale-writer refusal tests keep their assertions. Two only changed the expected wording, because the refusal now comes from the run's own assertion instead of the deleted receipt wrapper: `session-event-handoff.test.ts` "rejects invocation retirement" (`no longer owns its invocation` → `no longer active`) and the retained-receipt check in `tool-authority.runtime.retention.test-support.ts` (`=== false` → throws).

## What users see

A tool call already running through a CLI (MCP loopback) or a subagent settle turn finishes when the grant or batch is replaced mid-call. The next call is refused before it starts, as before. Stop still cancels a running call. Error text for a closed run inside some tools (terminal, skill authoring, session events) now comes from the run's own assertion instead of the caller-specific wording.

## Evidence

- **Typecheck / lint / ratchets:** `pnpm tsgo:core`, `pnpm tsgo:test` clean on the head; oxfmt and oxlint clean on changed files; lifetime-check ratchet OK, session-identity ratchet OK (after prune).
- **Tests (pre-push):** importer set of every changed source and test-support file (816 files) with `OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1`, run in lanes (the runner aborted once on a vitest resource-claim error after the gateway lanes, so the rest ran in a second call), then a focused rerun of every repaired file and a post-merge rerun after merging `main` for a ratchet-list conflict with openclaw#203847. Remaining reds, all not ours: red on the base locally (`d6b84a4c90a1` / `2f6261e2a4ec`): `slack-download-read-authority` (claim at result), `github-pr-workspace-preparation`, `server.sessions.create.{durability,lifecycle,projects}`, `sessions-create-device-folder`, `provider-destroy-authority`, `service.pr-automation{,-feedback}`, `openclaw-tools.subagents.sessions-spawn.lifecycle`, `mcp-http.personal-authority`; known main reds from openclaw#203664/openclaw#203590/openclaw#203516: `server-cron-failure-repair.final-effect`, `cron.scheduled-policy-adoption`, `github-publication-imported-actions`, `question.communication`/`.recovery`, `mcp-http.async-scope`, `agent.test`, `plugin-reload-send-revocation.product`.
- **Local ClawSweeper review** on exact head `eb077c177329`: `review_status: complete`, "patch is correct", 0 findings.
- **One-admission E2E** (isolated Gateway, real model, exact head `eb077c177329`, `ocx build --dist`): `pass: true`. `results.jsonl` (28 rows) kept with the task proof. `verdict.json` checks:
  ```json
  [{"id":"R.running-turn-finishes","pass":true,"detail":{"state":"final","toolEnds":3,"toolEndsAfterRevoke":3}},{"id":"Q.queued-input-refused-visibly","pass":true,"detail":{"accepted":true,"providerRequestsWithQueuedMarker":0,"visibleRefusalInTranscript":true}},{"id":"S.stop-cancels","pass":true,"detail":{"abort":{"ok":true,"aborted":true},"state":"aborted","requestsWithStopMarker":1}}]
  ```

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant