Skip to content

perf(gateway): verify each request's account token once - #261

Merged
Telli merged 2 commits into
mainfrom
perf/verify-account-token-once
Sep 29, 2026
Merged

Telli merged 2 commits into
mainfrom
perf/verify-account-token-once

Conversation

@Telli

@Telli Telli commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Follow-up to #256. This commit was pushed to #256's branch after it had already merged, so it never reached main.

With #256, each gated request verifies the caller's credential twice: once to authenticate (IsAuthorizedRequest) and again to resolve the role (AuthorizeOperatorRequest). For account tokens, each verification:

  • runs PBKDF2 (120,000 iterations, about 17 ms of CPU measured locally);
  • holds OperatorAccountService's global lock while it does;
  • then rewrites the accounts file.

That halves account-token throughput on /v1/*, /apps/chat, A2A, /ws, and the mutating MCP tools, and it doubles the lock time every other request waits behind.

Summary

  • The first verification in a request stores its outcome in HttpContext.Items. Later checks in the same request reuse it when the presented token matches.
  • Revocation, disabling, and role changes still apply from the next request.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • Tests

Validation

  • dotnet build OpenClaw.Net.slnx --configuration Release: 0 warnings, 0 errors
  • dotnet test OpenClaw.Net.slnx --configuration Release --no-build: all passing (run on the branch stacked above this commit; the commit itself is unchanged)
  • dotnet run --project samples/OpenClaw.HelloAgent -c Release --no-build

AccountToken_WhenCheckedTwiceInOneRequest_ShouldBeVerifiedOnce failed before the change. It revokes the token between the two checks, so a second verification is observable. AccountToken_WhenRevokedBeforeNextRequest_ShouldBeRejected guards against the result leaking across requests.

Review Notes

  • I considered NativeAOT compatibility (no reflection; a private record in HttpContext.Items)
  • I considered security posture and unsafe defaults. The cache lives only for one request and is keyed on the exact token string.
  • I updated docs/tests where needed
  • This PR is scoped and does not mix unrelated changes

Commercial or Customer-Driven Contribution Disclosure

Same origin as #256. Vendor-neutral gateway performance fix.

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the code style implementation of this project
  • I have added tests that prove my fix is effective or that my feature works
  • All new and existing tests passed locally (dotnet test)
  • I have updated the documentation (README.md, comments) if required
  • I have checked for security implications (input validation, authorization)
  • I have checked the relevant maintainer review checklist
  • I have disclosed whether this directly supports a company or customer use case

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Account-token checks now return consistent results when the same token is checked multiple times during a request.
    • Revoked account tokens are rejected on subsequent requests. A token revoked during an in-progress request may remain valid for that request.

Account-token verification runs PBKDF2 (120,000 iterations, about 17 ms
of CPU) inside OperatorAccountService's global lock and then rewrites
the accounts file. The role checks added in this branch meant that
/v1/*, /apps/chat, A2A, /ws, /ws/live, and mutating MCP tools verified
the same token twice per request, halving account-token throughput on
those surfaces.

Cache the verification outcome in HttpContext.Items for the rest of the
request. Revocation, disabling, and role changes still apply from the
next request.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings September 28, 2026 22:42

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 26ec78dd-cce9-45b4-bba9-c38835a0047c

📥 Commits

Reviewing files that changed from the base of the PR and between 03d9a76 and f9328a0.

📒 Files selected for processing (2)
  • src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs
  • src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

Both account-token authorization paths now use request-scoped caching for verification results and identities. Tests cover repeated checks within one request and rejection of a revoked token in a subsequent request.

Changes

Account-token authentication

Layer / File(s) Summary
Request-scoped verification and authorization checks
src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs, src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs
A shared helper caches token verification results and identities in HttpContext.Items. Both authorization paths use the helper. Tests check reuse after revocation in the same request and rejection on a new request. The test setup creates an account, token, and service provider, and removes temporary storage during disposal.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: geffzhang

Merge Risk: ⚪ Minimal · up to 7b9d4

No actionable merge-blocking issue is established. The account-token cache is scoped to the request and matching token.

Security Architecture Review

Security architecture risk: 🔵 Low · up to f9328

A token revoked or an account downgraded between checks can still pass a later check in the same request. A new request checks account state again. The added exposure is narrow but affects an authorization boundary.

Retained concerns

  • Low · security · inferred: Revocation, disablement, or a role downgrade after the first account-token check cannot affect a later check on the same request. On /ws, the later agent-role check occurs after WebSocket acceptance, creating a narrow interval in which a previously authorized credential can pass that check despite an intervening account change.
Security review details

Security Blast Radius

  • inferred — The added stale-result interval is limited to subsequent checks for the same token on one request. For /ws it can affect the setup-time agent-role decision; subsequent frames inherit the established connection identity, but the inspected loop does not look up the request cache.

Security Findings and Attack Paths

  • inferred — If an authorized account token is revoked or its role is reduced between /ws authentication and its later agent-role check, the cached result can allow setup to continue where a fresh verifier check could reject it. This requires an intervening state change; it is not evidence of authorization after revocation on a new request.

Trust Boundaries and Controls

  • observed — The gateway still checks account-token authorization mode before using the cache. The account service serializes its verification with account-state access, but a cache hit does not re-enter that service.
  • observed — /ws and /ws/live authorize during connection setup, not by calling the changed helpers for each message. Thus an active connection's lack of per-message reauthorization is not established as a new behavior of this PR.

Hardening Proposals

  • proposed — If revocation or role changes must govern the /ws setup-time role decision, recheck account state at that decision or explicitly define the permitted request-scoped staleness. Independently specify whether established connections must react to later revocation.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: reuse account-token verification within a request.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Comment thread src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs
Comment thread src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs
Comment thread src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs
@Telli
Telli merged commit efc88f9 into main Sep 29, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants