Skip to content

Commit 1382d4e

Browse files
committed
fix(gateway): reject unconfigured session owners
Validate the canonical configured owner before session and worktree side effects so dispatch, reclaim, and delete can manage every created session.
1 parent 5b67b61 commit 1382d4e

5 files changed

Lines changed: 124 additions & 76 deletions

File tree

‎src/gateway/server-methods/sessions-create.ts‎

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ import {
3333
resolveSessionCreateModelSelection as resolveCreateTitleEntry,
3434
} from "../session-create-service.js";
3535
import { resolveRequestedSessionAgentId as resolveRequestedGlobalAgentId } from "../session-request-agent.js";
36-
import { resolveSessionStoreAgentId } from "../session-store-key.js";
3736
import { readSessionMessageCountAsync } from "../session-transcript-readers.js";
3837
import {
3938
loadGatewaySessionEntryReadOnly,
@@ -104,8 +103,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
104103
const explicitlyRequestedAgent = resolveRequestedGlobalAgentId(
105104
cfg,
106105
agentSelectionKey,
107-
explicitlyRequestedAgentId,
108-
{ allowUnconfiguredExplicitAgent: true },
106+
p.agentId ?? parseAgentSessionKey(explicitlyRequestedKey)?.agentId,
109107
);
110108
if (!explicitlyRequestedAgent.ok) {
111109
respond(false, undefined, explicitlyRequestedAgent.error);
@@ -224,7 +222,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
224222
return;
225223
}
226224
const explicitSessionLabel = normalizeOptionalString(p.label);
227-
const titleAgentId = normalizeAgentId(explicitlyRequestedAgent.agentId);
225+
const titleAgentId = explicitlyRequestedAgent.agentId;
228226
const shouldPrepareWorktreeTitle =
229227
p.worktree === true && !requestedWorktreeName && !explicitSessionLabel;
230228
const deferWorktreeTitle =
@@ -280,11 +278,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
280278
}
281279
}
282280
let sessionKey = p.key;
283-
let sessionAgentId =
284-
catalogAgentId ??
285-
explicitlyRequestedAgent.agentId ??
286-
p.agentId ??
287-
parseAgentSessionKey(explicitlyRequestedKey)?.agentId;
281+
let sessionAgentId = catalogAgentId ?? explicitlyRequestedAgent.agentId;
288282
let sessionWorktree: Awaited<ReturnType<typeof managedWorktrees.create>> | undefined;
289283
const sessionExecCwd = requestedExecNode ? requestedCwd : undefined;
290284
let sessionCwd = requestedExecNode ? undefined : (projectRoot ?? requestedCwd);
@@ -298,11 +292,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
298292
requestedProjectId,
299293
sessionCwd,
300294
sessionKey,
301-
targetAgentId: normalizeAgentId(
302-
sessionAgentId ??
303-
parseAgentSessionKey(sessionKey ?? "")?.agentId ??
304-
explicitlyRequestedAgent.agentId,
305-
),
295+
targetAgentId: sessionAgentId,
306296
});
307297
if (!preparedRoot.ok) {
308298
respond(false, undefined, preparedRoot.error);
@@ -314,11 +304,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
314304
// Workspace-contained cwd and registry-authorized projects stay at operator.write;
315305
// arbitrary host paths still require operator.admin before reaching this block.
316306
const explicitKey = explicitlyRequestedKey;
317-
const agentId = normalizeAgentId(
318-
explicitlyRequestedAgent.agentId ??
319-
normalizeOptionalString(p.agentId) ??
320-
parseAgentSessionKey(explicitKey)?.agentId,
321-
);
307+
const agentId = explicitlyRequestedAgent.agentId;
322308
let targetKey = explicitKey;
323309
let preservesUnspecifiedKey = false;
324310
if (
@@ -336,9 +322,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
336322
const parent = loadGatewaySessionEntryReadOnly(parentSessionKey, {
337323
agentId: parentRequestedAgent.agentId,
338324
});
339-
const parentAgentId = normalizeAgentId(
340-
parentRequestedAgent.agentId ?? resolveSessionStoreAgentId(cfg, parent.canonicalKey),
341-
);
325+
const parentAgentId = parentRequestedAgent.agentId;
342326
if (
343327
parent.entry?.sessionId &&
344328
parent.canonicalKey === resolveAgentMainSessionKey({ cfg, agentId: parentAgentId })
@@ -518,11 +502,7 @@ export const sessionCreateHandlers: GatewayRequestHandlers = {
518502
ADMIN_SCOPE,
519503
clientScopes,
520504
).allowed;
521-
const modelCatalogAgentId = normalizeAgentId(
522-
sessionAgentId ??
523-
parseAgentSessionKey(sessionKey ?? "")?.agentId ??
524-
explicitlyRequestedAgent.agentId,
525-
);
505+
const modelCatalogAgentId = sessionAgentId;
526506
if (!authority.ensureActive()) {
527507
return;
528508
}

‎src/gateway/server.sessions.create.test.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -748,6 +748,30 @@ test("incognito webchat rejects a vanished non-default-agent session before disp
748748
}
749749
});
750750

751+
test("createGatewaySession rejects explicit and key-derived unconfigured creation owners", async () => {
752+
const { createGatewaySession } = await import("./session-create-service.js");
753+
const cfg = { agents: { entries: { ops: { default: true } } } };
754+
const prepareLifecycle = vi.fn();
755+
756+
for (const { owner, message } of [
757+
{ owner: { agentId: "main" }, message: 'Unknown agent id "main"' },
758+
{
759+
owner: { key: "agent:main:dashboard:unconfigured-owner" },
760+
message: 'Unknown agent id "main"',
761+
},
762+
{ owner: { agentId: " " }, message: 'Unknown agent id " "' },
763+
]) {
764+
await expect(
765+
createGatewaySession({ cfg, ...owner, commandSource: "test", prepareLifecycle }),
766+
).resolves.toMatchObject({
767+
ok: false,
768+
error: { code: "INVALID_REQUEST", message },
769+
});
770+
}
771+
772+
expect(prepareLifecycle).not.toHaveBeenCalled();
773+
});
774+
751775
test("createGatewaySession rechecks admin scope after incognito inheritance resolves", async () => {
752776
await createSessionStoreDir();
753777
try {
@@ -2879,6 +2903,7 @@ test("sessions.create rejects worktrees for agent workspaces without a commit",
28792903

28802904
test("sessions.create stores dashboard model, thinking, and parent linkage, and creates a transcript", async () => {
28812905
const { storePath } = await createSessionStoreDir();
2906+
testState.agentsConfig = { list: [{ id: "main", default: true }, { id: "ops" }] };
28822907
agentDiscoveryMock.enabled = true;
28832908
agentDiscoveryMock.models = [{ id: "gpt-test-a", name: "A", provider: "openai" }];
28842909
await writeSessionStore({
@@ -3737,6 +3762,7 @@ test("sessions.create resolves the current default instead of inherited runtime
37373762

37383763
test("sessions.create accepts an explicit key for persistent dashboard sessions", async () => {
37393764
await createSessionStoreDir();
3765+
testState.agentsConfig = { list: [{ id: "main", default: true }, { id: "ops-agent" }] };
37403766

37413767
const key = "agent:ops-agent:dashboard:direct:subagent-orchestrator";
37423768
const created = await directSessionReq<{
@@ -4120,6 +4146,8 @@ test("sessions.create adopting an existing key does not restamp node provenance"
41204146

41214147
test("sessions.create scopes the main alias to the requested agent", async () => {
41224148
const { storePath } = await createSessionStoreDir();
4149+
testState.agentsConfig = { list: [{ id: "main", default: true }, { id: "longmemeval" }] };
4150+
testState.agentConfig = { sessionStore: { agentId: "longmemeval" } };
41234151

41244152
const created = await directSessionReq<{
41254153
key?: string;
@@ -4132,7 +4160,7 @@ test("sessions.create scopes the main alias to the requested agent", async () =>
41324160
agentId: "longmemeval",
41334161
});
41344162

4135-
expect(created.ok).toBe(true);
4163+
expect(created.ok, JSON.stringify(created.error)).toBe(true);
41364164
expect(created.payload?.key).toBe("agent:longmemeval:main");
41374165
expect(created.payload?.entry).not.toHaveProperty("sessionFile");
41384166

@@ -4197,6 +4225,8 @@ test("sessions.create replaces a dead main entry with a fresh session id", async
41974225

41984226
test("sessions.create preserves global and unknown sentinel keys", async () => {
41994227
const { storePath } = await createSessionStoreDir();
4228+
testState.agentsConfig = { list: [{ id: "main", default: true }, { id: "longmemeval" }] };
4229+
testState.agentConfig = { sessionStore: { agentId: "longmemeval" } };
42004230

42014231
const globalCreated = await directSessionReq<{
42024232
key?: string;
@@ -4209,7 +4239,7 @@ test("sessions.create preserves global and unknown sentinel keys", async () => {
42094239
agentId: "longmemeval",
42104240
});
42114241

4212-
expect(globalCreated.ok).toBe(true);
4242+
expect(globalCreated.ok, JSON.stringify(globalCreated.error)).toBe(true);
42134243
expect(globalCreated.payload?.key).toBe("global");
42144244
expect(globalCreated.payload?.entry).not.toHaveProperty("sessionFile");
42154245

@@ -4646,6 +4676,7 @@ test("sessions.create allows plugin runtimes to link their own parent session",
46464676

46474677
test("sessions.create rejects unknown parentSessionKey", async () => {
46484678
await createSessionStoreDir();
4679+
testState.agentsConfig = { list: [{ id: "main", default: true }, { id: "ops" }] };
46494680

46504681
const created = await directSessionReq("sessions.create", {
46514682
agentId: "ops",

‎src/gateway/server.sessions.delete-worktree-lifecycle.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,75 @@ async function initializeRemoteBackedGitWorkspace(root: string): Promise<string>
5353
return await fs.realpath(workspace);
5454
}
5555

56+
test("sessions.create only allocates worktrees for lifecycle-manageable agent owners", async () => {
57+
const openClawState = await createOpenClawTestState({
58+
layout: "state-only",
59+
prefix: "openclaw-create-worktree-agent-owner-",
60+
});
61+
const workspace = await initializeRemoteBackedGitWorkspace(openClawState.root);
62+
closeOpenClawStateDatabaseForTest();
63+
testState.agentConfig = { workspace };
64+
testState.agentsConfig = { list: [{ id: "ops", default: true }] };
65+
const { storePath } = await createSessionStoreDir();
66+
const adminClient = { connect: { scopes: ["operator.admin"] } } as never;
67+
const allocatedWorktreeIds = new Set<string>();
68+
const createWorktree = vi.spyOn(managedWorktrees, "create");
69+
try {
70+
for (const owner of [{ agentId: "main" }, { key: "agent:main:dashboard:unconfigured-owner" }]) {
71+
const created = await directSessionReq<{
72+
key: string;
73+
worktree: { id: string };
74+
}>("sessions.create", { ...owner, worktree: true }, { client: adminClient });
75+
if (created.payload?.worktree.id) {
76+
allocatedWorktreeIds.add(created.payload.worktree.id);
77+
}
78+
79+
expect(created).toMatchObject({
80+
ok: false,
81+
error: { code: "INVALID_REQUEST", message: 'Unknown agent id "main"' },
82+
});
83+
if (owner.key) {
84+
expect(
85+
loadSessionEntry({ agentId: "main", sessionKey: owner.key, storePath }),
86+
).toBeUndefined();
87+
}
88+
expect(createWorktree).not.toHaveBeenCalled();
89+
}
90+
91+
for (const owner of [{ agentId: "ops" }, {}]) {
92+
const created = await directSessionReq<{
93+
key: string;
94+
worktree: { id: string; path: string };
95+
}>("sessions.create", { ...owner, worktree: true }, { client: adminClient });
96+
if (created.payload?.worktree.id) {
97+
allocatedWorktreeIds.add(created.payload.worktree.id);
98+
}
99+
expect(created).toMatchObject({
100+
ok: true,
101+
payload: { key: expect.stringMatching(/^agent:ops:/) },
102+
});
103+
104+
const worktree = created.payload!.worktree;
105+
await expect(
106+
directSessionReq("sessions.delete", { key: created.payload!.key, agentId: "ops" }),
107+
).resolves.toMatchObject({ ok: true, payload: { deleted: true } });
108+
await expect(fs.access(worktree.path)).rejects.toThrow();
109+
allocatedWorktreeIds.delete(worktree.id);
110+
}
111+
} finally {
112+
createWorktree.mockRestore();
113+
for (const id of allocatedWorktreeIds) {
114+
if (getRegistryWorktree(process.env, id)?.removedAt === undefined) {
115+
await managedWorktrees.remove({ id, reason: "test-cleanup", allowSnapshotLoss: true });
116+
}
117+
}
118+
closeOpenClawStateDatabaseForTest();
119+
testState.agentConfig = undefined;
120+
testState.agentsConfig = undefined;
121+
await openClawState.cleanup();
122+
}
123+
});
124+
56125
test("sessions.delete snapshots and removes session worktrees", async () => {
57126
const openClawState = await createOpenClawTestState({
58127
layout: "state-only",

‎src/gateway/session-create-service.ts‎

Lines changed: 13 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -345,44 +345,21 @@ export async function createGatewaySession(params: {
345345
const requestedKey = normalizeOptionalString(params.key);
346346
const parentSessionKey = normalizeOptionalString(params.parentSessionKey);
347347
const projectId = normalizeOptionalString(params.projectId);
348-
const explicitAgentId = normalizeOptionalString(params.agentId);
348+
const explicitAgentId = params.agentId;
349+
const normalizedExplicitAgentId = normalizeOptionalString(explicitAgentId);
349350
const explicitKeyAgentId = parseAgentSessionKey(requestedKey)?.agentId;
350-
if (
351-
explicitAgentId &&
352-
explicitKeyAgentId &&
353-
normalizeAgentId(explicitKeyAgentId) !== normalizeAgentId(explicitAgentId)
354-
) {
355-
return {
356-
ok: false,
357-
error: errorShape(
358-
ErrorCodes.INVALID_REQUEST,
359-
`sessions.create key agent (${explicitKeyAgentId}) does not match agentId (${normalizeAgentId(explicitAgentId)})`,
360-
),
361-
};
362-
}
363-
const requestedKeyAgent = requestedKey
364-
? resolveRequestedSessionAgentId(params.cfg, requestedKey, explicitAgentId, {
365-
allowUnconfiguredExplicitAgent: true,
366-
})
367-
: undefined;
368-
if (requestedKeyAgent && !requestedKeyAgent.ok) {
369-
return requestedKeyAgent;
370-
}
371-
// Resolve the main alias under an explicit selection before compatibility ownership.
372-
const implicitSelectionKey = explicitAgentId
373-
? `agent:${normalizeAgentId(explicitAgentId)}:main`
374-
: "main";
375-
const implicitAgent = requestedKeyAgent
376-
? undefined
377-
: resolveRequestedSessionAgentId(params.cfg, implicitSelectionKey, explicitAgentId, {
378-
allowUnconfiguredExplicitAgent: true,
379-
});
380-
if (implicitAgent && !implicitAgent.ok) {
381-
return implicitAgent;
382-
}
383-
const agentId = normalizeAgentId(
384-
explicitAgentId ?? requestedKeyAgent?.agentId ?? implicitAgent?.agentId,
351+
const selectedAgent = resolveRequestedSessionAgentId(
352+
params.cfg,
353+
requestedKey ??
354+
(normalizedExplicitAgentId
355+
? `agent:${normalizeAgentId(normalizedExplicitAgentId)}:main`
356+
: "main"),
357+
explicitAgentId ?? explicitKeyAgentId,
385358
);
359+
if (!selectedAgent.ok) {
360+
return selectedAgent;
361+
}
362+
const agentId = selectedAgent.agentId;
386363
const catalogModel = normalizeOptionalString(params.catalogTarget?.model);
387364
const catalogAgentRuntime = normalizeOptionalAgentRuntimeId(params.catalogTarget?.agentRuntime);
388365
const catalogPluginOwnerId = normalizeOptionalString(params.catalogTarget?.pluginOwnerId);

‎src/gateway/session-request-agent.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ export function resolveRequestedSessionAgentId(
3636
cfg: OpenClawConfig,
3737
key: string,
3838
explicitAgentId?: string,
39-
options?: { allowUnconfiguredExplicitAgent?: boolean },
4039
): RequestedSessionAgentIdResolution {
4140
const parsed = parseAgentSessionKey(key.trim());
4241
const configuredAgentIds = listAgentIds(cfg);
@@ -49,11 +48,7 @@ export function resolveRequestedSessionAgentId(
4948
};
5049
}
5150
const normalizedRequestedAgentId = normalizedRequest?.value;
52-
if (
53-
normalizedRequestedAgentId &&
54-
!options?.allowUnconfiguredExplicitAgent &&
55-
!configuredAgentIds.includes(normalizedRequestedAgentId)
56-
) {
51+
if (normalizedRequestedAgentId && !configuredAgentIds.includes(normalizedRequestedAgentId)) {
5752
return {
5853
ok: false,
5954
error: errorShape(ErrorCodes.INVALID_REQUEST, `Unknown agent id "${explicitAgentId}"`),
@@ -64,11 +59,7 @@ export function resolveRequestedSessionAgentId(
6459
const keyIsGlobalMainAlias =
6560
cfg.session?.scope === "global" &&
6661
(parsed.rest === "main" || parsed.rest === normalizeMainKey(cfg.session?.mainKey));
67-
if (
68-
keyIsGlobalMainAlias &&
69-
!options?.allowUnconfiguredExplicitAgent &&
70-
!configuredAgentIds.includes(keyAgentId)
71-
) {
62+
if (keyIsGlobalMainAlias && !configuredAgentIds.includes(keyAgentId)) {
7263
return {
7364
ok: false,
7465
error: errorShape(ErrorCodes.INVALID_REQUEST, `Unknown agent id "${parsed.agentId}"`),

0 commit comments

Comments
 (0)