Skip to content

fix: MCP Apps cannot be pinned by their signed-in owner - #178043

Merged
jalehman merged 3 commits into
openclaw:mainfrom
McgAtom:fix/mcp-app-board-requester
Oct 21, 2026
Merged

jalehman merged 3 commits into
openclaw:mainfrom
McgAtom:fix/mcp-app-board-requester

Conversation

@McgAtom

@McgAtom McgAtom commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes users being unable to pin their own requester-bound MCP App previews to a board they can edit. This includes an authenticated shared-secret operator whose connection remains usable after display-profile preparation fails.

User Impact

Users can pin their own previews while other writers of the same shared board cannot pin those previews. Existing grants, cancellation, sharing removal and runtime revocation remain enforced. No persisted format, schema or configuration change is introduced.

Why This Change Was Made

Resolve the requester through the existing captured operator-authority owner before resolving the preview. This preserves named users and the canonical attested token/password owner fallback, rather than guessing an owner ID from a missing connection profile. Keep that authority current through the Board mutation and release it in the existing cleanup path, including when actor release fails. Non-MCP widget content does not acquire this extra hold. The existing preview requester-equality guard remains unchanged.

Credit to roboclaw-bot for identifying the shared-secret case and offering the canonical authority amendment.

Evidence

  • The original requester propagation regression fails before the repair. The added shared-secret control also fails on the published a27d134086ca72c1876accf301048fc21029a64d source with McpAppViewExpiredError; with the amendment, all 7 owner cases pass. They exercise actual Board dispatch and SQLite persistence, including cancellation, sharing removal, runtime retirement and foreign-requester denial.
  • 43 tests across 4 Board consumer files pass, including those 7 owner cases. Targeted types through the canonical wrapper, typed lint, formatting and diff checks pass. Independent source review and a canonical Codex review found no actionable P0–P2 issue; these reviews are source assessments, not independent runtime executions.
  • The built isolated Gateway authenticates Alice and Bob over real WebSockets. Bob first writes and publishes an ordinary widget on their shared board, then cannot pin Alice’s actual model/MCP preview. The rejected request leaves revision 1, only the control widget, no publication and no additional tool effects. Alice pins the same preview successfully. The same flow grants the app, serves real MCP resource/tool requests, holds a catalog refresh and rejects delayed execution and subsequent resource access after revocation; the forbidden tool marker never runs.
  • A separate fault-injected built Gateway exercises the shared-secret handshake boundary. After one healthy owner connection, a temporary profile-preparation exception leaves a real password-authenticated socket without an authenticated display profile (users.self rejects). That socket completes an actual model/MCP turn and pins its owner-bound preview through canonical operator acquisition. A different authenticated profile cannot pin it, and the stored revision remains 1. The existing Alice/Bob and grant/revocation flow also passes in this run.
  • The fault changes only display-profile preparation at the existing handshake catch boundary; it does not inject a requester identity or alter canonical operator acquisition. Both temporary experiment files were restored byte-for-byte. The fault hook and experiment-only test are excluded from this PR. This demonstrates controlled fallback recovery, not an observed production database outage. Model and MCP servers are synthetic; no authenticated external-provider claim is made.
Redacted shared-secret Gateway output
[shared-secret-fallback-proof] {"handshakeAccepted":true,"usersSelfRefusedForMissingProfile":true,"agentStatus":"ok","ownerPin":"fallback-owner-pin","foreignProfilePinRejected":true,"revisionBefore":1,"revisionAfter":1,"widgets":["fallback-owner-pin"]}
Tests  1 passed (1)

The fault-injected run takes 14.92 seconds in Vitest, including fixture setup. Its synthetic prompt was corrected to use the maintained provider fixture’s existing tool-search trigger after the first experiment produced no App; assertions were retained.

Validation above applies to the published a27d134086ca72c1876accf301048fc21029a64d tree plus this two-file authority amendment, retaining product base a56638bd73343411b7524b8cbc9b0f9631531c2a. It is not a fresh build or validation of current upstream main. The published head’s product CI passes, but its CodeQL run 39376534819 was cancelled after the process-exec job timed out during checkout, before initialization or analysis. That category remains incomplete; aggregate green statuses do not replace it. This amendment has no hosted CI result until it is published and its new-head checks complete.

  • Contributor confirmation: I understand what this code does.

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Oct 20, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head a27d134086ca72c1876accf301048fc21029a64d, but the PR head is now 8605f601e62ff3f0373c92d86c7a0b7d045b9547. Its old verdict and PR readiness labels are no longer current.

Next step
Run or wait for a fresh ClawSweeper review on the current PR head.

Review history (3 earlier review cycles)
  • reviewed 2026-10-20T04:52:53.505Z sha 7516243 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-20T05:52:39.104Z sha a27d134 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-20T06:00:19.414Z sha a27d134 :: needs maintainer review before merge. :: none

@roboclaw-bot

roboclaw-bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

@McgAtom — the source comparison resolves the apparent discrepancy in our earlier question: healthy token/password backend connections now attach the owner profile, so the reported full-flow pass is consistent with your resolver. I found no basis to claim a stale-authority defect in that normal profiled path.

There is a separate, admitted fallback case: connect-user-profile.ts permits authenticated owner admission when profile preparation fails; connect-session.ts still registers the authenticated system owner and shared-auth generation. Existing post-connect-health and real-socket connect-device-pairing regressions preserve admission without authenticatedUserProfile. The canonical operator-authority owner explicitly recognizes that subject, whereas the display/profile helper returns undefined. Our fixture represents that fallback, not a claim that healthy backend connections normally lack a profile.

I prepared an incremental amendment against your exact head 7516243, rather than opening a competing PR. It uses the existing captured operator authority and includes the different-real-profile control: an ordinary write to the shared session succeeds, then the original requester-bound preview pin is denied with no destination or tool call. Existing grant/revocation/cancellation/retirement/sharing assertions remain.

The patch passes a disposable-index apply check; both resulting files exactly match our reviewed candidate’s source. That candidate has 23 passing focused handler/storage cases and a passing current-source build. Those green receipts belong to our candidate, not automatically to an amended contributor head. Our full Gateway replay remains unpassed. No contributor code was executed and your branch has not been changed.

Could you confirm the exact Gateway source/build and requester route for the reported pass? The patch below is offered for this PR, with your existing authorship preserved.

Proposed incremental amendment for 7516243 — not applied
diff --git a/src/gateway/server-methods/board.mcp-admission.test.ts b/src/gateway/server-methods/board.mcp-admission.test.ts
index cf3276e01e1c..7f985b9e83cb 100644
--- a/src/gateway/server-methods/board.mcp-admission.test.ts
+++ b/src/gateway/server-methods/board.mcp-admission.test.ts
@@ -1,5 +1,6 @@
 import { Type } from "typebox";
 import { afterEach, expect, it, vi } from "vitest";
+import { GATEWAY_OWNER_PROFILE_ID } from "../../../packages/gateway-protocol/src/schema/users.js";
 import { awaitGateBeforeSettlement, withinTest } from "../../../test/helpers/promise.js";
 import type { SessionMcpRuntime } from "../../agents/agent-bundle-mcp-types.js";
 import { fetchMcpAppView, getMcpAppViewLease } from "../../agents/mcp-ui-resource.js";
@@ -19,7 +20,9 @@ import {
   openOpenClawAgentDatabase,
 } from "../../state/openclaw-agent-db.js";
 import { runOpenClawAgentWorkerWrite } from "../../state/openclaw-agent-write-admission.js";
+import { ensureCanonicalGatewayOwnerProfile } from "../../state/user-profile-writes.js";
 import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
+import { captureGatewayAuthPolicy } from "../auth-policy.js";
 import { boardStore } from "../board-store.js";
 import {
   executeMcpAppOperation,
@@ -28,10 +31,11 @@ import {
   resolveMcpAppAllowedToolNames,
   type McpAppActiveView,
 } from "../mcp-app-operations.js";
+import { makeClient } from "../server-broadcast.test-helpers.js";
 import { handleGatewayRequest } from "../server-methods.js";
 import { roleClient, rolePolicyConfig } from "../session-sharing.test-utils.js";
 import { createBoardHarness } from "./board.test-support.js";
-import type { RespondFn } from "./types.js";
+import type { GatewayClient, RespondFn } from "./types.js";
 
 const profileState = { scenario: "minimal", prepareProfileCatalog: true } as const;
 const scopes = ["operator.read", "operator.write", "operator.approvals"] as const;
@@ -41,14 +45,23 @@ afterEach(() => {
   vi.restoreAllMocks();
 });
 
-it.for(["keep", "revoke", "cancel", "retire", "sharing"] as const)(
-  "retains only current source tool authority after queueing (%s)",
+it.for([
+  "keep",
+  "revoke",
+  "cancel",
+  "retire",
+  "sharing",
+  "shared-secret",
+  "other-requester",
+] as const)(
+  "retains only current requester-bound source tool authority (%s)",
   (outcome, { signal: testSignal }) =>
     withOpenClawTestState(profileState, async ({ workspaceDir }) => {
       const revoke = outcome === "revoke";
       const cancel = outcome === "cancel";
       const retire = outcome === "retire";
       const sharing = outcome === "sharing";
+      const sharedSecret = outcome === "shared-secret";
       const target = { agentId: "main", sessionKey: "agent:main:mcp-admission" };
       const cfg: OpenClawConfig = {
         ...rolePolicyConfig(),
@@ -57,20 +70,44 @@ it.for(["keep", "revoke", "cancel", "retire", "sharing"] as const)(
         tools: { exec: { mode: "full" } },
       };
       cfg.gateway!.roles!.definitions!.view!.scopes = [...scopes];
+      cfg.gateway!.auth = { mode: "token", token: "synthetic-fixture-token" };
       setRuntimeConfigSnapshot(cfg, cfg);
-      const client = {
-        ...roleClient("view", "mcp-admission-owner"),
-        connId: "mcp-admission-owner",
-      };
-      client.connect.scopes = [...scopes];
-      const clientProfileId = client.authenticatedUserProfile!.profileId;
+      const client: GatewayClient = sharedSecret
+        ? makeClient("shared-secret-peer", "operator", ["operator.admin"]).client
+        : {
+            ...roleClient("view", "mcp-admission-owner"),
+            connId: "mcp-admission-owner",
+          };
+      if (sharedSecret) {
+        await ensureCanonicalGatewayOwnerProfile("Synthetic owner");
+        client.connect.client = {
+          id: "gateway-client",
+          version: "test",
+          platform: "test",
+          mode: "backend",
+        };
+        client.internal = { authenticatedOperator: true, operatorRoleActor: { kind: "system" } };
+        client.authPolicy = captureGatewayAuthPolicy(cfg, {
+          role: "operator",
+          authMethod: "token",
+        });
+        client.usesSharedGatewayAuth = true;
+        client.sharedGatewaySessionGeneration = "synthetic-shared-generation";
+        expect(client.authenticatedUserProfile).toBeUndefined();
+      } else {
+        client.connect.scopes = [...scopes];
+      }
+      const clientProfileId = sharedSecret
+        ? GATEWAY_OWNER_PROFILE_ID
+        : client.authenticatedUserProfile!.profileId;
       const creatorId = sharing
         ? roleClient("view", "mcp-admission-other").authenticatedUserProfile!.profileId
         : clientProfileId;
       await upsertSessionEntryCore(target, {
         sessionId: "mcp-admission-session",
         updatedAt: 1,
-        visibility: sharing ? ("shared" as const) : ("draft" as const),
+        visibility:
+          sharing || outcome === "other-requester" ? ("shared" as const) : ("draft" as const),
         createdActor: {
           type: "human" as const,
           source: "profile" as const,
@@ -150,9 +187,9 @@ it.for(["keep", "revoke", "cancel", "retire", "sharing"] as const)(
           mintFromTranscript: async ({ descriptor: sourceDescriptor, readOnly, ...options }) => {
             const fetched = await fetchMcpAppView({
               ...options,
+              requesterId: clientProfileId,
               runtime,
               ...sourceDescriptor,
-              requesterId: clientProfileId,
               toolInput: {},
               toolResult: { content: [] },
               ...(readOnly ? { readOnly: true } : {}),
@@ -173,11 +210,12 @@ it.for(["keep", "revoke", "cancel", "retire", "sharing"] as const)(
         method: string,
         input: Record<string, unknown>,
         signal?: AbortSignal,
+        requester: GatewayClient = client,
       ) => {
         const respond = vi.fn<RespondFn>();
         await handleGatewayRequest({
           req: { type: "req", id: "mcp-admission", method, params: { ...target, ...input } },
-          client,
+          client: requester,
           context: board.context,
           respond,
           isWebchatConnect: () => false,
@@ -192,6 +230,38 @@ it.for(["keep", "revoke", "cancel", "retire", "sharing"] as const)(
       };
       await appView("source", sourceWidget);
       const sourceView = views[0]!;
+      if (outcome === "other-requester") {
+        const other = roleClient("write", "mcp-admission-writer");
+        other.connId = "other-requester";
+        const control = await invoke(
+          "board.widget.put",
+          {
+            name: "write-access-control",
+            content: { kind: "html", html: "<p>Authorized session writer</p>" },
+          },
+          undefined,
+          other,
+        );
+        expect(control.mock.calls[0]?.[2]).toBeUndefined();
+        expect(control.mock.calls[0]?.[0]).toBe(true);
+        const denied = await invoke(
+          "board.widget.put",
+          {
+            name: "destination",
+            content: { kind: "mcp-app", viewId: sourceView.view.viewId },
+          },
+          undefined,
+          other,
+        );
+        expect(denied.mock.calls[0]).toMatchObject([
+          false,
+          undefined,
+          { message: expect.stringContaining("not authorized") },
+        ]);
+        expect(await boardStore.readWidgetMcpApp(target, "destination")).toBeUndefined();
+        expect(callTool).not.toHaveBeenCalled();
+        return;
+      }
       await requireMcpAppInteraction(sourceView.view);
       const authorizeSource = sourceView.view.authorizeAppInteraction!;
       const policyEntered = createDeferredCore();
diff --git a/src/gateway/server-methods/board.ts b/src/gateway/server-methods/board.ts
index d2ffd9e6385b..f097e00e3b75 100644
--- a/src/gateway/server-methods/board.ts
+++ b/src/gateway/server-methods/board.ts
@@ -55,9 +55,9 @@ import {
   requireMcpAppInteraction,
   resolveMcpAppActiveView,
   resolveMcpAppAllowedToolNames,
-  resolveMcpAppRequesterId,
 } from "../mcp-app-operations.js";
 import { mintMcpAppViewFromTranscript } from "../mcp-app-reconstruction.js";
+import { captureGatewayOperatorRunAuthority } from "../operator-run-authority.js";
 import { sessionObserverScopeKey } from "../session-observer-model.js";
 import { resolveRequestedSessionStoreTarget } from "../session-store-key.js";
 import {
@@ -202,8 +202,19 @@ export function createBoardHandlers(store: BoardStore): GatewayRequestHandlers {
       "board.widget.put",
       validateBoardWidgetPutParams,
       async (invocation) => {
-        const { params: requestParams, respond, context, client } = invocation;
-        const authority = captureBoardRequestAuthority(invocation);
+        const { params: requestParams, respond, context } = invocation;
+        const boardAuthority = captureBoardRequestAuthority(invocation);
+        let requester: Awaited<ReturnType<typeof captureGatewayOperatorRunAuthority>>;
+        const authority = {
+          ...boardAuthority,
+          assertActive: composeSessionSourceAssertion(
+            [boardAuthority.assertActive],
+            (assertSources) => {
+              assertSources();
+              requester?.authority.assertCurrent();
+            },
+          ),
+        };
         const boardSession = resolveBoardSession(requestParams, context, respond);
         if (!boardSession) {
           return;
@@ -238,11 +249,21 @@ export function createBoardHandlers(store: BoardStore): GatewayRequestHandlers {
             }
             content = { kind: "html", html: document.html };
           } else if (requestParams.content.kind === "mcp-app") {
+            requester = await captureGatewayOperatorRunAuthority({
+              client: invocation.client,
+              context,
+              hasCurrentClientAuthority: invocation.hasCurrentClientAuthority,
+              invocationAuthority: {
+                assertCurrent: boardAuthority.assertActive,
+                signal: invocation.signal,
+              },
+            });
+            authority.assertActive();
             const active = await resolveMcpAppActiveView({
               ...boardSession,
               viewId: requestParams.content.viewId,
+              requesterId: requester?.authority.profileId,
               cfg: context.getRuntimeConfig(),
-              requesterId: resolveMcpAppRequesterId(client),
             });
             authority.assertActive();
             const { view } = active;
@@ -474,7 +495,11 @@ export function createBoardHandlers(store: BoardStore): GatewayRequestHandlers {
           };
           await (memory ? runWithSessionActorStorage(memory, putAndApprove) : putAndApprove());
         } finally {
-          await memory?.actor.release();
+          try {
+            await memory?.actor.release();
+          } finally {
+            requester?.release();
+          }
         }
       },
     ),

@McgAtom

McgAtom commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 20, 2026
steipete pushed a commit that referenced this pull request Oct 20, 2026
Refresh maintained dependencies to the newest releases published on or before the 2026-10-13T04:46:41Z seven-day cutoff: 119 npm declarations across 23 packages with regenerated pnpm and standalone Vercel locks, seven Rust crates, two Ruby gems and the MLX helper's Swift Collections. Patches, forks and release-age exemptions are preserved; Vitest 5.0.4, Codex Action 1.13, Gradle 9.8, pre-commit 4.7 and Ruff 0.17 stay deferred.

Merged with current main; the SecOps-owned create-github-app-token pin bumps moved to #178708. Also fixes the native completion contention test ordering. Remaining CI failures are attributed to existing main state in the PR (MCP board requester binding owned by #178043, gateway-rpc-chat ownership e2e reproduced on main, Wear timing test).

Co-authored-by: roboclaw-bot <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
Refresh maintained dependencies to the newest releases published on or before the 2026-10-13T04:46:41Z seven-day cutoff: 119 npm declarations across 23 packages with regenerated pnpm and standalone Vercel locks, seven Rust crates, two Ruby gems and the MLX helper's Swift Collections. Patches, forks and release-age exemptions are preserved; Vitest 5.0.4, Codex Action 1.13, Gradle 9.8, pre-commit 4.7 and Ruff 0.17 stay deferred.

Merged with current main; the SecOps-owned create-github-app-token pin bumps moved to openclaw#178708. Also fixes the native completion contention test ordering. Remaining CI failures are attributed to existing main state in the PR (MCP board requester binding owned by openclaw#178043, gateway-rpc-chat ownership e2e reproduced on main, Wear timing test).

Co-authored-by: roboclaw-bot <[email protected]>
@clawsweeper clawsweeper Bot removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 21, 2026
@jalehman
jalehman merged commit b394c80 into openclaw:main Oct 21, 2026
130 of 131 checks passed
@jalehman

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
)

* fix: preserve requester identity when pinning MCP Apps

* test: prove shared-board MCP requester isolation

* fix: retain MCP pin authority for shared-secret operators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants