Skip to content

fix(gateway): clients can identify authorization failures - #110925

Merged
steipete merged 6 commits into
mainfrom
codex/gateway-structured-auth-errors
Jul 18, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/gateway-structured-auth-errors

Conversation

@steipete

@steipete steipete commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor
Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Fixes an issue where gateway clients received only free-form strings for method-level authorization failures, forcing third-party clients to parse messages to identify missing scopes. PinchChat added exactly such a parser in commit 3d5a897 to provide actionable guidance.

Why This Change Was Made

Method-level authorization failures now use the semantic FORBIDDEN code and additive MISSING_SCOPE details containing the missing scope and complete known required scope set. The legacy missing scope: <scope> message remains unchanged for compatibility. HTTP 403 scope responses mirror the structured details when a concrete scope is available and preserve the prior fallback otherwise. Node-pairing approval failures report both pairing and additional admin requirements when applicable.

While this PR was in flight, main moved webchat session mutations onto the ordinary operator-scope policy. The obsolete client-mode-specific rejection and proposed discriminator were therefore dropped; webchat mutation failures now receive the same MISSING_SCOPE contract as other RPCs. Protocol schemas, generated Swift bindings, SDK exports, and docs expose the new additive contract. No protocol version bump is needed.

User Impact

Gateway clients can show reliable, actionable authorization guidance without regex-parsing human-readable messages. Older clients continue to receive the legacy missing-scope text.

Release-note context: gateway authorization failures now include structured missing-scope details for third-party clients.

Evidence

  • Source-blind built-gateway WebSocket proof observed FORBIDDEN with the unchanged message and exact MISSING_SCOPE, missingScope, and requiredScopes fields.
  • 188 focused gateway, protocol, and plugin-contract tests passed on the exact rebased head, including HTTP compatibility, node-pairing scope sets, plugin actions, and webchat session mutations.
  • Remote protocol generators produced byte-identical JSON, Swift, and Kotlin artifacts; the plugin SDK API baseline check passed.
  • Full production build and pnpm check:changed passed on Blacksmith Testbox.
  • Exact-head hosted CI run 29660238863 passed, including openclaw/ci-gate.
  • Fresh whole-branch autoreview reported no accepted or actionable findings.

@steipete
steipete requested a review from a team as a code owner July 18, 2026 19:28
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Jul 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d8158ea43a

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/gateway/protocol.md Outdated
Comment on lines +35 to +37
and can change except where a compatibility note says otherwise. Method-level
authorization failures use top-level `code: "FORBIDDEN"` with one of these
structured detail shapes:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Convert remaining method-level scope denials to FORBIDDEN

When a caller passes the method's base scope but fails a secondary authorization check, this documented contract is still false: talk.config with includeSecrets returns INVALID_REQUEST without details at src/gateway/server-methods/talk.ts:725-731, and admin-only node.invoke commands do the same at src/gateway/server-methods/nodes.ts:1450-1458 (the embedded agent reset check at src/gateway/server-methods/agent-reset-phase.ts:76-81 is another instance). Clients therefore still need message parsing for several method-level missing-scope failures; route these checks through missingScopeErrorShape as well.

Useful? React with 👍 / 👎.

