Skip to content

Commit be9eb71

Browse files
committed
fix(sessions): scope delegated access to target owner
1 parent d81cfca commit be9eb71

5 files changed

Lines changed: 175 additions & 17 deletions

File tree

‎src/agents/tools/sessions-access.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { GatewayCredentialsRequiredError } from "../../gateway/call.js";
77
import { GatewayClientRequestError } from "../../gateway/client.js";
88
import {
99
createAgentToAgentPolicy,
10+
createSessionVisibilityChecker,
1011
createSessionVisibilityGuard,
1112
createSessionVisibilityRowChecker,
1213
resolveEffectiveSessionToolsVisibility,
@@ -560,6 +561,65 @@ describe("createSessionVisibilityGuard", () => {
560561
expect(gateway).not.toHaveBeenCalled();
561562
});
562563

564+
it("does not apply a bare-key scoped grant to another agent's session", async () => {
565+
const targets: string[] = [];
566+
const unregister = createSessionVisibilityChecker.registerScopedAccessProvider((request) => {
567+
targets.push(request.targetSessionKey);
568+
return request.targetSessionKey === "shared" ? { expectedSessionId: "agent-a" } : undefined;
569+
});
570+
try {
571+
const gateway = vi.fn();
572+
const access = await resolveSessionToolAccess({
573+
action: "history",
574+
requesterAgentId: "main",
575+
requesterSessionKey: "agent:main:main",
576+
authorizationTargetSessionKey: "agent:ops:shared",
577+
targetAgentId: "ops",
578+
targetSessionKey: "shared",
579+
requesterOwned: false,
580+
visibility: "self",
581+
a2aPolicy: createAgentToAgentPolicy({} as unknown as OpenClawConfig),
582+
callGateway: gateway as never,
583+
});
584+
585+
expect(access.allowed).toBe(false);
586+
expect(targets).toEqual(["agent:ops:shared"]);
587+
expect(gateway).not.toHaveBeenCalled();
588+
} finally {
589+
unregister();
590+
}
591+
});
592+
593+
it("keeps incognito targets hidden from scoped grants", async () => {
594+
const targetSessionKey = "agent:main:dashboard:incognito-private";
595+
const unregister = createSessionVisibilityChecker.registerScopedAccessProvider(() => ({
596+
expectedSessionId: "incognito-incarnation",
597+
}));
598+
try {
599+
const gateway = vi.fn();
600+
const access = await resolveSessionToolAccess({
601+
action: "history",
602+
requesterAgentId: "main",
603+
requesterSessionKey: "agent:main:main",
604+
targetAgentId: "main",
605+
targetSessionKey,
606+
requesterOwned: true,
607+
visibility: "all",
608+
a2aPolicy: createAgentToAgentPolicy({} as unknown as OpenClawConfig),
609+
callGateway: gateway as never,
610+
});
611+
612+
expect(access).toEqual({
613+
allowed: false,
614+
status: "forbidden",
615+
error: `Session not visible from session tools: ${targetSessionKey}`,
616+
});
617+
expect(gateway).not.toHaveBeenCalled();
618+
} finally {
619+
unregister();
620+
}
621+
});
622+
563623
it("retains lookup-failure guidance for a cross-agent ACP child candidate", async () => {
564624
const gateway = vi.fn(async () => {
565625
throw new GatewayClientRequestError({

‎src/agents/tools/sessions-access.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ export async function resolveSessionToolAccess(params: {
5353
const scoped = createSessionVisibilityChecker.resolveScopedAccess({
5454
action: params.action,
5555
requesterSessionKey: params.requesterSessionKey,
56-
targetSessionKey: params.targetSessionKey,
56+
// A bare key is not globally unique under explicit ownership. Callers
57+
// qualify cross-agent targets so a grant cannot cross store owners.
58+
targetSessionKey: authorizationTargetSessionKey,
5759
});
5860
if (scoped) {
5961
return { allowed: true, expectedSessionId: scoped.expectedSessionId };

‎src/agents/tools/sessions-search-tool.test.ts‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
/** sessions_search visibility, bounds, redaction, and input tests. */
2+
import path from "node:path";
23
import { Value } from "typebox/value";
3-
import { describe, expect, it } from "vitest";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
6+
import {
7+
applySessionStoreProjection,
8+
replaceSessionEntrySync,
9+
} from "../../config/sessions/session-accessor.js";
10+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
411
import type { callGateway as gatewayCall } from "../../gateway/call.js";
12+
import { createSessionVisibilityChecker } from "../../plugin-sdk/session-visibility.js";
513
import { compactToolOutputHint } from "../tool-schema-hints.js";
614
import { createSessionsSearchTool } from "./sessions-search-tool.js";
715

@@ -86,6 +94,8 @@ function createTool(params: {
8694
}
8795

8896
describe("sessions_search tool", () => {
97+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
98+
8999
it("rejects a literal global target owned by another fixed-store agent", async () => {
90100
const requests: CallGatewayRequest[] = [];
91101
const tool = createTool({
@@ -419,4 +429,57 @@ describe("sessions_search tool", () => {
419429
params: { agentId: "main", query: "text", sessionKeys: ["main"], limit: 25 },
420430
});
421431
});
432+
433+
it("rejects a scoped grant when the target incarnation changes before search", async () => {
434+
const requesterSessionKey = "agent:main:clickclack:discussion-race";
435+
const targetSessionKey = "agent:main:main";
436+
const expectedSessionId = "old-incarnation";
437+
const storePath = path.join(tempDirs.make("openclaw-sessions-search-"), "sessions.sqlite");
438+
await applySessionStoreProjection({
439+
storePath,
440+
skipMaintenance: true,
441+
update: (store) => {
442+
store[targetSessionKey] = { sessionId: expectedSessionId, updatedAt: 1 };
443+
return { persist: true, result: undefined };
444+
},
445+
});
446+
const requests: CallGatewayRequest[] = [];
447+
const unregister = createSessionVisibilityChecker.registerScopedAccessProvider((request) => {
448+
if (
449+
request.requesterSessionKey !== requesterSessionKey ||
450+
request.targetSessionKey !== targetSessionKey
451+
) {
452+
return undefined;
453+
}
454+
replaceSessionEntrySync(
455+
{ storePath, sessionKey: targetSessionKey },
456+
{ sessionId: "replacement-incarnation", updatedAt: 2 },
457+
);
458+
return { expectedSessionId };
459+
});
460+
try {
461+
const tool = createSessionsSearchTool({
462+
agentSessionKey: requesterSessionKey,
463+
sandboxed: true,
464+
config: {
465+
session: { store: storePath },
466+
tools: { sessions: { visibility: "self" } },
467+
agents: { defaults: { sandbox: { sessionToolsVisibility: "spawned" } } },
468+
} as OpenClawConfig,
469+
callGateway: async <T = Record<string, unknown>>(
470+
request: CallGatewayRequest,
471+
): Promise<T> => {
472+
requests.push(request);
473+
return { results: [hit({ sessionKey: targetSessionKey })] } as T;
474+
},
475+
});
476+
477+
await expect(
478+
tool.execute("scoped-grant-race", { query: "text", sessionKey: targetSessionKey }),
479+
).rejects.toThrow(`Session "${targetSessionKey}" changed after access was granted.`);
480+
expect(requests.some((request) => request.method === "sessions.search")).toBe(false);
481+
} finally {
482+
unregister();
483+
}
484+
});
422485
});

‎src/agents/tools/sessions-search-tool.ts‎

Lines changed: 43 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ import {
2727
callAgentToolGatewayRequest,
2828
type AgentToolGatewayRequestCaller,
2929
} from "./in-process-gateway.js";
30-
import { resolveSessionToolTargetAgentId } from "./scoped-session-access.js";
30+
import {
31+
resolveSessionToolTargetAgentId,
32+
runWithScopedSessionAccess,
33+
} from "./scoped-session-access.js";
3134
import {
3235
createAgentToAgentPolicy,
3336
createSessionVisibilityRowChecker,
@@ -110,6 +113,7 @@ type SearchSessionCandidate = {
110113
key: string;
111114
access: "authorized" | "row";
112115
agentId?: string;
116+
expectedSessionId?: string;
113117
ownerSessionKey?: string;
114118
parentSessionKey?: string;
115119
spawnedBy?: string;
@@ -370,7 +374,14 @@ export function createSessionsSearchTool(opts?: {
370374
agentId: opts?.agentId,
371375
});
372376

373-
let sessionTarget: { agentId: string; key: string; requesterOwned: boolean } | undefined;
377+
let sessionTarget:
378+
| {
379+
agentId: string;
380+
key: string;
381+
requesterOwned: boolean;
382+
expectedSessionId?: string;
383+
}
384+
| undefined;
374385
if (requestedSessionKey) {
375386
const normalizedRequestedKey = requestedSessionKey.trim();
376387
const semanticTargetAgentId =
@@ -461,13 +472,19 @@ export function createSessionsSearchTool(opts?: {
461472
if (!access.allowed) {
462473
return jsonResult({ status: access.status, error: access.error });
463474
}
475+
if (access.expectedSessionId) {
476+
sessionTarget.expectedSessionId = access.expectedSessionId;
477+
}
464478
}
465479
const searchSessions = (
466480
sessionTarget
467481
? [
468482
{
469483
key: sessionTarget.key,
470484
access: "authorized" as const,
485+
...(sessionTarget.expectedSessionId
486+
? { expectedSessionId: sessionTarget.expectedSessionId }
487+
: {}),
471488
...(!parseAgentSessionKey(sessionTarget.key)
472489
? { agentId: sessionTarget.agentId }
473490
: {}),
@@ -509,19 +526,30 @@ export function createSessionsSearchTool(opts?: {
509526
offset += SESSIONS_SEARCH_MAX_SESSION_KEYS
510527
) {
511528
const chunk = candidates.slice(offset, offset + SESSIONS_SEARCH_MAX_SESSION_KEYS);
512-
const result = await gatewayCall<{
513-
results?: GatewaySearchHit[];
514-
indexing?: boolean;
515-
truncated?: boolean;
516-
}>({
517-
method: "sessions.search",
518-
params: {
519-
agentId,
520-
query,
521-
limit: SESSIONS_SEARCH_MAX_LIMIT,
522-
sessionKeys: chunk.map((candidate) => candidate.key),
523-
},
524-
});
529+
const runSearch = () =>
530+
gatewayCall<{
531+
results?: GatewaySearchHit[];
532+
indexing?: boolean;
533+
truncated?: boolean;
534+
}>({
535+
method: "sessions.search",
536+
params: {
537+
agentId,
538+
query,
539+
limit: SESSIONS_SEARCH_MAX_LIMIT,
540+
sessionKeys: chunk.map((candidate) => candidate.key),
541+
},
542+
});
543+
const scopedCandidate = chunk.length === 1 ? chunk[0] : undefined;
544+
const result = scopedCandidate?.expectedSessionId
545+
? await runWithScopedSessionAccess({
546+
cfg,
547+
agentId,
548+
expectedSessionId: scopedCandidate.expectedSessionId,
549+
targetSessionKey: scopedCandidate.key,
550+
run: runSearch,
551+
})
552+
: await runSearch();
525553
indexing ||= result.indexing === true;
526554
backendTruncated ||= result.truncated === true;
527555
for (const hit of Array.isArray(result.results) ? result.results : []) {

‎src/plugin-sdk/session-visibility.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,11 @@ function registerScopedSessionAccessProvider(provider: ScopedSessionAccessProvid
6262
function resolveScopedSessionAccess(
6363
request: ScopedSessionAccessRequest,
6464
): ScopedSessionAccessGrant | undefined {
65+
// Incognito transcripts must never be re-persisted through another session,
66+
// including host-scoped access paths that bypass normal visibility policy.
67+
if (resolveIncognitoSessionAccessDenial(request.targetSessionKey)) {
68+
return undefined;
69+
}
6570
for (const provider of scopedSessionAccessProviders) {
6671
try {
6772
const grant = provider(request);

0 commit comments

Comments
 (0)