diff --git a/doc/LOW-TRUST-PRESETS.md b/doc/LOW-TRUST-PRESETS.md index bead89bc5ea..1ad5b3aec7b 100644 --- a/doc/LOW-TRUST-PRESETS.md +++ b/doc/LOW-TRUST-PRESETS.md @@ -147,6 +147,15 @@ runtime boundary: - inline sensitive environment values such as API keys and tokens are rejected - workspace runtime-service mutations are denied unless the boundary explicitly grants the `runtime.manage` tool class +- company-wide `runtime:manage` stays denied, but the assignee may use + `set_task_monitor` to schedule or clear a self-wake on its own in-boundary + task; monitors that create recovery tasks or escalate to the board are denied +- that self-wake is allowed only when the agent, project and task policies + alone resolve the same low-trust boundary as the run, so the woken run keeps + the same limits; a boundary carried only by the run snapshot is denied +- the assignee cannot clear or replace a monitor it does not own: a + board-scheduled, recovery, escalation or provider-quota monitor still needs + `runtime:manage` When the task's project has no configured workspace and no layer specifies a workspace strategy, sandbox execution uses a private directory for that company diff --git a/server/src/__tests__/issue-monitor-scheduler.test.ts b/server/src/__tests__/issue-monitor-scheduler.test.ts index 75b3973a6eb..f08db88886d 100644 --- a/server/src/__tests__/issue-monitor-scheduler.test.ts +++ b/server/src/__tests__/issue-monitor-scheduler.test.ts @@ -31,6 +31,7 @@ import { heartbeatService } from "../services/heartbeat.ts"; import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.ts"; import { normalizeIssueExecutionPolicy, parseIssueExecutionState } from "../services/issue-execution-policy.ts"; import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; +import { resolveAndRetainRunTrustPreset } from "../services/run-trust-preset.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; // These process fixtures do not consume skills. Keep the real scheduler, @@ -406,6 +407,41 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { expect(wakes.filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1); }); + it("keeps low-trust limits on the run a reviewer's self-wake starts", async () => { + const { companyId, issueId, agentId } = await seedFixture(); + const runId = randomUUID(); + const policy = { trustPreset: "low_trust_review", authorizationPolicy: { trustPreset: "low_trust_review", + trustBoundary: { mode: "low_trust_review", companyId, rootIssueId: issueId } } }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, + runtimeMode: "native", status: "running", contextSnapshot: { issueId, executionPolicy: policy } }); + await db.update(issues).set({ executionRunId: runId, executionPolicy: null, executionState: null, + monitorNextCheckAt: null, monitorNotes: null, monitorScheduledBy: null }).where(eq(issues.id, issueId)); + const authority = new PaperclipRunnerToolAuthority(db, { companyId, issueId, agentId, runId }); + const monitor = { nextCheckAt: new Date(Date.now() + 60_000).toISOString(), notes: "Check the review again." }; + const call = (idempotencyKey: string) => authority.execute({ + tool: "set_task_monitor", callId: randomUUID(), arguments: { idempotencyKey, monitor }, + }); + try { + await expect(call("run-only-trust")).rejects.toThrow(/runtime:manage/); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.monitorNextCheckAt).toBeNull(); + await db.update(issues).set({ executionPolicy: policy }).where(eq(issues.id, issueId)); + await expect(call("task-trust")).resolves.toMatchObject({ monitor: { status: "scheduled" } }); + } finally { + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId)); + await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, issueId)); + } + expect((await heartbeatService(db).tickTimers(new Date(Date.parse(monitor.nextCheckAt) + 1_000))).enqueued).toBe(1); + const [woken] = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))) + .filter(run => run.id !== runId); + expect(woken).toBeDefined(); + await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, woken!.id)); + const [agent] = await db.select().from(agents).where(eq(agents.id, agentId)); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const retained = await resolveAndRetainRunTrustPreset(db, { companyId, agentId, runId: woken!.id, + agent: { companyId, permissions: agent!.permissions }, issue: { companyId, executionPolicy: issue!.executionPolicy } }); + expect(retained.trustPreset).toMatchObject({ kind: "low_trust_review", boundary: { rootIssueId: issueId } }); + }); + it.each(["replaced", "cleared", "reassigned", "completed"] as const)("fences a monitor %s after claim but before wake admission", async (change) => { const { companyId, issueId, agentId } = await seedFixture(); const replacementAt = new Date("2026-04-11T13:30:00.000Z"); diff --git a/server/src/services/issue-monitors.ts b/server/src/services/issue-monitors.ts index 66baba56502..960deeb43af 100644 --- a/server/src/services/issue-monitors.ts +++ b/server/src/services/issue-monitors.ts @@ -28,32 +28,46 @@ export function applyActorMonitorScheduledBy( ); } +type SelfWakeMonitor = { recoveryPolicy?: string | null; serviceName?: string | null; scheduledBy?: string | null }; + +function isSelfWakeMonitor(monitor: SelfWakeMonitor | null) { + return !monitor || ((monitor.recoveryPolicy ?? "wake_owner") === "wake_owner" + && monitor.serviceName !== PROVIDER_QUOTA_MONITOR_SERVICE_NAME + && (monitor.scheduledBy ?? "assignee") === "assignee"); +} + export async function assertCanManageIssueMonitor( accessSvc: Pick, "decide">, req: { actor: AuthorizationActor }, companyId: string, assigneeAgentId: string | null, monitorChanged: boolean, + ownTask?: { monitor: SelfWakeMonitor | null; existing: SelfWakeMonitor | null }, ) { if (!monitorChanged) return; if (req.actor.type === "board") return; + const isAssignee = + req.actor.type === "agent" && + !!req.actor.agentId && + req.actor.agentId === assigneeAgentId; const runtimeDecision = await accessSvc.decide({ actor: req.actor, action: "runtime:manage", resource: { type: "company", companyId }, }); - if (!runtimeDecision.allowed) { + const ownTaskSelfWake = + ownTask && + isAssignee && + runtimeDecision.reason === "deny_low_trust_boundary" && + isSelfWakeMonitor(ownTask.monitor) && + isSelfWakeMonitor(ownTask.existing); + if (!runtimeDecision.allowed && !ownTaskSelfWake) { throw forbidden( runtimeDecision.explanation, authorizationDeniedDetails(runtimeDecision), ); } - if ( - req.actor.type === "agent" && - req.actor.agentId && - req.actor.agentId === assigneeAgentId - ) - return; + if (isAssignee) return; throw forbidden( "Only the assignee agent or a board user can manage issue monitors", ); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 7469f505268..9a745b79f6f 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -2574,7 +2574,7 @@ export class PaperclipRunnerToolAuthority { let replayed = false; let replayStatus: string | null = null; let replayMonitor: ReturnType | null = null; - const authorizeTarget = async (tx: Db, context: { run: typeof heartbeatRuns.$inferSelect }) => { + const authorizeTarget = async (tx: Db, context: { run: typeof heartbeatRuns.$inferSelect; actor: typeof agents.$inferSelect }) => { // A second owned task may itself be writing another task: fail on lock // contention instead of taking opposite issue/run locks and deadlocking. const [target] = await tx.select().from(issues).where(and( @@ -2590,7 +2590,17 @@ export class PaperclipRunnerToolAuthority { } }); if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision)); } - await assertCanManageIssueMonitor(access, { actor }, target.companyId, target.assigneeAgentId, true); + const project = target.projectId + ? (await tx.select().from(projects).where(and(eq(projects.id, target.projectId), eq(projects.companyId, this.binding.companyId))))[0] ?? null + : null; + const taskSources = { companyId: this.binding.companyId, agent: context.actor, project, issue: target }; + const taskTrust = resolveCoreTrustPreset(taskSources); + const runTrust = resolveCoreTrustPreset({ ...taskSources, + run: { companyId: this.binding.companyId, executionPolicy: context.run.contextSnapshot?.executionPolicy } }); + const wakeKeepsTrust = taskTrust.kind === "low_trust_review" && runTrust.kind === "low_trust_review" + && canonicalJson(taskTrust.boundary) === canonicalJson(runTrust.boundary); + await assertCanManageIssueMonitor(access, { actor }, target.companyId, target.assigneeAgentId, true, + wakeKeepsTrust ? { monitor: input.monitor, existing: normalizeIssueExecutionPolicy(target.executionPolicy)?.monitor ?? null } : undefined); if (target.assigneeAgentId !== this.binding.agentId || target.assigneeUserId || !["in_progress", "in_review"].includes(target.status)) { throw forbidden("Monitors require an in-progress or in-review task assigned to this agent"); diff --git a/server/src/services/native-runtime/task-monitor.integration.test.ts b/server/src/services/native-runtime/task-monitor.integration.test.ts index 32c20c9e9a6..0b1c488631e 100644 --- a/server/src/services/native-runtime/task-monitor.integration.test.ts +++ b/server/src/services/native-runtime/task-monitor.integration.test.ts @@ -115,6 +115,39 @@ describeEmbeddedPostgres("native task monitors", () => { await expect(authority.execute({ tool: "set_task_monitor", callId: randomUUID(), arguments: { idempotencyKey: "review", monitor: value.monitor } })).rejects.toThrow("review run"); }); + it("lets a low-trust reviewer schedule a self-wake on its own task without company runtime access", async () => { + const value = await fixture(), otherId = randomUUID(); + const policy = { trustPreset: "low_trust_review", authorizationPolicy: { trustPreset: "low_trust_review", + trustBoundary: { mode: "low_trust_review", companyId: value.companyId, rootIssueId: value.issueId } } }; + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: value.issueId, executionPolicy: policy } }) + .where(eq(heartbeatRuns.id, value.runId)); + await db.update(issues).set({ executionPolicy: policy }).where(eq(issues.id, value.issueId)); + await db.insert(issues).values({ id: otherId, companyId: value.companyId, + title: "Owned task outside the review boundary", status: "in_progress", assigneeAgentId: value.agentId }); + await expect(value.call({ idempotencyKey: "review-check", monitor: value.monitor })) + .resolves.toMatchObject({ taskId: value.issueId, monitor: { status: "scheduled" }, replayed: false }); + expect((await value.read()).monitorNextCheckAt?.toISOString()).toBe(value.monitor.nextCheckAt); + for (const recoveryPolicy of ["create_recovery_issue", "escalate_to_board"]) { + await expect(value.call({ idempotencyKey: `review-${recoveryPolicy}`, monitor: { ...value.monitor, recoveryPolicy } })) + .rejects.toThrow(/runtime:manage/); + } + await expect(value.call({ taskId: otherId, idempotencyKey: "review-other", monitor: value.monitor })).rejects.toThrow(); + expect((await db.select().from(issues).where(eq(issues.id, otherId)))[0]!.monitorNextCheckAt).toBeNull(); + await expect(value.call({ idempotencyKey: "review-clear", monitor: null })) + .resolves.toMatchObject({ taskId: value.issueId, replayed: false }); + expect((await value.read()).monitorNextCheckAt).toBeNull(); + for (const existing of [{ scheduledBy: "board", recoveryPolicy: "escalate_to_board" }, + { scheduledBy: "assignee", recoveryPolicy: "create_recovery_issue" }, { scheduledBy: "board" }, + { scheduledBy: "assignee", serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME }]) { + await db.update(issues).set({ executionPolicy: { ...policy, monitor: { ...value.monitor, ...existing } }, + monitorNextCheckAt: new Date(value.monitor.nextCheckAt) }).where(eq(issues.id, value.issueId)); + for (const monitor of [null, value.monitor]) { + await expect(value.call({ idempotencyKey: `review-replace-${randomUUID()}`, monitor })).rejects.toThrow(/runtime:manage/); + } + expect((await value.read()).monitorNextCheckAt?.toISOString()).toBe(value.monitor.nextCheckAt); + } + }); + it("rechecks the responsible user's permissions before mutation and replay", async () => { const value = await fixture(), userId = randomUUID(); await db.insert(authUsers).values({ id: userId, name: "Owner", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });