Skip to content

refactor(gateway): trust admitted client scope arrays - #182897

Merged
steipete merged 2 commits into
mainfrom
dbasync/dprevalidate-gw
Oct 24, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/dprevalidate-gw

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway connections validate optional string-array scopes at admission. Downstream handlers repeatedly call Array.isArray on the retained, typed value. Remove 20 of these repeated shape checks across 14 Gateway files (22 additions, 34 deletions; net -12 production lines).

User Impact

No user-visible authorization change. Gateway handlers do less repeated validation after admitting a connection.

Why This Change Was Made

The WebSocket ConnectParams schema and admission validators remain the boundary owners. In-process constructors accept or produce typed arrays. Scope membership, revocation, per-effect authorization, nullable clients, and the original pre-/post-await capture positions are preserved. No SQL, schema, database identity, SDK surface, provider request, or configuration changes.

Retained checks include untrusted token-scope normalization, unknown-valued approval-client scopes, agent-tool input decoding, and WebSocket admission. Arbitrary JavaScript violating an internal TypeScript constructor contract is not a supported input boundary; existing array operations already rely on that contract.

Acceptance rule (registered before measurement)

Use frozen SQL harness v3.1.4 with synthetic state and real loopback Gateway transport. One baseline/candidate pair with matching default options; analyze ten warm turns separately from cold/startup/restart phases. Require successful turns, spawn, cron, control RPCs, compaction, restart, and shutdown. Compare statement, worker-request, and MAIN counts, including per-operation execution-window counts; no increase caused by changed scope consumers. Report warm median, nearest-rank p95, and min–max, plus raw phase changes. Any 20% adverse metric is a stop pending disposition. No latency or CPU speed claim is made. Counts-only runs do not use the timing lock.

The frozen v3.1.4 causal hook predates the shared AsyncContext migration: causal phases are empty and requests classify as background on current main. The comparison therefore uses native warm execution windows, not causal turn counts; the frozen harness is unchanged. This limitation is recorded before the first run.

The simplification gain is 20 removed runtime array-shape checks, with no new validation owner, state, cache, copying, or fallback.

Preserved authorization checks

Removed shape check Preserved permission or effect check
operator-scopes; operator-approval-authorization (three sites) Admin/approval scope membership and device/connection binding in the same functions
approval-record-lookup Admin/approval membership, requester identity, visibility filter, revocation and effect-time authority
health (two sites) Admin membership at its existing capture point
server-broadcast-scopes; server-request-context Event scope policy, invalidation and approval-delivery membership
session-catalog-visibility; client-human-presence Operator scope policy and authenticated UI identity
environments (three sites) Admin policy before projection, with current scopes re-read at the same post-await sites
sessions-mutations (two sites); sessions-patch-engine Permission-mode/admin authorization and the existing internal null-client contract
device-scope-upgrade; nodes.pairing Role-scope policy and pending-pairing ownership enforcement
talk handlers Admin or talk-secrets scope membership before secret disclosure

Admission regression

The existing ConnectParamsSchema (packages/gateway-protocol/src/schema/frames.ts:61) owns scope shape. WebSocket admission applies validateConnectParams at src/gateway/server/ws-connection/message-handler.ts:286. The suspension-admission suite now sends actual connect frames with both "operator.admin" and "xoperator.adminx" as string-valued scopes, and requires INVALID_REQUEST, socket close, and no admitted client. Downstream includes can therefore only receive an admitted array.

Evidence

All 16 focused owner test files pass (416 tests), including both malformed string-scope connect frames, final scope-revocation checks, and the repaired session-status path. Exact-head CI 40133681144 passes production/test types, core/extension lint, source contracts, architecture/Madge, T1/dialect/worker ratchets, selected test shards, and all three PostgreSQL conformance shards. Metadata 40134106199 passes after correcting template headings; earlier failed metadata runs are superseded.

Local check:changed --base 11c9161b4a1e5e00e3a5145c04d5ae4756d61958 passes type-aware changed-file core oxlint, oxfmt, architecture/Madge (zero cycles), owner guards, and ratchets. Its three typecheck steps stop at the containment guard because the campaign mandates an internal-disk virtual store outside this external-disk worktree. No guard bypass was used; exact-head CI supplies completed type proof. The completed production, full-tree, and script export scans report the same 1,230 unique findings on exact base and candidate: zero new or resolved findings, none in changed files. Both scans exit nonzero for this identical pre-existing export debt; the comparison proves this patch adds none. The frozen baseline/candidate pair completed successfully; counts and threshold investigation are below.