Comment on lines +1024 to +1027
missingScopeErrorShape({
missingScope: approved.missingScope,
requiredScopes: [approved.missingScope],
}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return the full pairing scope set

For a node request declaring commands such as system.run, resolveNodePairApprovalScopes requires both operator.pairing and operator.admin, but this response reports only whichever scope failed first. A caller missing both is told that requiredScopes is only operator.pairing, then encounters a second denial after granting it, contradicting the new contract that this field contains the complete known set. Preserve and return the full approval scope list from approveNodePairing instead of constructing it from missingScope.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4671a42b01

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const resolvedRequiredScopes = isOperatorScope(registeredScope)
? [registeredScope]
: resolveLeastPrivilegeOperatorScopesForMethod(method, params);
return missingScopeErrorShape({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the node diagnostics authentication fallback

When a locally stored device token's recorded scopes pass the CLI preflight but the gateway's current pairing has since been narrowed or revoked, node.list and node.describe now throw GatewayClientRequestError with gatewayCode: "FORBIDDEN" and detail code MISSING_SCOPE. The fallback predicate in src/cli/nodes-cli/rpc.ts:47-65 recognizes only the legacy INVALID_REQUEST response or connect-auth detail codes, so callNodeDiagnosticsGatewayCli rethrows instead of trying local shared auth and ordinary credentials. Update that predicate to recognize the new structured missing-scope response.

Useful? React with 👍 / 👎.

requiredScopes: readonly string[];
}): ErrorShape {
const details = buildMissingScopeErrorDetails(params);
return errorShape(ErrorCodes.FORBIDDEN, `missing scope: ${params.missingScope}`, { details });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Map FORBIDDEN admin RPC responses to HTTP 403

When a trusted-proxy caller supplies a narrowed x-openclaw-scopes header and invokes an allowlisted Admin HTTP RPC method requiring a scope it lacks, this new error reaches extensions/admin-http-rpc/src/handler.ts:45-66, whose status switch has no FORBIDDEN case and therefore returns HTTP 500. This misclassifies a caller authorization failure as a server fault and can trigger incorrect retries or alerts; add the new code to that adapter's error-code set and map it to 403.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/gateway-structured-auth-errors branch from 4671a42 to 908d91b Compare July 18, 2026 20:34
@clawsweeper clawsweeper Bot added the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label Jul 18, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 908d91b1a4

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const resolvedRequiredScopes = isOperatorScope(registeredScope)
? [registeredScope]
: resolveLeastPrivilegeOperatorScopesForMethod(method, params);
return missingScopeErrorShape({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle FORBIDDEN in the question-list unavailable path

When a Swift chat client reconnects after operator.questions has been removed, question.list now returns FORBIDDEN, but questionListIsUnavailable only recognizes INVALID_REQUEST at apps/shared/OpenClawKit/Sources/OpenClawChatUI/ChatQuestionCard.swift:397-400. The error therefore falls into the best-effort catch instead of the branch that clears existing question cards, leaving stale actionable cards visible until local expiry; update that client predicate to recognize the new structured missing-scope response.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 18, 2026, 4:44 PM ET / 20:44 UTC.

Summary
The PR adds a FORBIDDEN gateway error code plus structured missing-scope details across protocol schemas, gateway WebSocket/HTTP responses, docs, tests, and Swift protocol models.

PR surface: Source +92, Tests +106, Docs +15, Generated 0, Other +23. Total +236 across 18 files.

Reproducibility: yes. from source with medium confidence: invoke a gateway method through the affected CLI, Admin HTTP RPC, Swift question-list, or remaining scope-denial paths after it returns the new FORBIDDEN code; the supplied review reports identify the concrete predicates and call sites.

Review metrics: 1 noteworthy metric.

  • Gateway error surface: 1 top-level error code added; 1 exported structured detail schema added. Existing clients have code-based authorization handling, so this additive protocol surface still requires downstream compatibility verification.

Stored data model
Persistent data-model change detected: serialized state: src/plugins/contracts/session-actions.contract.test.ts, unknown-data-model-change: packages/gateway-protocol/src/schema/error-codes.ts, vector/embedding metadata: packages/gateway-protocol/src/schema/error-codes.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🦪 silver shellfish
Result: blocked until stronger real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Update the remaining gateway emitters and downstream INVALID_REQUEST consumers.
  • [P2] Add focused regressions for CLI fallback, Admin HTTP 403 mapping, and Swift question-card cleanup.
  • [P1] Attach redacted after-fix live output or a terminal recording; after updating the PR body, request @clawsweeper re-review if a fresh review does not start automatically.

Proof guidance:

  • [P1] Needs stronger real behavior proof before merge: The PR body reports a built-gateway WebSocket run, but the supplied context contains no inspectable after-fix terminal output, log, screenshot, recording, or linked artifact; add redacted live proof covering the changed structured response and affected recovery behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Changing authorization failures from INVALID_REQUEST to FORBIDDEN bypasses existing compatibility predicates in the node diagnostics CLI and Swift question-card recovery path.
  • [P1] The Admin HTTP RPC adapter can translate the new authorization error into HTTP 500 instead of 403 for narrowed trusted-proxy scopes.
  • [P1] Several method-level scope checks remain on the old unstructured error shape, leaving clients to parse messages despite the documented contract.
  • [P1] The PR body describes live proof, but no inspectable after-fix transcript, terminal output, recording, or artifact is present in the supplied review context.

Maintainer options:

  1. Complete the authorization-error migration (recommended)
    Update the remaining emitters and legacy-code consumers, then prove both structured gateway responses and the affected fallback/recovery paths.
  2. Limit the new code to opt-in consumers
    Retain existing INVALID_REQUEST behavior until all supported adapters can consume FORBIDDEN, if maintainers prefer a staged protocol transition.

Next step before merge

  • [P1] The remaining blockers are concrete, mechanical compatibility repairs across known gateway clients and emitters; the protected maintainer label keeps the final merge decision with humans.

Security
Cleared: The diff changes authorization error classification and protocol data only; no new dependency, workflow, secret, permission, or artifact-execution path is introduced.

Review findings

  • [P2] Preserve node diagnostics fallback for structured denials — src/gateway/server-methods.ts:327-333
  • [P2] Map structured authorization failures to HTTP 403 — packages/gateway-protocol/src/schema/error-codes.ts:18
  • [P2] Keep Swift question recovery aligned with FORBIDDEN — apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift:29
Review details

Best possible solution:

Make one canonical structured authorization-error path, migrate every gateway denial and downstream legacy-code consumer to it, and add focused regression coverage for WebSocket, HTTP, CLI fallback, Admin HTTP RPC, and Swift recovery behavior.

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

Yes, from source with medium confidence: invoke a gateway method through the affected CLI, Admin HTTP RPC, Swift question-list, or remaining scope-denial paths after it returns the new FORBIDDEN code; the supplied review reports identify the concrete predicates and call sites.

Is this the best way to solve the issue?

No, not yet. The structured protocol shape is a maintainable solution, but it must be applied consistently to all method-level authorization denials and existing consumers before it replaces the legacy error code.

Full review comments:

  • [P2] Preserve node diagnostics fallback for structured denials — src/gateway/server-methods.ts:327-333
    node.list and node.describe can now reject with FORBIDDEN plus MISSING_SCOPE, but the diagnostics fallback still recognizes the legacy INVALID_REQUEST code. A narrowed or revoked stored-token scope will now rethrow instead of trying its existing local-auth fallback; update the predicate and add its regression case.
    Confidence: 0.9
  • [P2] Map structured authorization failures to HTTP 403 — packages/gateway-protocol/src/schema/error-codes.ts:18
    The Admin HTTP RPC adapter's status mapping does not handle the newly emitted FORBIDDEN code. A trusted-proxy request with narrowed scopes will be reported as HTTP 500 rather than a caller authorization failure; add the 403 mapping and cover it.
    Confidence: 0.9
  • [P2] Keep Swift question recovery aligned with FORBIDDEN — apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift:29
    The Swift question-list unavailable predicate recognizes the legacy INVALID_REQUEST response only. When question.list loses its required scope, the client will retain stale actionable question cards instead of clearing them; accept the structured missing-scope denial there as well.
    Confidence: 0.86
  • [P2] Convert the remaining method-level scope denials — src/gateway/server-methods.ts:327-333
    This change documents FORBIDDEN as the method-level authorization contract, but secondary checks in talk.config, admin-only node.invoke, and the embedded-agent reset path still return the legacy unstructured INVALID_REQUEST response. Route those checks through the same helper so clients do not need message parsing on those methods.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.87

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 42bacaa112c5.

Label changes

Label changes:

  • add P2: The change improves a normal gateway/client authorization workflow, but remaining adapters can mis-handle authorization denials rather than causing a system-wide outage.
  • add merge-risk: 🚨 compatibility: Existing CLI, HTTP, and Swift code paths branch on the legacy authorization error code and need migration to preserve their current recovery behavior.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body reports a built-gateway WebSocket run, but the supplied context contains no inspectable after-fix terminal output, log, screenshot, recording, or linked artifact; add redacted live proof covering the changed structured response and affected recovery behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.

Label justifications:

  • P2: The change improves a normal gateway/client authorization workflow, but remaining adapters can mis-handle authorization denials rather than causing a system-wide outage.
  • merge-risk: 🚨 compatibility: Existing CLI, HTTP, and Swift code paths branch on the legacy authorization error code and need migration to preserve their current recovery behavior.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body reports a built-gateway WebSocket run, but the supplied context contains no inspectable after-fix terminal output, log, screenshot, recording, or linked artifact; add redacted live proof covering the changed structured response and affected recovery behavior. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +92, Tests +106, Docs +15, Generated 0, Other +23. Total +236 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 7 104 12 +92
Tests 8 119 13 +106
Docs 1 15 0 +15
Config 0 0 0 0
Generated 1 1 1 0
Other 1 23 0 +23
Total 18 262 26 +236

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs packages/gateway-protocol/src/schema/error-codes.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server-methods.authorization.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server.node-pairing-authz.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server.sessions.permissions-hooks.test.ts.
  • [P1] Run focused tests added for src/cli/nodes-cli/rpc.ts and extensions/admin-http-rpc/src/handler.ts, plus the repository-supported Swift/OpenClawKit test lane for ChatQuestionCard.swift.

What I checked:

Likely related people:

  • steipete: Authored all six commits in this PR, including the gateway protocol, server authorization, and generated binding changes that establish the new contract. (role: recent gateway protocol contributor; confidence: medium; commits: cda1ab149b00, 908d91b1a4d9, 01e4b3b78f8f; files: packages/gateway-protocol/src/schema/error-codes.ts, src/gateway/server-methods.ts, src/gateway/server-methods/nodes.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit 5fe8d6a into main Jul 18, 2026
150 of 156 checks passed
@steipete
steipete deleted the codex/gateway-structured-auth-errors branch July 18, 2026 21:02
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 19, 2026
…10925)

* fix(gateway): structure authorization errors

* test(gateway): align authorization contracts

* fix(gateway): regenerate protocol bindings

* fix(gateway): preserve optional scope errors

* fix(gateway): report complete pairing scopes

* style(gateway): format protocol exports
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
…10925)

* fix(gateway): structure authorization errors

* test(gateway): align authorization contracts

* fix(gateway): regenerate protocol bindings

* fix(gateway): preserve optional scope errors

* fix(gateway): report complete pairing scopes

* style(gateway): format protocol exports
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 docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant