From f9328a0f9fc1812cca3b28372be5dd9e4a7f2c19 Mon Sep 17 00:00:00 2001 From: telli Date: Mon, 28 Sep 2026 14:54:56 -0700 Subject: [PATCH 1/4] perf(gateway): verify each request's account token once 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) --- .../Endpoints/EndpointHelpers.cs | 28 ++++++- .../EndpointHelpersAuthenticationTests.cs | 81 +++++++++++++++++++ 2 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs diff --git a/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs b/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs index 209ec51c..1c899934 100644 --- a/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs +++ b/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs @@ -69,7 +69,7 @@ public static bool IsAuthorizedRequest(HttpContext ctx, GatewayConfig config, bo if (operatorAccounts is not null) { var token = GatewaySecurity.GetToken(ctx, config.Security.AllowQueryStringToken); - if (!string.IsNullOrWhiteSpace(token) && operatorAccounts.TryAuthenticateToken(token, out _)) + if (!string.IsNullOrWhiteSpace(token) && TryAuthenticateAccountToken(ctx, operatorAccounts, token, out _)) return true; } } @@ -161,7 +161,7 @@ public static OperatorAuthorizationResult AuthorizeOperatorRequest( if (IsAllowedAuthMode(policy, OrganizationAuthModeNames.AccountToken) && !string.IsNullOrWhiteSpace(token) && operatorAccounts is not null && - operatorAccounts.TryAuthenticateToken(token, out var accountIdentity)) + TryAuthenticateAccountToken(ctx, operatorAccounts, token, out var accountIdentity)) { return new OperatorAuthorizationResult( true, @@ -203,6 +203,30 @@ operatorAccounts is not null && IsBootstrapAdmin: false); } + private sealed record AccountTokenVerification(string Token, bool Succeeded, OperatorIdentitySnapshot? Identity); + + // Token verification is deliberately slow (PBKDF2) and serialized inside OperatorAccountService, and one + // request can pass through several checks (authentication, role, identity). Verify each request's token + // once and reuse the outcome; revocation still applies from the next request. + private static bool TryAuthenticateAccountToken( + HttpContext ctx, + OperatorAccountService operatorAccounts, + string token, + out OperatorIdentitySnapshot? identity) + { + if (ctx.Items.TryGetValue(typeof(AccountTokenVerification), out var cached) && + cached is AccountTokenVerification previous && + string.Equals(previous.Token, token, StringComparison.Ordinal)) + { + identity = previous.Identity; + return previous.Succeeded; + } + + var succeeded = operatorAccounts.TryAuthenticateToken(token, out identity); + ctx.Items[typeof(AccountTokenVerification)] = new AccountTokenVerification(token, succeeded, identity); + return succeeded; + } + public static bool TrySetMaxRequestBodySize(HttpContext ctx, long maxBytes) { var feature = ctx.Features.Get(); diff --git a/src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs b/src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs new file mode 100644 index 00000000..3bf10f14 --- /dev/null +++ b/src/OpenClaw.Tests/EndpointHelpersAuthenticationTests.cs @@ -0,0 +1,81 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using OpenClaw.Core.Models; +using OpenClaw.Gateway; +using OpenClaw.Gateway.Bootstrap; +using OpenClaw.Gateway.Endpoints; +using Xunit; + +namespace OpenClaw.Tests; + +public sealed class EndpointHelpersAuthenticationTests : IDisposable +{ + private readonly string _storagePath = Path.Combine(Path.GetTempPath(), "openclaw-endpoint-auth-tests", Guid.NewGuid().ToString("N")); + + public void Dispose() + { + try { Directory.Delete(_storagePath, recursive: true); } + catch { } + } + + [Fact] + public void AccountToken_WhenCheckedTwiceInOneRequest_ShouldBeVerifiedOnce() + { + var (startup, services, accounts, accountId, token) = CreateOperatorToken(); + var ctx = CreateRequest(services, token.Token); + + Assert.True(EndpointHelpers.IsAuthorizedRequest(ctx, startup.Config, startup.IsNonLoopbackBind)); + + // Revoking after the first check makes a second verification observable: a re-run of the slow + // token check would now fail, while a reused result for this request still succeeds. + Assert.True(accounts.RevokeToken(accountId, token.TokenInfo!.Id)); + var auth = EndpointHelpers.AuthorizeOperatorRequest(ctx, startup, services.GetRequiredService(), requireCsrf: false); + + Assert.True(auth.IsAuthorized); + Assert.Equal(accountId, auth.AccountId); + } + + [Fact] + public void AccountToken_WhenRevokedBeforeNextRequest_ShouldBeRejected() + { + var (startup, services, accounts, accountId, token) = CreateOperatorToken(); + Assert.True(EndpointHelpers.IsAuthorizedRequest(CreateRequest(services, token.Token), startup.Config, startup.IsNonLoopbackBind)); + + Assert.True(accounts.RevokeToken(accountId, token.TokenInfo!.Id)); + + Assert.False(EndpointHelpers.IsAuthorizedRequest(CreateRequest(services, token.Token), startup.Config, startup.IsNonLoopbackBind)); + } + + private (GatewayStartupContext Startup, ServiceProvider Services, OperatorAccountService Accounts, string AccountId, OperatorAccountTokenCreateResponse Token) CreateOperatorToken() + { + var config = new GatewayConfig { AuthToken = "bootstrap-token" }; + var startup = new GatewayStartupContext + { + Config = config, + RuntimeState = RuntimeModeResolver.Resolve(config.Runtime, dynamicCodeSupported: true), + IsNonLoopbackBind = true + }; + var accounts = new OperatorAccountService(_storagePath, NullLogger.Instance); + var account = accounts.Create(new OperatorAccountCreateRequest + { + Username = "memo-operator", + Password = "P@ssw0rd123!", + Role = OperatorRoleNames.Operator + }); + var token = accounts.CreateToken(account.Id, new OperatorAccountTokenCreateRequest { Label = "memo" })!; + + var services = new ServiceCollection(); + services.AddSingleton(new BrowserSessionAuthService(config)); + services.AddSingleton(accounts); + services.AddSingleton(new OrganizationPolicyService(_storagePath, NullLogger.Instance)); + return (startup, services.BuildServiceProvider(), accounts, account.Id, token); + } + + private static DefaultHttpContext CreateRequest(IServiceProvider services, string token) + { + var ctx = new DefaultHttpContext { RequestServices = services }; + ctx.Request.Headers.Authorization = $"Bearer {token}"; + return ctx; + } +} From bac8ec728cfe0f89dbcdbb481a506a72a81e0723 Mon Sep 17 00:00:00 2001 From: telli Date: Mon, 28 Sep 2026 12:08:10 -0700 Subject: [PATCH 2/4] fix(gateway): require operator role for the /ws/live model bridge /ws/live admitted any authenticated role. It runs no tools, but it opens a live session on the gateway's provider credentials, so a viewer token could spend them. It now uses CanExecuteAgent like /ws and closes below operator with 1008. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1 + docs/AUTHENTICATION.md | 5 ++-- docs/zh-CN/AUTHENTICATION.md | 5 ++-- src/OpenClaw.Core/Models/GatewayConfig.cs | 3 +- .../Endpoints/EndpointHelpers.cs | 5 ++-- .../Endpoints/WebSocketEndpoints.cs | 8 +++++ .../GatewayAdminEndpointTests.cs | 30 +++++++++++++++++-- 7 files changed, 48 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5411dcda..3d5cc2ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ All notable changes to this project are tracked in this file. - Required the `operator` role wherever a request runs the agent or mutates state, matching `POST /api/integration/messages`. Previously any authenticated identity, including viewer account tokens, viewer browser sessions, and OIDC users without an operator role claim, could run the agent with tools through these surfaces. New operator accounts default to `viewer`, so grant `operator` to accounts used for Companion, CLI/TUI chat, and API clients. - `/ws`: closed with code 1008, which web chat reports as an authorization failure. + - `/ws/live`: closed with code 1008. The live model bridge runs no tools but spends provider credentials. - `POST /v1/chat/completions` and `POST /v1/responses`: 403 with an OpenAI-style `permission_error` body. - A2A execution paths: 403. Discovery stays public. - `POST /apps/chat`: 403. diff --git a/docs/AUTHENTICATION.md b/docs/AUTHENTICATION.md index 1ce6e2db..a1655f5c 100644 --- a/docs/AUTHENTICATION.md +++ b/docs/AUTHENTICATION.md @@ -131,7 +131,7 @@ Request enters ### 3.2 WebSocket Authentication Flow -WebSocket endpoints (`/ws`, `/ws/live`) authenticate in Phase 1. `/ws` then applies the chat role check (Phase 2) and resolves the user ID (Phase 3): +WebSocket endpoints (`/ws`, `/ws/live`) authenticate in Phase 1 and then apply the role check (Phase 2). `/ws` also resolves the user ID (Phase 3): **Phase 1: `TryValidateWebSocketRequest` → `IsAuthorizedRequest`** @@ -149,7 +149,7 @@ WebSocket request (/ws) └─ Passed ──→ Accept WebSocket connection ``` -**Phase 2 (`/ws` only): `EndpointHelpers.CanExecuteAgent`** +**Phase 2: `EndpointHelpers.CanExecuteAgent`** Every `/ws` frame becomes agent input, so the connection needs the same `operator` role as `POST /api/integration/messages`. The role is resolved through `AuthorizeOperatorRequest`, the same chain the HTTP API uses: @@ -185,6 +185,7 @@ WebSocket connected | Surface | Below operator | |---------|----------------| | `/ws` | Accepted, then closed with 1008 (PolicyViolation) | +| `/ws/live` | Accepted, then closed with 1008. The live bridge runs no tools but spends provider credentials | | `POST /v1/chat/completions`, `POST /v1/responses` | 403 with an OpenAI-style `permission_error` body | | A2A execution paths (discovery stays public) | 403 | | `POST /apps/chat` | 403 | diff --git a/docs/zh-CN/AUTHENTICATION.md b/docs/zh-CN/AUTHENTICATION.md index 13d03dde..9ef7bc48 100644 --- a/docs/zh-CN/AUTHENTICATION.md +++ b/docs/zh-CN/AUTHENTICATION.md @@ -131,7 +131,7 @@ HTTP API 端点使用 `AuthorizeOperatorRequest` 方法([EndpointHelpers.cs](. ### 3.2 WebSocket 认证流程 -WebSocket 端点 (`/ws`, `/ws/live`) 在第一步完成认证;`/ws` 随后执行聊天角色检查(第二步)并解析用户 ID(第三步): +WebSocket 端点 (`/ws`, `/ws/live`) 在第一步完成认证,随后执行角色检查(第二步);`/ws` 还会解析用户 ID(第三步): **第一步:`TryValidateWebSocketRequest` → `IsAuthorizedRequest`** @@ -149,7 +149,7 @@ WebSocket 请求 (/ws) └─ 通过 ──→ 接受 WebSocket 连接 ``` -**第二步(仅 `/ws`):`EndpointHelpers.CanExecuteAgent`** +**第二步:`EndpointHelpers.CanExecuteAgent`** 每个 `/ws` 帧都会成为智能体输入,因此连接需要与 `POST /api/integration/messages` 相同的 `operator` 角色。角色通过 `AuthorizeOperatorRequest` 解析,与 HTTP API 使用同一认证链: @@ -185,6 +185,7 @@ WebSocket 已连接 | 入口 | 角色低于 operator 时 | |------|----------------------| | `/ws` | 先接受,再以 1008 (PolicyViolation) 关闭 | +| `/ws/live` | 先接受,再以 1008 关闭。实时桥接不运行工具,但会消耗提供商凭据额度 | | `POST /v1/chat/completions`、`POST /v1/responses` | 403,返回 OpenAI 风格的 `permission_error` 响应体 | | A2A 执行路径(发现端点仍然公开) | 403 | | `POST /apps/chat` | 403 | diff --git a/src/OpenClaw.Core/Models/GatewayConfig.cs b/src/OpenClaw.Core/Models/GatewayConfig.cs index 17c5b175..4de35924 100644 --- a/src/OpenClaw.Core/Models/GatewayConfig.cs +++ b/src/OpenClaw.Core/Models/GatewayConfig.cs @@ -387,7 +387,8 @@ public sealed class SecurityConfig /// /// Temporary compatibility switch, to be removed in the next release. When true, authenticated identities /// below the operator role (such as viewer accounts) can still run the agent through /ws, /v1/*, A2A, - /// /apps/chat, MCP App tool calls, and mutating MCP tools. Each such request is logged so the accounts can be promoted. + /// /apps/chat, MCP App tool calls, mutating MCP tools, and /ws/live. Each such request is logged so the accounts + /// can be promoted. /// public bool AllowViewerAgentExecution { get; set; } = false; diff --git a/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs b/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs index 1c899934..25152a78 100644 --- a/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs +++ b/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs @@ -357,7 +357,8 @@ public static (OperatorAuthorizationResult? Authorization, IResult? Failure) Aut /// /// Surfaces that turn a request into agent input or another mutation (chat, the OpenAI-compatible API, - /// A2A, MCP Apps chat and tool calls, mutating MCP tools) require the same role as POST /api/integration/messages. + /// A2A, MCP Apps chat and tool calls, mutating MCP tools, the live model bridge) require the same role as + /// POST /api/integration/messages. /// Authentication alone is not enough: viewer credentials must stay read-only. /// Denials, and admissions under Security.AllowViewerAgentExecution, are logged with the account so /// admins can find identities that need the operator role. @@ -393,7 +394,7 @@ public static bool CanExecuteAgent( } logger.LogWarning( - "Denied {Action} for {AuthMode} account {AccountId} ({Username}) with role {Role}: running the agent requires the operator role.", + "Denied {Action} for {AuthMode} account {AccountId} ({Username}) with role {Role}: this action requires the operator role.", action, auth.AuthMode, auth.AccountId, auth.Username, auth.Role); return false; } diff --git a/src/OpenClaw.Gateway/Endpoints/WebSocketEndpoints.cs b/src/OpenClaw.Gateway/Endpoints/WebSocketEndpoints.cs index af908099..7b3fbc1b 100644 --- a/src/OpenClaw.Gateway/Endpoints/WebSocketEndpoints.cs +++ b/src/OpenClaw.Gateway/Endpoints/WebSocketEndpoints.cs @@ -43,6 +43,14 @@ public static void MapOpenClawWebSocketEndpoints( return; var ws = await ctx.WebSockets.AcceptWebSocketAsync(); + + // The live bridge runs no tools but spends provider credentials, so it needs the same role as /ws. + if (!EndpointHelpers.CanExecuteAgent(ctx, startup)) + { + await ws.CloseAsync(WebSocketCloseStatus.PolicyViolation, EndpointHelpers.OperatorRoleRequiredMessage, ctx.RequestAborted); + return; + } + try { var openRequest = await ReceiveLiveOpenRequestAsync(ws, ctx.RequestAborted); diff --git a/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs b/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs index 777b1b2e..d2af936b 100644 --- a/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs +++ b/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs @@ -380,6 +380,32 @@ public async Task WebSocketChat_WhenOpenLoopbackWithoutCredentials_ShouldStayOpe Assert.Null(await ReceiveWithinAsync(ws, TimeSpan.FromMilliseconds(500))); } + [Fact] + public async Task WebSocketLive_WhenViewerAccountToken_ShouldCloseWithPolicyViolation() + { + await using var harness = await CreateHarnessAsync(nonLoopbackBind: true); + var token = CreateAccountToken(harness, "live-viewer", OperatorRoleNames.Viewer); + + using var ws = await ConnectWebSocketAsync(harness, token, "/ws/live"); + var received = await ReceiveWithinAsync(ws, TimeSpan.FromSeconds(5)); + + Assert.NotNull(received); + Assert.Equal(WebSocketMessageType.Close, received.MessageType); + Assert.Equal(WebSocketCloseStatus.PolicyViolation, ws.CloseStatus); + Assert.Contains("operator", ws.CloseStatusDescription, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task WebSocketLive_WhenOperatorAccountToken_ShouldStayOpen() + { + await using var harness = await CreateHarnessAsync(nonLoopbackBind: true); + var token = CreateAccountToken(harness, "live-operator", OperatorRoleNames.Operator); + + using var ws = await ConnectWebSocketAsync(harness, token, "/ws/live"); + + Assert.Null(await ReceiveWithinAsync(ws, TimeSpan.FromMilliseconds(500))); + } + [Theory] [InlineData("/v1/chat/completions", """{"messages":[{"role":"user","content":"hello"}]}""")] [InlineData("/v1/responses", """{"input":"hello"}""")] @@ -719,12 +745,12 @@ private static string CreateAccountToken(GatewayTestHarness harness, string user return token!.Token; } - private static async Task ConnectWebSocketAsync(GatewayTestHarness harness, string? bearerToken) + private static async Task ConnectWebSocketAsync(GatewayTestHarness harness, string? bearerToken, string path = "/ws") { var client = harness.App.GetTestServer().CreateWebSocketClient(); if (bearerToken is not null) client.ConfigureRequest = request => request.Headers.Authorization = $"Bearer {bearerToken}"; - return await client.ConnectAsync(new Uri("ws://localhost/ws"), CancellationToken.None); + return await client.ConnectAsync(new Uri("ws://localhost" + path), CancellationToken.None); } // Returns null when nothing arrives in time, which for these tests means the server kept the connection open. From 4e64d0ee21891dd37f3993d73aee73cd8032a1db Mon Sep 17 00:00:00 2001 From: telli Date: Mon, 28 Sep 2026 12:08:10 -0700 Subject: [PATCH 3/4] feat(companion): check the account role before opening chat Companion opened the chat socket before loading the account's role, so a viewer was admitted and then closed by the gateway. It now loads the role first; when the gateway reports a role below operator it explains that chat needs the operator role instead of connecting, and keeps the read-only status views. A role that is only the no-token placeholder does not block the connection, and the role is applied as soon as the auth session loads rather than after the setup status call. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 +- .../ViewModels/MainWindowViewModel.cs | 18 ++++++- .../CompanionConnectionTests.cs | 54 +++++++++++++++++++ 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d5cc2ef..b47d4edb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,7 +47,7 @@ All notable changes to this project are tracked in this file. - Each denial is logged under `OpenClaw.Gateway.Authorization` with the surface, account, and role, so admins can find accounts to promote. - Migration aid: `OpenClaw:Security:AllowViewerAgentExecution=true` restores the previous behavior for authenticated identities below `operator`, logs each such request, and adds the `viewer_agent_execution_allowed` risk flag to `admin posture`. It is temporary and will be removed in the next release. - Stopped trusting a loopback client IP on `/apps/health`, `/apps/chat`, and `/apps/mcp/{appId}`. Behind a same-host reverse proxy without `TrustForwardedHeaders`, every caller has a loopback IP, so these routes answered unauthenticated requests, including agent runs and MCP App tool calls, and ignored `AlwaysRequireAuth`. They now follow the gateway's bind-based rule: open only on a loopback-bound gateway without `AlwaysRequireAuth`. -- Added `OpenClawWebSocketClient.OnClosed`, raised with the gateway's close status and reason. Companion now marks itself disconnected and shows the reason instead of appearing connected after the gateway closes the socket. +- Added `OpenClawWebSocketClient.OnClosed`, raised with the gateway's close status and reason. Companion now marks itself disconnected and shows the reason instead of appearing connected after the gateway closes the socket. It also checks the account's role before connecting: a gateway-reported role below `operator` gets an explanation instead of a chat connection, and the read-only status views stay available. - Bound tool-approval decisions to the original requester (`channelId` + `senderId`) for non-loopback/public binds. - Kept `POST /tools/approve` as an explicit admin override path. - Added WhatsApp official webhook signature validation support (`ValidateSignature`, `WebhookAppSecret`/`WebhookAppSecretRef`). diff --git a/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs b/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs index 08e9d62b..201e5906 100644 --- a/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs +++ b/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs @@ -65,6 +65,8 @@ public sealed partial class MainWindowViewModel : ViewModelBase [ObservableProperty] private string _operatorRole = OperatorRoleNames.Viewer; + private bool _operatorRoleReportedByGateway; + [ObservableProperty] private string _operatorAuthMode = "account_token"; @@ -526,11 +528,21 @@ private async Task ConnectAsync() SaveSettings(); Status = "Connecting…"; + + // Learn the role first: a viewer would be admitted and then closed by the gateway, so say why up front + // and keep the read-only status views. Only trust a role the gateway reported, not the no-token placeholder. + await LoadAdminStatusAsyncInternal(); + if (_operatorRoleReportedByGateway && !IsBootstrapAdmin && !OperatorRoleNames.CanAccess(OperatorRole, OperatorRoleNames.Operator)) + { + Status = "Disconnected"; + AddSystemMessage($"Signed in as {OperatorIdentity} with the {OperatorRole} role. Chat needs the operator role; ask an admin to change this account's role."); + return; + } + await _client.ConnectAsync(uri, string.IsNullOrWhiteSpace(AuthToken) ? null : AuthToken, CancellationToken.None); IsConnected = true; Status = "Connected"; await SendCanvasReadyAsync(); - await LoadAdminStatusAsyncInternal(); await LoadWhatsAppSetupAsync(); } catch (Exception ex) @@ -628,6 +640,7 @@ private async Task LoadAdminStatusAsync() private async Task LoadAdminStatusAsyncInternal() { + _operatorRoleReportedByGateway = false; using var client = CreateAdminClient(out var error); if (client is null) { @@ -647,8 +660,9 @@ private async Task LoadAdminStatusAsyncInternal() try { var auth = await client.GetAuthSessionAsync(CancellationToken.None); - var setup = await client.GetSetupStatusAsync(CancellationToken.None); ApplyOperatorIdentity(auth.AuthMode, auth.Role, auth.DisplayName, auth.Username, auth.IsBootstrapAdmin); + _operatorRoleReportedByGateway = true; + var setup = await client.GetSetupStatusAsync(CancellationToken.None); AdminStatus = auth.IsBootstrapAdmin ? "Using bootstrap/breakglass admin auth." : $"Authenticated as {auth.DisplayName ?? auth.Username ?? "operator"} via {auth.AuthMode}."; diff --git a/src/OpenClaw.Tests/CompanionConnectionTests.cs b/src/OpenClaw.Tests/CompanionConnectionTests.cs index 24d3b076..fb6807b2 100644 --- a/src/OpenClaw.Tests/CompanionConnectionTests.cs +++ b/src/OpenClaw.Tests/CompanionConnectionTests.cs @@ -1,8 +1,11 @@ +using System.Net; using System.Net.WebSockets; +using System.Text; using Avalonia.Headless.XUnit; using Avalonia.Threading; using OpenClaw.Companion.Models; using OpenClaw.Companion.Services; +using OpenClaw.Client; using OpenClaw.Companion.ViewModels; using Xunit; @@ -66,6 +69,57 @@ public async Task ServerClose_WhenClientReconnectsBeforeUiDispatch_ShouldKeepCon Assert.DoesNotContain(vm.Messages, message => message.Role == ChatRole.System); } + [AvaloniaFact] + public async Task Connect_WhenGatewayReportsViewerRole_ShouldExplainWithoutOpeningChat() + { + var vm = CreateViewModelWithAuthSession("""{"authMode":"account_token","role":"viewer","username":"reader"}"""); + vm.AuthToken = "viewer-token"; + + await vm.ConnectCommand.ExecuteAsync(null); + Dispatcher.UIThread.RunJobs(); + + Assert.False(vm.IsConnected); + Assert.Equal("Disconnected", vm.Status); + Assert.Contains(vm.Messages, m => m.Text.Contains("operator role", StringComparison.OrdinalIgnoreCase)); + Assert.DoesNotContain(vm.Messages, m => m.Text.StartsWith("Connect failed", StringComparison.Ordinal)); + } + + [AvaloniaFact] + public async Task Connect_WhenNoTokenLoaded_ShouldStillAttemptChat() + { + // Without a token the viewer role is only a placeholder, not something the gateway reported. + var vm = CreateViewModelWithAuthSession("""{"authMode":"account_token","role":"viewer"}"""); + + await vm.ConnectCommand.ExecuteAsync(null); + Dispatcher.UIThread.RunJobs(); + + Assert.Contains(vm.Messages, m => m.Text.StartsWith("Connect failed", StringComparison.Ordinal)); + Assert.DoesNotContain(vm.Messages, m => m.Text.Contains("operator role", StringComparison.OrdinalIgnoreCase)); + } + + private MainWindowViewModel CreateViewModelWithAuthSession(string authSessionJson) + { + var dir = Path.Combine(Path.GetTempPath(), "openclaw-companion-connection-tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + _tempDirs.Add(dir); + var vm = new MainWindowViewModel( + new SettingsStore(dir), + new GatewayWebSocketClient(), + (baseUrl, authToken) => new OpenClawHttpClient(baseUrl, authToken, new HttpClient(new CallbackHandler(request => + request.RequestUri!.AbsolutePath == "/auth/session" + ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(authSessionJson, Encoding.UTF8, "application/json") } + : new HttpResponseMessage(HttpStatusCode.NotFound))))); + // Nothing listens here, so an attempted chat connection fails fast and visibly. + vm.ServerUrl = "ws://127.0.0.1:9/ws"; + return vm; + } + + private sealed class CallbackHandler(Func callback) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(callback(request)); + } + private (MainWindowViewModel ViewModel, GatewayWebSocketClient Client) CreateConnectedViewModel() { var dir = Path.Combine(Path.GetTempPath(), "openclaw-companion-connection-tests", Guid.NewGuid().ToString("N")); From 6abb971c9454aa6bb27916b3e26f9136885a05b9 Mon Sep 17 00:00:00 2001 From: telli Date: Tue, 29 Sep 2026 03:58:25 -0700 Subject: [PATCH 4/4] fix(companion): follow the gateway's agent-execution answer, not the role Companion's preflight refused to open chat for any gateway-reported role below operator. With Security.AllowViewerAgentExecution on, the gateway still admits those viewers, so the documented migration switch did not work for Companion users. GET /auth/session now reports canExecuteAgent, computed by the same rule CanExecuteAgent enforces, including the opt-out. Companion blocks only when the gateway says false; when the field is absent (older gateways) it connects and lets the gateway decide. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 2 +- docs/AUTHENTICATION.md | 2 ++ docs/zh-CN/AUTHENTICATION.md | 2 ++ .../ViewModels/MainWindowViewModel.cs | 13 ++++---- src/OpenClaw.Core/Models/AdminApiModels.cs | 6 ++++ .../Endpoints/AdminEndpoints.Support.cs | 1 + .../Endpoints/EndpointHelpers.cs | 5 +++ .../CompanionConnectionTests.cs | 32 +++++++++++++++++-- .../GatewayAdminEndpointTests.cs | 20 ++++++++++++ 9 files changed, 74 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b47d4edb..61040045 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,7 +47,7 @@ All notable changes to this project are tracked in this file. - Each denial is logged under `OpenClaw.Gateway.Authorization` with the surface, account, and role, so admins can find accounts to promote. - Migration aid: `OpenClaw:Security:AllowViewerAgentExecution=true` restores the previous behavior for authenticated identities below `operator`, logs each such request, and adds the `viewer_agent_execution_allowed` risk flag to `admin posture`. It is temporary and will be removed in the next release. - Stopped trusting a loopback client IP on `/apps/health`, `/apps/chat`, and `/apps/mcp/{appId}`. Behind a same-host reverse proxy without `TrustForwardedHeaders`, every caller has a loopback IP, so these routes answered unauthenticated requests, including agent runs and MCP App tool calls, and ignored `AlwaysRequireAuth`. They now follow the gateway's bind-based rule: open only on a loopback-bound gateway without `AlwaysRequireAuth`. -- Added `OpenClawWebSocketClient.OnClosed`, raised with the gateway's close status and reason. Companion now marks itself disconnected and shows the reason instead of appearing connected after the gateway closes the socket. It also checks the account's role before connecting: a gateway-reported role below `operator` gets an explanation instead of a chat connection, and the read-only status views stay available. +- Added `OpenClawWebSocketClient.OnClosed`, raised with the gateway's close status and reason. Companion now marks itself disconnected and shows the reason instead of appearing connected after the gateway closes the socket. It also asks the gateway before connecting: `GET /auth/session` now reports `canExecuteAgent`, which follows `AllowViewerAgentExecution`, and when it is `false` Companion explains the missing `operator` role instead of opening chat. The read-only status views stay available. Against a gateway that does not report the field, Companion connects and the gateway decides. - Bound tool-approval decisions to the original requester (`channelId` + `senderId`) for non-loopback/public binds. - Kept `POST /tools/approve` as an explicit admin override path. - Added WhatsApp official webhook signature validation support (`ValidateSignature`, `WebhookAppSecret`/`WebhookAppSecretRef`). diff --git a/docs/AUTHENTICATION.md b/docs/AUTHENTICATION.md index a1655f5c..abbb476d 100644 --- a/docs/AUTHENTICATION.md +++ b/docs/AUTHENTICATION.md @@ -196,6 +196,8 @@ Bootstrap tokens and open loopback resolve to `admin` and are unaffected. New op Each denial is logged as a warning under the `OpenClaw.Gateway.Authorization` category, naming the surface, auth mode, account, and role (never the credential), so admins can find the accounts to promote. To migrate without an outage, set `OpenClaw:Security:AllowViewerAgentExecution=true`, watch the log for the admitted accounts, grant them `operator`, then turn the setting off. The setting is temporary and will be removed in the next release. +`GET /auth/session` reports the result of this check as `canExecuteAgent`, including the effect of `AllowViewerAgentExecution`, so clients can explain a refusal before connecting. Companion uses it; a gateway that predates the field omits it. + ### 3.4 `IsAuthorizedRequest` — Detailed Logic ```csharp diff --git a/docs/zh-CN/AUTHENTICATION.md b/docs/zh-CN/AUTHENTICATION.md index 9ef7bc48..0eb7df21 100644 --- a/docs/zh-CN/AUTHENTICATION.md +++ b/docs/zh-CN/AUTHENTICATION.md @@ -196,6 +196,8 @@ WebSocket 已连接 每次拒绝都会在 `OpenClaw.Gateway.Authorization` 类别下记录一条警告日志,包含入口、认证方式、账户和角色(绝不包含凭据),便于管理员找出需要提升角色的账户。如需无中断迁移,可设置 `OpenClaw:Security:AllowViewerAgentExecution=true`,从日志中找出被放行的账户,为其授予 `operator` 角色,然后关闭该设置。该设置是临时的,将在下一个版本移除。 +`GET /auth/session` 会以 `canExecuteAgent` 字段报告这项检查的结果(包括 `AllowViewerAgentExecution` 的影响),客户端可以在连接前说明拒绝原因。Companion 会使用该字段;早于此字段的网关不会返回它。 + ### 3.4 `IsAuthorizedRequest` 详细逻辑 ```csharp diff --git a/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs b/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs index 201e5906..cc319159 100644 --- a/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs +++ b/src/OpenClaw.Companion/ViewModels/MainWindowViewModel.cs @@ -65,7 +65,7 @@ public sealed partial class MainWindowViewModel : ViewModelBase [ObservableProperty] private string _operatorRole = OperatorRoleNames.Viewer; - private bool _operatorRoleReportedByGateway; + private bool? _agentExecutionAllowedByGateway; [ObservableProperty] private string _operatorAuthMode = "account_token"; @@ -529,10 +529,11 @@ private async Task ConnectAsync() Status = "Connecting…"; - // Learn the role first: a viewer would be admitted and then closed by the gateway, so say why up front - // and keep the read-only status views. Only trust a role the gateway reported, not the no-token placeholder. + // Ask the gateway first: an account it won't let run the agent would be admitted and then closed, so say why + // up front and keep the read-only status views. Only its answer counts, not the role: a viewer can still chat + // under Security.AllowViewerAgentExecution, and a gateway that doesn't report it decides at connect time. await LoadAdminStatusAsyncInternal(); - if (_operatorRoleReportedByGateway && !IsBootstrapAdmin && !OperatorRoleNames.CanAccess(OperatorRole, OperatorRoleNames.Operator)) + if (_agentExecutionAllowedByGateway == false) { Status = "Disconnected"; AddSystemMessage($"Signed in as {OperatorIdentity} with the {OperatorRole} role. Chat needs the operator role; ask an admin to change this account's role."); @@ -640,7 +641,7 @@ private async Task LoadAdminStatusAsync() private async Task LoadAdminStatusAsyncInternal() { - _operatorRoleReportedByGateway = false; + _agentExecutionAllowedByGateway = null; using var client = CreateAdminClient(out var error); if (client is null) { @@ -661,7 +662,7 @@ private async Task LoadAdminStatusAsyncInternal() { var auth = await client.GetAuthSessionAsync(CancellationToken.None); ApplyOperatorIdentity(auth.AuthMode, auth.Role, auth.DisplayName, auth.Username, auth.IsBootstrapAdmin); - _operatorRoleReportedByGateway = true; + _agentExecutionAllowedByGateway = auth.CanExecuteAgent; var setup = await client.GetSetupStatusAsync(CancellationToken.None); AdminStatus = auth.IsBootstrapAdmin ? "Using bootstrap/breakglass admin auth." diff --git a/src/OpenClaw.Core/Models/AdminApiModels.cs b/src/OpenClaw.Core/Models/AdminApiModels.cs index 9c5f22e1..34c5dd00 100644 --- a/src/OpenClaw.Core/Models/AdminApiModels.cs +++ b/src/OpenClaw.Core/Models/AdminApiModels.cs @@ -27,6 +27,12 @@ public sealed class AuthSessionResponse public string? Username { get; init; } public string? DisplayName { get; init; } public bool IsBootstrapAdmin { get; init; } + + /// + /// Whether this caller may run the agent (chat over /ws, /v1/*, A2A, and the other agent surfaces). + /// Null from gateways that predate the field; those decide only when the client connects. + /// + public bool? CanExecuteAgent { get; init; } public bool PublicBind { get; init; } public string[] AllowedAuthModes { get; init; } = []; public string EffectiveToolSurface { get; init; } = "web"; diff --git a/src/OpenClaw.Gateway/Endpoints/AdminEndpoints.Support.cs b/src/OpenClaw.Gateway/Endpoints/AdminEndpoints.Support.cs index e916e8e7..ba6c8dbc 100644 --- a/src/OpenClaw.Gateway/Endpoints/AdminEndpoints.Support.cs +++ b/src/OpenClaw.Gateway/Endpoints/AdminEndpoints.Support.cs @@ -234,6 +234,7 @@ private static AuthSessionResponse MapAuthSessionResponse( Username = auth.Username, DisplayName = auth.DisplayName, IsBootstrapAdmin = auth.IsBootstrapAdmin, + CanExecuteAgent = EndpointHelpers.AllowsAgentExecution(auth, startup), PublicBind = startup.IsNonLoopbackBind, AllowedAuthModes = [.. policy.AllowedAuthModes], EffectiveToolSurface = preset.Surface, diff --git a/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs b/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs index 25152a78..f7d69bf4 100644 --- a/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs +++ b/src/OpenClaw.Gateway/Endpoints/EndpointHelpers.cs @@ -363,6 +363,11 @@ public static (OperatorAuthorizationResult? Authorization, IResult? Failure) Aut /// Denials, and admissions under Security.AllowViewerAgentExecution, are logged with the account so /// admins can find identities that need the operator role. /// + // The rule CanExecuteAgent enforces, without its logging, so /auth/session can report it before a client tries. + internal static bool AllowsAgentExecution(OperatorAuthorizationResult auth, GatewayStartupContext startup) + => auth.IsAuthorized + && (IsRoleAllowed(auth.Role, "integration.mutate.agent", out _) || startup.Config.Security.AllowViewerAgentExecution); + public static bool CanExecuteAgent( HttpContext ctx, GatewayStartupContext startup, diff --git a/src/OpenClaw.Tests/CompanionConnectionTests.cs b/src/OpenClaw.Tests/CompanionConnectionTests.cs index fb6807b2..db522b02 100644 --- a/src/OpenClaw.Tests/CompanionConnectionTests.cs +++ b/src/OpenClaw.Tests/CompanionConnectionTests.cs @@ -70,9 +70,9 @@ public async Task ServerClose_WhenClientReconnectsBeforeUiDispatch_ShouldKeepCon } [AvaloniaFact] - public async Task Connect_WhenGatewayReportsViewerRole_ShouldExplainWithoutOpeningChat() + public async Task Connect_WhenGatewayReportsAgentExecutionDenied_ShouldExplainWithoutOpeningChat() { - var vm = CreateViewModelWithAuthSession("""{"authMode":"account_token","role":"viewer","username":"reader"}"""); + var vm = CreateViewModelWithAuthSession("""{"authMode":"account_token","role":"viewer","username":"reader","canExecuteAgent":false}"""); vm.AuthToken = "viewer-token"; await vm.ConnectCommand.ExecuteAsync(null); @@ -84,6 +84,34 @@ public async Task Connect_WhenGatewayReportsViewerRole_ShouldExplainWithoutOpeni Assert.DoesNotContain(vm.Messages, m => m.Text.StartsWith("Connect failed", StringComparison.Ordinal)); } + [AvaloniaFact] + public async Task Connect_WhenGatewayAllowsViewerAgentExecution_ShouldAttemptChat() + { + // Security.AllowViewerAgentExecution lets a viewer chat, so the role alone must not stop Companion. + var vm = CreateViewModelWithAuthSession("""{"authMode":"account_token","role":"viewer","username":"reader","canExecuteAgent":true}"""); + vm.AuthToken = "viewer-token"; + + await vm.ConnectCommand.ExecuteAsync(null); + Dispatcher.UIThread.RunJobs(); + + Assert.Contains(vm.Messages, m => m.Text.StartsWith("Connect failed", StringComparison.Ordinal)); + Assert.DoesNotContain(vm.Messages, m => m.Text.Contains("operator role", StringComparison.OrdinalIgnoreCase)); + } + + [AvaloniaFact] + public async Task Connect_WhenGatewayDoesNotReportAgentExecution_ShouldAttemptChat() + { + // An older gateway reports only the role; it decides at connect time, so Companion must not guess. + var vm = CreateViewModelWithAuthSession("""{"authMode":"account_token","role":"viewer","username":"reader"}"""); + vm.AuthToken = "viewer-token"; + + await vm.ConnectCommand.ExecuteAsync(null); + Dispatcher.UIThread.RunJobs(); + + Assert.Contains(vm.Messages, m => m.Text.StartsWith("Connect failed", StringComparison.Ordinal)); + Assert.DoesNotContain(vm.Messages, m => m.Text.Contains("operator role", StringComparison.OrdinalIgnoreCase)); + } + [AvaloniaFact] public async Task Connect_WhenNoTokenLoaded_ShouldStillAttemptChat() { diff --git a/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs b/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs index d2af936b..3a871248 100644 --- a/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs +++ b/src/OpenClaw.Tests/GatewayAdminEndpointTests.cs @@ -652,6 +652,26 @@ public async Task AgentExecution_WhenViewerAndAllowViewerAgentExecution_ShouldRu Assert.Contains("legacy-viewer", entry, StringComparison.Ordinal); } + [Theory] + [InlineData(OperatorRoleNames.Viewer, false, false)] + [InlineData(OperatorRoleNames.Operator, false, true)] + [InlineData(OperatorRoleNames.Viewer, true, true)] + public async Task AuthSession_ShouldReportWhetherTheCallerCanRunTheAgent(string role, bool allowViewerAgentExecution, bool expected) + { + await using var harness = await CreateHarnessAsync( + nonLoopbackBind: true, + configure: config => config.Security.AllowViewerAgentExecution = allowViewerAgentExecution); + var token = CreateAccountToken(harness, $"session-{role}", role); + + using var request = new HttpRequestMessage(HttpMethod.Get, "/auth/session"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + var response = await harness.Client.SendAsync(request); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using var payload = await ReadJsonAsync(response); + Assert.Equal(expected, payload.RootElement.GetProperty("canExecuteAgent").GetBoolean()); + } + [Fact] public async Task AgentExecution_WhenAllowViewerAgentExecutionWithoutCredentials_ShouldStillReject() {