The first CI run caught a removed callerScopes local still consumed by session-patch publication; the repair restores the original pre-await capture while removing only its redundant shape test. Independent constructor/writer audit covers all selected paths. Simplification found no new owner, wrapper, state, or test machinery. Codex P0–P2 autoreview: scoped-clean (two rounds), covering the diff and unchanged boundary/constructor context. Frozen harness hashes: 36/36 verified.

Frozen count comparison

One alternating baseline/candidate pair; each run includes ten warm native execution windows. All turns, spawn, control RPCs, cron, compaction, restart and shutdown contracts passed. No latency or CPU claim. Both builds match their recorded full SHAs.

python3 "$HARNESS/measure.py" --repo "$PWD" --out "$PROOF/baseline" --sha 11c9161b4a1e5e00e3a5145c04d5ae4756d61958 --repetitions 1
python3 "$HARNESS/measure.py" --repo "$PWD" --out "$PROOF/candidate" --sha cbbc441ffad3a17d2ce1f5028b0dd1d54cbc8557 --repetitions 1
Count Baseline Candidate
Warm sql: median / p95 [min–max] 51 / 68 [50–68] 50.5 / 70 [50–70]
Warm sql: sum 545 547
Whole workload sql 3006 3006
Warm requests: median / p95 [min–max] 12 / 20 [12–20] 12 / 19 [12–19]
Warm requests: sum 135 135
Whole workload requests 803 799
Warm main: median / p95 [min–max] 0 / 0 [0–0] 0 / 0 [0–0]
Warm main: sum 0 0
Whole workload main 95 95
Native execution window Baseline SQL / requests / MAIN Candidate SQL / requests / MAIN
00.fixture 0 / 0 / 0 0 / 0 / 0
01.boot 307 / 100 / 49 308 / 100 / 49
01.connect 233 / 22 / 0 27 / 9 / 0
02.first-turn 252 / 81 / 0 456 / 94 / 0
03.turn-01 56 / 14 / 0 59 / 15 / 0
03.turn-02 68 / 20 / 0 65 / 19 / 0
03.turn-03 68 / 17 / 0 50 / 12 / 0
03.turn-04 50 / 12 / 0 70 / 17 / 0
03.turn-05 51 / 12 / 0 51 / 12 / 0
03.turn-06 50 / 12 / 0 50 / 12 / 0
03.turn-07 50 / 12 / 0 50 / 12 / 0
03.turn-08 51 / 12 / 0 50 / 12 / 0
03.turn-09 50 / 12 / 0 50 / 12 / 0
03.turn-10 51 / 12 / 0 52 / 12 / 0
04.second-session 507 / 120 / 0 504 / 120 / 0
05.control-plane 7 / 1 / 0 8 / 1 / 0
06.cron 241 / 66 / 0 235 / 63 / 0
07.compaction 126 / 28 / 0 109 / 20 / 0
07.idle-settle 143 / 21 / 0 163 / 29 / 0
07.idle-connected 87 / 30 / 0 87 / 30 / 0
08.shutdown 22 / 7 / 5 22 / 6 / 5
09.restart-boot 329 / 121 / 36 334 / 121 / 36
09.restart-connect 40 / 17 / 0 21 / 10 / 0
10.restart-first-turn 144 / 48 / 0 159 / 53 / 0
11.restart-shutdown 23 / 6 / 5 26 / 8 / 5
done 0 / 0 / 0 0 / 0 / 0
Changed warm operation SQL delta Request delta MAIN delta
NO_REQUEST / AsyncWorkScope.enter -2 +0 +0
commitSessionEntryPatch +4 +1 +0
readPluginModelCatalogEntries +1 +0 +0
sessionUpstream.listWatched -1 -1 +0

Every other warm operation is unchanged, including the transcript prepare/persist batches, pending-input reads, cache-write tracking, metadata refresh (9 SQL / 1 request), and UNKNOWN (19 / 9). No new whole-workload operation names.

20% stop investigation and disposition (2026-10-24): the first-turn, warm-04, idle-settle and restart-shutdown raw windows crossed the threshold. The maintainer accepted these as execution-phase placement under the existing attribution rule after reviewing compensating adjacent windows, unchanged total SQL/MAIN, and the absence of new operation names. This is an explicit disposition, not a latency or SQL-saving claim. Worker open (181 SQL) moved from connect to first turn; connect + first-turn totals are 485/103/0 → 483/103/0. Metadata refresh and associated native work moved from warm-03 to warm-04; their combined counts are 118/29/0 → 120/29/0. Post-compaction model-context/transcript/read bookkeeping moved into idle-settle; compaction + settle are 269/49/0 → 272/49/0. Restart shutdown includes one pending patch commit and one upstream-watch poll; whole patch-commit request count remains 39. These are execution-window observations, not causal turn attribution. The patch changes no SQL, scheduling, worker routing, caching or await positions.

Open-PR compatibility

The complete shared open-PR index (2,677 PRs, refreshed 2026-10-24 22:49 UTC) finds 31 other PRs overlapping this patch. All overlapping heads are unchanged from the completed comparison. For each pinned head below, git merge-tree on base 11c9161b4a1 and candidate cbbc441ffad adds zero conflict paths or hunks. 25 already conflict with the base. The excluded plugin-host-hooks edit is absent from this PR.

PR Compared head New conflicts
#182742 1ec16f56b90b 0
#182625 37a8c13f41d0 0
#181390 78147279767a 0
#179959 a7d517ce8456 0
#179661 a636ce0d18d7 0
#177257 aa973a461027 0
#177207 e692a2097a42 0
#170160 ee6003da2db0 0
#165481 7e285f117b8c 0
#163964 d5a65a503ac6 0
#162160 588af7c58287 0
#162144 5ccbb4ccb1cd 0
#162132 c978efa59f1c 0
#162126 e48a73e79cb2 0
#161344 c243b9d29741 0
#161030 8b9bcd58c2a9 0
#160364 0a3c2ac0a504 0
#155419 51e8c1ae26a5 0
#152205 24ff19f9bda8 0
#151441 e6ac94f213a2 0
#150588 c37c07949dcd 0
#150246 4a94ab9dd156 0
#149251 56f143c054b2 0
#148770 75e2bbe54f53 0
#148581 bb721c82a7d0 0
#145067 e2c0e8ad86ec 0
#144766 67152d15a35e 0
#141239 9c0f28f7eabd 0
#135610 f4fcc3f53dbb 0
#89526 74a5bb304832 0
#65205 89b897744353 0

Release-note context: internal Gateway scope handling simplification; user-visible authorization behavior is unchanged.

Remove repeated array-shape checks after connection admission while preserving scope membership, revocation, and existing capture timing.
@clawsweeper

clawsweeper Bot commented Oct 24, 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.

@steipete
steipete marked this pull request as ready for review October 24, 2026 21:13
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 24, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T21:22:36.138368Z cbbc441 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 24, 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: cbbc441ffad3a17d2ce1f5028b0dd1d54cbc8557
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/operator-approval-authorization.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/operator-scopes.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/device-scope-upgrade.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods/nodes.pairing.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR removes repeated array-shape checks from typed Gateway scope consumers and adds malformed-scope admission coverage.

Example: A WebSocket client sends scopes as "xoperator.adminx" instead of an array.

  • Before: Connection admission rejects the request with INVALID_REQUEST.
  • After: Admission still rejects it before downstream scope consumers run.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is small, coherent, and supported by current-head checks; confidence in runtime behavior rests on source and admission-harness coverage rather than supplied end-to-end evidence.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal refactor is outside the ordinary contributor proof gate and does not materially change the authority chain; current-head CI supports validation, while inspected related-item screenshots do not demonstrate this change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
Reason: Maintainer direction is established, and the narrow reduction follows the repository's validate-once ownership rule without changing supported behavior.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: the maintainer-directed simplification preserves admission validation, permission checks, and scope-capture timing, with no actionable introduced bug found.

Priority: P3
Reviewed head: cbbc441ffad3a17d2ce1f5028b0dd1d54cbc8557

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No shipped-entry-point baseline/candidate result is supplied for this refactor; the added tests exercise the unchanged admission boundary.
Agent review details

How this fits together

Gateway admission validates incoming connection parameters and retains authenticated client scopes; handlers and event delivery consume those scopes to authorize operations and disclosure.

flowchart LR
  A[Connection frame] --> B[Protocol validation]
  B --> C[Authentication and scope ceilings]
  C --> D[Admitted client]
  E[Typed internal constructors] --> D
  D --> F[Permission and live authority checks]
  F --> G[RPC effects and event delivery]
Loading

Technical review

Best possible solution:

Keep scope-shape validation at admission and let typed consumers perform their existing permission and live-authority checks.

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

No broken user behavior is claimed; source inspection confirms repeated checks on scopes already constrained by admission or typed constructors, and no target code was executed during this review.

Is this the best way to solve the issue?

The direct substitutions are the smallest complete simplification: they retain the existing validation owner, nullable-client behavior, authorization predicates, and capture timing without introducing another abstraction.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 61deaaef5879.

Provenance checked

  • Admin and approval scope predicates keeps the original intent (refactor(gateway): deslop gateway request and runtime flows #162874: Shared scope predicates reduce duplicated Gateway policy; durable approval authorization separately preserves reviewer-device and trusted-runtime binding.)
  • Prepared-worker detail disclosure and human presence keeps the original intent (feat: show live cloud worker pool in settings #157200: Prepared details require current administrator scope after discovery; authenticated session-creating UI presence controls preparation demand.)
  • Approval lookup and event delivery keeps the original intent (fix: keep approval requests on the owning channel account #121673: Approval visibility and settlement retain owning-account, requester, and current-authority restrictions; event scope membership remains separate from delivery capability.)
  • Session mutations and catalog visibility keeps the original intent (fix(sessions): hide unowned host catalogs on multi-user gateways #123421: Multi-user catalogs hide unowned sessions; mutation consumers retain their existing admin checks, trusted-null contract, and captured caller scopes.)
  • Health disclosure keeps the original intent (fac040c: Sensitive status details are restricted to administrator scopes; this PR preserves the original membership decision and capture point.)
  • Device upgrades and node pairing keeps the original intent (refactor: share device and node RPC validation preambles #177240: Validation consolidation preserves live authority, scope-upgrade identity binding, and pairing ownership; these checks remain in place.)
  • Talk secret access keeps the original intent (4c86821: The original Talk change allows paired clients to retrieve secrets only through administrator or Talk-secret scope membership; history was followed across the talk.ts move.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 02dc25a adds src/gateway/operator-approval-authorization.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 02dc25a1b51f; files: src/gateway/operator-approval-authorization.ts)
  • Vincent Koc: Raw commit 7ff0e11 adds src/gateway/server-methods/talk.ts:44 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 7ff0e11c1f95; files: src/gateway/server-methods/talk.ts)

PR surface

Source -12, Tests +19. Total +7 across 15 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 14 21 33 -12
Tests 1 20 1 +19
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 41 34 +7

Review metrics

Metric Value Why it matters
Production versus test LOC Production +21/-33; tests +20/-1 Production shrinks without adding machinery; the test growth exercises malformed input at the existing admission owner.

Labels

Label changes:

  • add P3: This is an internal simplification with no claimed user-visible defect or authorization change.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P3: This is an internal simplification with no claimed user-visible defect or authorization change.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 October 24, 2026, 5:41 PM ET / 21:41 UTC.

@steipete
steipete merged commit 219e918 into main Oct 24, 2026
176 of 178 checks passed
@steipete
steipete deleted the dbasync/dprevalidate-gw branch October 24, 2026 22:58
steipete added a commit that referenced this pull request Oct 25, 2026
Populate missing connect.scopes in the shared catalog RPC fixture after
#182897 made downstream handlers trust admitted connection metadata.
Preserve client identity, supplied scopes, and live scope mutations.

The progress suite reproduces 15 failures on main and passes all 17 cases
with the fixture repair. Five sibling files yield 38 passes and one
unchanged base failure expecting CATALOG_LOADING instead of pending.
Focused lint, format, Gateway-methods test types, and Codex review pass.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
Remove 20 redundant array-shape checks from downstream Gateway consumers of admitted connection scopes. Keep WebSocket admission validation, permission membership, revocation, effect-time authority and scope-capture ordering with their existing owners.

Add actual handshake regression coverage rejecting string-valued scopes before admission. All 416 focused owner tests and exact-head CI pass. Synthetic Gateway workload retains 3,006 SQL statements and 95 MAIN statements; no SQL or latency improvement is claimed.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
Populate missing connect.scopes in the shared catalog RPC fixture after
openclaw#182897 made downstream handlers trust admitted connection metadata.
Preserve client identity, supplied scopes, and live scope mutations.

The progress suite reproduces 15 failures on main and passes all 17 cases
with the fixture repair. Five sibling files yield 38 passes and one
unchanged base failure expecting CATALOG_LOADING instead of pending.
Focused lint, format, Gateway-methods test types, and Codex review pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant