Skip to content

Commit 126240a

Browse files
committed
fix(session): add authorization and race condition guards to cancelBackgroundTask (#55)
1 parent ea5296e commit 126240a

3 files changed

Lines changed: 59 additions & 11 deletions

File tree

‎packages/opencode/src/session/index.ts‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -501,14 +501,16 @@ export namespace Session {
501501
wakeupInProgress.delete(sessionID)
502502
}
503503

504-
export function cancelBackgroundTask(id: string): boolean {
504+
function cancelBackgroundTask(id: string): boolean {
505505
const task = pendingBackgroundTasks.get(id)
506506
if (!task) return false
507507

508+
const existing = backgroundTaskResults.get(id)
509+
if (existing && existing.status !== "running") return false
510+
508511
const metadata = pendingTaskMetadata.get(id)
509512
const startTime = metadata?.start_time ?? Date.now()
510513

511-
// Release slot BEFORE deleting metadata to prevent permanent slot leak
512514
if (metadata?.release_slot) {
513515
try {
514516
metadata.release_slot()
@@ -530,12 +532,13 @@ export namespace Session {
530532
cancelled: true,
531533
}
532534

533-
const existing = backgroundTaskResults.get(id)
534535
if (existing) {
535-
existing.status = "failed"
536-
existing.error = "Task was cancelled"
537-
existing.cancelled = true
538-
existing.time.completed = Date.now()
536+
if (existing.status === "running") {
537+
existing.status = "failed"
538+
existing.error = "Task was cancelled"
539+
existing.cancelled = true
540+
existing.time.completed = Date.now()
541+
}
539542
} else {
540543
backgroundTaskResults.set(id, result)
541544
if (backgroundTaskResults.size > MAX_STORED_TASK_RESULTS) {
@@ -553,8 +556,11 @@ export namespace Session {
553556
return true
554557
}
555558

556-
export function tryCancel(taskId: string): {
557-
status: "cancelled" | "not_found" | "already_completed"
559+
export function tryCancel(
560+
taskId: string,
561+
callerSessionID: string,
562+
): {
563+
status: "cancelled" | "not_found" | "already_completed" | "unauthorized"
558564
message?: string
559565
} {
560566
const result = backgroundTaskResults.get(taskId)
@@ -565,6 +571,13 @@ export namespace Session {
565571
}
566572
}
567573

574+
if (result.metadata?.session_id !== callerSessionID) {
575+
return {
576+
status: "unauthorized",
577+
message: `Task ${taskId} belongs to a different session and cannot be cancelled`,
578+
}
579+
}
580+
568581
if (result.status !== "running") {
569582
return {
570583
status: "already_completed",

‎packages/opencode/src/tool/cancel_task.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import DESCRIPTION from "./cancel_task.txt"
33
import z from "zod"
44
import { Session } from "../session"
55

6-
type CancellationStatus = "cancelled" | "not_found" | "already_completed"
6+
type CancellationStatus = "cancelled" | "not_found" | "already_completed" | "unauthorized"
77

88
interface CancelTaskResult {
99
task_id: string
@@ -27,7 +27,7 @@ export const CancelTaskTool = Tool.define<z.ZodObject<{ task_id: z.ZodString }>,
2727
.describe("The ID of the background task to cancel"),
2828
}),
2929
async execute(params, ctx) {
30-
const result = Session.tryCancel(params.task_id)
30+
const result = Session.tryCancel(params.task_id, ctx.sessionID)
3131

3232
const response: CancelTaskResult = {
3333
task_id: params.task_id,

‎packages/opencode/test/tool/cancel_task.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,41 @@ describe("tool.cancel_task", () => {
9393
})
9494
})
9595

96+
test("returns unauthorized when trying to cancel another session's task", async () => {
97+
await using tmp = await tmpdir({ git: true })
98+
await Instance.provide({
99+
directory: tmp.path,
100+
fn: async () => {
101+
const tool = await CancelTaskTool.init()
102+
const taskId = "test-task-other-session"
103+
104+
const promise = new Promise<string>((resolve) => {
105+
setTimeout(() => resolve("Should not be cancelled"), 10000)
106+
})
107+
108+
Session.trackBackgroundTask(taskId, promise, undefined, {
109+
agent_type: "test",
110+
description: "Test task",
111+
session_id: "other-session-id",
112+
start_time: Date.now(),
113+
})
114+
115+
await new Promise((r) => setTimeout(r, 50))
116+
117+
const result = await tool.execute({ task_id: taskId }, ctx)
118+
119+
const output = JSON.parse(result.output)
120+
expect(output.status).toBe("unauthorized")
121+
expect(output.task_id).toBe(taskId)
122+
expect(output.message).toContain("different session")
123+
expect(result.metadata.status).toBe("unauthorized")
124+
125+
const taskResult = Session.getBackgroundTaskResult(taskId)
126+
expect(taskResult?.status).toBe("running")
127+
},
128+
})
129+
})
130+
96131
test("validates input with Zod schema", async () => {
97132
await Instance.provide({
98133
directory: "/tmp/test",

0 commit comments

Comments
 (0)