From 64aca2a59ef4fdbb2a9b204f9232624928177c7c Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 30 Nov 2026 16:15:54 -0600 Subject: [PATCH] fix(issues): enforce scope guard on child/plan routes and update golden Reuse parseScopeFilter in route scope parsing, enforce agent scope='board' restriction across POST /issues/:id/children, POST /issues/:id/accepted-plan-decompositions, and issueService.create, update issue-detail-response.json golden for the new scope field, remove unused ISSUE_SCOPES import, and note the contract re-backfill requirement in migration 0511. Co-Authored-By: Paperclip --- .../src/migrations/0511_simple_the_hunter.sql | 2 +- .../fixtures/issue-detail-response.json | 1 + .../__tests__/issue-scope-visibility.test.ts | 36 +++++++++++-- server/src/routes/issues.ts | 50 ++++++++++++------- server/src/services/issues.ts | 16 ++++-- .../runner-e2e/source-sdk-public-inputs.json | 10 ++-- 6 files changed, 83 insertions(+), 32 deletions(-) diff --git a/packages/db/src/migrations/0511_simple_the_hunter.sql b/packages/db/src/migrations/0511_simple_the_hunter.sql index bff264f5948..574520de18a 100644 --- a/packages/db/src/migrations/0511_simple_the_hunter.sql +++ b/packages/db/src/migrations/0511_simple_the_hunter.sql @@ -1,4 +1,4 @@ --- paperclip:migration-compat online_compatible: adds issues.scope with constant default 'board', backfills existing conversation and agent-created rows in bounded primary-key batches, adds issues_scope_check as NOT VALID then validates under SHARE UPDATE EXCLUSIVE, and builds both scope indexes CONCURRENTLY. Every statement is idempotent because this file runs outside a transaction; issues_conversation_scope_check is deferred to a follow-up contract migration so rolling deploys with previous writers do not fail 1:1 chat inserts. +-- paperclip:migration-compat online_compatible: adds issues.scope with constant default 'board', backfills existing conversation and agent-created rows in bounded primary-key batches, adds issues_scope_check as NOT VALID then validates under SHARE UPDATE EXCLUSIVE, and builds both scope indexes CONCURRENTLY. Every statement is idempotent because this file runs outside a transaction; issues_conversation_scope_check is deferred to a follow-up contract migration (which must re-run the conversation scope='chat' backfill in bounded batches before ADD/VALIDATE CONSTRAINT to catch any conversation rows inserted by old writers during rolling deploy). ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "scope" text DEFAULT 'board' NOT NULL;--> statement-breakpoint DO $$ DECLARE diff --git a/server/src/__tests__/fixtures/issue-detail-response.json b/server/src/__tests__/fixtures/issue-detail-response.json index e1d98dc1f95..ae90e4ae173 100644 --- a/server/src/__tests__/fixtures/issue-detail-response.json +++ b/server/src/__tests__/fixtures/issue-detail-response.json @@ -17,6 +17,7 @@ "titleNeedsGeneration": false, "description": "Uses [@Detail project](project://)", "status": "in_progress", + "scope": "board", "statusVersion": 0, "lastStatusDecisionId": null, "workMode": "standard", diff --git a/server/src/__tests__/issue-scope-visibility.test.ts b/server/src/__tests__/issue-scope-visibility.test.ts index 82022ac7ea3..3340aa71ede 100644 --- a/server/src/__tests__/issue-scope-visibility.test.ts +++ b/server/src/__tests__/issue-scope-visibility.test.ts @@ -362,8 +362,8 @@ describeEmbeddedPostgres("issues.scope visibility and lifecycle", () => { ).rejects.toMatchObject({ status: 422 }); }); - it("forbids agent actors from forging scope='board' on POST or PATCH", async () => { - const { companyId, userId } = await seedCompanyWithBoardAccess(ctx.db, "Issue Scope Agent Authz"); + it("forbids agent actors from forging scope='board' on POST, child POST, decomposition POST, or PATCH", async () => { + const { companyId, userId, actor: boardActor } = await seedCompanyWithBoardAccess(ctx.db, "Issue Scope Agent Authz"); const [agent] = await ctx.db .insert(agents) .values({ companyId, name: "Caller", role: "engineer", adapterType: "process" }) @@ -385,24 +385,54 @@ describeEmbeddedPostgres("issues.scope visibility and lifecycle", () => { onBehalfOfMemberships: [], } as unknown as Parameters[1]; const agentApp = routeApp(ctx.db, agentActor, issueRoutes); + const boardApp = routeApp(ctx.db, boardActor, issueRoutes); await request(agentApp) .post(`/api/companies/${companyId}/issues`) .send({ title: "Spoofed board task", status: "todo", scope: "board" }) .expect(403); + await request(agentApp) + .post(`/api/issues/${agentTask.id}/children`) + .send({ title: "Spoofed board child", status: "todo", scope: "board" }) + .expect(403); + + await request(agentApp) + .post(`/api/issues/${agentTask.id}/accepted-plan-decompositions`) + .send({ + acceptedPlanRevisionId: randomUUID(), + children: [{ title: "Spoofed plan child", status: "todo", scope: "board" }], + }) + .expect(403); + await request(agentApp) .patch(`/api/issues/${agentTask.id}`) .send({ scope: "board" }) .expect(403); expect((await svc.getById(agentTask.id))?.scope).toBe("agent"); - // A normal agent-created issue defaults to 'agent' cleanly. + // Direct service creation by an agent without handoff provenance also rejects scope='board'. + await expect( + svc.create(companyId, { + title: "Direct service spoof", + status: "todo", + scope: "board", + createdByAgentId: agent!.id, + }), + ).rejects.toMatchObject({ status: 403 }); + + // A normal agent-created issue or child defaults to 'agent' cleanly. const createdByAgent = await request(agentApp) .post(`/api/companies/${companyId}/issues`) .send({ title: "Ordinary agent task", status: "todo" }) .expect(201); expect(createdByAgent.body.scope).toBe("agent"); + + const boardChild = await request(boardApp) + .post(`/api/issues/${agentTask.id}/children`) + .send({ title: "Board child", status: "todo", scope: "board" }) + .expect(201); + expect(boardChild.body.scope).toBe("board"); expect(userId).toBeTruthy(); }); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 82f079c1815..88c1262f205 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -245,6 +245,7 @@ import { routineService, workProductService, } from "../services/index.js"; +import { parseScopeFilter } from "../services/issue-visibility.js"; import { runnerGoalService, RunnerGoalActionError, @@ -3455,20 +3456,33 @@ function parseIssueListScopeQueryParam( if (!entries || entries.some((entry) => typeof entry !== "string")) { return { ok: false, error: `scope must be one of ${ISSUE_SCOPES.join(", ")}` }; } - const scopes = [ - ...new Set( - entries - .flatMap((entry) => entry.split(",")) - .map((scope) => scope.trim()) - .filter(Boolean), - ), - ]; - for (const scope of scopes) { - if (!ISSUE_SCOPES.includes(scope as (typeof ISSUE_SCOPES)[number])) { - return { ok: false, error: `Invalid issue scope '${scope}'; expected one of ${ISSUE_SCOPES.join(", ")}` }; - } + try { + const scopes = parseScopeFilter(entries); + return { ok: true, value: scopes.length > 0 ? scopes.join(",") : undefined }; + } catch (err) { + return { + ok: false, + error: err instanceof Error ? err.message : `scope must be one of ${ISSUE_SCOPES.join(", ")}`, + }; + } +} + +function assertActorMayWriteIssueScope( + req: Request, + requestedScope: unknown, + existingScope?: string | null, +) { + if ( + req.actor.type === "agent" && + requestedScope === "board" && + existingScope !== "board" + ) { + throw forbidden( + existingScope === undefined + ? "Only board users can create issues with scope 'board'" + : "Only board users can promote issues to scope 'board'", + ); } - return { ok: true, value: scopes.length > 0 ? scopes.join(",") : undefined }; } async function coordinateIssueListGet(input: { @@ -13499,9 +13513,7 @@ export function issueRoutes( ); let deduplicationReason: "idempotency_key" | "recent_open_title" | null = null; - if (req.actor.type === "agent" && createBody.scope === "board") { - throw forbidden("Only board users can create issues with scope 'board'"); - } + assertActorMayWriteIssueScope(req, createBody.scope); const createInput = { ...createBody, workspaceSelectionActor: req.actor, @@ -13821,6 +13833,7 @@ export function issueRoutes( ? { assigneeAgentId: normalizedAssigneeAgentId } : {}), }; + assertActorMayWriteIssueScope(req, createBody.scope); // Board users nest freely, and watchdog follow-ups are located by parent. // Other agents build at most parent → child trees: a child of a child is // placed beside it instead (never rejected). @@ -14095,6 +14108,7 @@ export function issueRoutes( ? { assigneeAgentId: normalizedAssigneeAgentId } : {}), }; + assertActorMayWriteIssueScope(req, childBody.scope); requestedChildren.push(childBody); assertNoAgentHostWorkspaceCommandMutation( req, @@ -14916,9 +14930,7 @@ export function issueRoutes( // An authorized agent may restrict a task; widening access remains an owner/admin action. if (req.body.visibility !== undefined && !(req.actor.type === "agent" && req.body.visibility === "private") && !(await resolveManagedIssueForPrivacy(req, res, existing))) return; - if (req.actor.type === "agent" && req.body.scope === "board" && existing.scope !== "board") { - throw forbidden("Only board users can promote issues to scope 'board'"); - } + assertActorMayWriteIssueScope(req, req.body.scope, existing.scope); // MCP task changes cannot stop a run or implicitly decide a pending review. const mcpParticipationChange = req.actor.source === "mcp_oauth" && ["status", "assigneeAgentId", "assigneeUserId", "blockedByIssueIds", "parentId", "projectId"].some(key => req.body[key] !== undefined); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 460388480b6..304ca0eeb84 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -171,7 +171,6 @@ import { deriveDefaultIssueScope, extractAgentMentionIds, extractProjectMentionIds, - ISSUE_SCOPES, issueCommentAuthorTypeSchema, issueCommentMetadataSchema, issueCommentPresentationSchema, @@ -11215,6 +11214,17 @@ export function issueService(db: Db) { .then((rows) => rows.length > 0)); if (!originPublic) originIssueId = null; } + const trustedBoardHandoff = + isExplicitBoardHandoff ?? + Boolean(handoffSource || (runSourceIssueIsConversation && !issueData.parentId)); + if ( + issueData.scope === "board" && + issueData.createdByAgentId != null && + issueData.createdByUserId == null && + !trustedBoardHandoff + ) { + throw forbidden("Only board users or chat handoffs can create issues with scope 'board'"); + } const derivedScope = deriveDefaultIssueScope({ scope: issueData.scope ?? null, conversationAgentId: issueData.conversationAgentId ?? null, @@ -11222,9 +11232,7 @@ export function issueService(db: Db) { createdByAgentId: issueData.createdByAgentId ?? null, createdByUserId: issueData.createdByUserId ?? null, originKind: issueData.originKind ?? "manual", - isExplicitBoardHandoff: - isExplicitBoardHandoff ?? - Boolean(handoffSource || (runSourceIssueIsConversation && !issueData.parentId)), + isExplicitBoardHandoff: trustedBoardHandoff, }); const values = { ...issueData, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index c06f059f4db..fd734d05485 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -237,7 +237,7 @@ "packages/shared/src/connector-availability.ts": "7797798bc989b774e8b6e62748ad689f66ab4193", "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", - "packages/shared/src/constants.ts": "4709afa0716747373733dd68755e10972fca0068", + "packages/shared/src/constants.ts": "de3d7da2b991efaf7f3eb5775af252e4f20d273f", "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", @@ -279,14 +279,14 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "cdfadcb65f541b0d07a0af3c27ad2ec74d62bd08", + "packages/shared/src/index.ts": "159182d500385c0d13c20ff71627e20ba5c0d47f", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", "packages/shared/src/issue-attribution.ts": "9c85194fb8739aeb5d70c8e128db6127a3057569", "packages/shared/src/issue-context-usage.ts": "2de0de824da2e4bce3c248335cdb5694d2a926ce", "packages/shared/src/issue-creation-source.test.ts": "afd00ce1ad8357daf860bc7e8e79340c765805f7", - "packages/shared/src/issue-creation-source.ts": "48bd43f183b1a9f7bc233128ad0fe84c82e04c17", + "packages/shared/src/issue-creation-source.ts": "d8f750a0e70ad3af34f66dacc70ef968e148adad", "packages/shared/src/issue-references.test.ts": "273873e8ecdb41aa9f88f76792880222822e39ee", "packages/shared/src/issue-references.ts": "3516c974d3e1b8e9de3bc204408ea3f130705323", "packages/shared/src/issue-thread-interactions.test.ts": "6f516055744fcedd2e0c06ce82c6a1a019120762", @@ -443,7 +443,7 @@ "packages/shared/src/types/index.ts": "f8eedd126cf46462eed07976d2f9480ad9194428", "packages/shared/src/types/instance.ts": "406736718fa7e8f788d4e963291943d38c16a368", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", - "packages/shared/src/types/issue.ts": "5229e472a1e6da94bc8905d94ba08e6a0faa7ba8", + "packages/shared/src/types/issue.ts": "84699de7b12622743914b66ce6d6d2c91220a64a", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", "packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949", @@ -526,7 +526,7 @@ "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", "packages/shared/src/validators/issue.test.ts": "7584bcce33a933ebcb02695b439767163e5ef61a", - "packages/shared/src/validators/issue.ts": "af96c56dc0a72b0f4c6d152c7ad1df75943231c2", + "packages/shared/src/validators/issue.ts": "6f581b6392cc1005b3dfdb2af2084773721410e8", "packages/shared/src/validators/json-schema.ts": "b6cba6a3f76b49afce1c7dc1c2f086ab946c6133", "packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d", "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830",