mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
fix(issues): tighten scope authz, backfill, and visibility helper
Match isAgentCreatedIssue in the 0511 backfill (include created_by_user_id IS NULL), extract surfaceScopeCondition into issue-visibility.ts, let explicit scope filters override includeAgentCreatedTasks=false, reject scope='chat' on non-conversation issues, and forbid agent actors from setting scope='board' on POST/PATCH. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
926c67e569
commit
ca94323056
6 files changed
+148
-36
No files matched your search
+2
-2
@@ -106,7 +106,7 @@ POST /api/companies/{companyId}/issues
|
||||
}
|
||||
```
|
||||
|
||||
`scope` is optional (`board` | `channel` | `agent` | `chat`). When omitted, the server derives `chat` for 1:1 conversations, `board` for manual human issues and explicit chat-to-board handoffs, and `agent` for agent-created or automated issues. Passing a non-`chat` scope on a 1:1 conversation returns `422`.
|
||||
`scope` is optional (`board` | `channel` | `agent` | `chat`). When omitted, the server derives `chat` for 1:1 conversations, `board` for manual human issues and explicit chat-to-board handoffs, and `agent` for agent-created or automated issues. Passing a non-`chat` scope on a 1:1 conversation or `scope: "chat"` on a non-conversation issue returns `422`. Agent actors cannot pass `scope: "board"` directly (`403`).
|
||||
|
||||
## Update Issue
|
||||
|
||||
@@ -121,7 +121,7 @@ Headers: X-Paperclip-Run-Id: {runId}
|
||||
|
||||
The optional `comment` field adds a comment in the same call. For execution-policy review or approval decisions, the decision comment must be included in this same `PATCH`; a prior `POST /api/issues/{issueId}/comments` does not satisfy the stage decision guard.
|
||||
|
||||
Updatable fields: `title`, `description`, `status`, `scope`, `priority`, `assigneeAgentId`, `projectId`, `goalId`, `parentId`, `billingCode`. Existing 1:1 conversation issues must keep `scope: "chat"` (other values return `422`).
|
||||
Updatable fields: `title`, `description`, `status`, `scope`, `priority`, `assigneeAgentId`, `projectId`, `goalId`, `parentId`, `billingCode`. Existing 1:1 conversation issues must keep `scope: "chat"` and non-conversation issues cannot be set to `scope: "chat"` (`422`). Agent actors cannot promote issues to `scope: "board"` (`403`).
|
||||
|
||||
For `PATCH /api/issues/{issueId}`, `assigneeAgentId` may be either the agent UUID or the agent shortname/urlKey within the same company.
|
||||
|
||||
|
||||
@@ -19,7 +19,11 @@ BEGIN
|
||||
SET "scope" = CASE
|
||||
WHEN i."conversation_agent_id" IS NOT NULL THEN 'chat'
|
||||
WHEN i."scope" = 'board'
|
||||
AND (i."created_by_agent_id" IS NOT NULL OR i."origin_kind" NOT IN ('manual', 'onboarding_first_task'))
|
||||
AND (
|
||||
i."created_by_agent_id" IS NOT NULL
|
||||
OR i."created_by_user_id" IS NULL
|
||||
OR i."origin_kind" NOT IN ('manual', 'onboarding_first_task')
|
||||
)
|
||||
THEN 'agent'
|
||||
ELSE i."scope"
|
||||
END
|
||||
@@ -29,7 +33,11 @@ BEGIN
|
||||
OR (
|
||||
i."conversation_agent_id" IS NULL
|
||||
AND i."scope" = 'board'
|
||||
AND (i."created_by_agent_id" IS NOT NULL OR i."origin_kind" NOT IN ('manual', 'onboarding_first_task'))
|
||||
AND (
|
||||
i."created_by_agent_id" IS NOT NULL
|
||||
OR i."created_by_user_id" IS NULL
|
||||
OR i."origin_kind" NOT IN ('manual', 'onboarding_first_task')
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -341,6 +341,69 @@ describeEmbeddedPostgres("issues.scope visibility and lifecycle", () => {
|
||||
expect(
|
||||
(await svc.list(companyId, { includeAgentCreatedTasks: false })).map((row) => row.id).sort(),
|
||||
).toEqual([boardTask.id, channelPost.id].sort());
|
||||
|
||||
// Explicit scope wins even when includeAgentCreatedTasks=false.
|
||||
const explicitAgentRes = await request(app)
|
||||
.get(`/api/companies/${companyId}/issues?scope=agent&includeAgentCreatedTasks=false`)
|
||||
.expect(200);
|
||||
expect(explicitAgentRes.body.map((row: { id: string }) => row.id)).toEqual([agentTask.id]);
|
||||
|
||||
// Non-conversation issues cannot take scope 'chat' on create or update.
|
||||
await expect(
|
||||
svc.create(companyId, {
|
||||
title: "Bogus non-chat",
|
||||
status: "todo",
|
||||
scope: "chat",
|
||||
createdByUserId: userId,
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 422 });
|
||||
await expect(
|
||||
svc.update(boardTask.id, { scope: "chat" }),
|
||||
).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");
|
||||
const [agent] = await ctx.db
|
||||
.insert(agents)
|
||||
.values({ companyId, name: "Caller", role: "engineer", adapterType: "process" })
|
||||
.returning();
|
||||
const svc = issueService(ctx.db);
|
||||
const agentTask = await svc.create(companyId, {
|
||||
title: "Agent task",
|
||||
status: "todo",
|
||||
createdByAgentId: agent!.id,
|
||||
assigneeAgentId: agent!.id,
|
||||
});
|
||||
const agentActor = {
|
||||
type: "agent",
|
||||
companyId,
|
||||
agentId: agent!.id,
|
||||
runId: undefined,
|
||||
source: "agent_jwt",
|
||||
onBehalfOfUserId: null,
|
||||
onBehalfOfMemberships: [],
|
||||
} as unknown as Parameters<typeof routeApp>[1];
|
||||
const agentApp = routeApp(ctx.db, agentActor, issueRoutes);
|
||||
|
||||
await request(agentApp)
|
||||
.post(`/api/companies/${companyId}/issues`)
|
||||
.send({ title: "Spoofed board task", 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.
|
||||
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");
|
||||
expect(userId).toBeTruthy();
|
||||
});
|
||||
|
||||
it("handles includeAgentCreatedTasks=false with creationVisibilityUserId and includeAgentCreatedTasks=true", async () => {
|
||||
|
||||
@@ -13499,6 +13499,9 @@ 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'");
|
||||
}
|
||||
const createInput = {
|
||||
...createBody,
|
||||
workspaceSelectionActor: req.actor,
|
||||
@@ -14913,6 +14916,9 @@ 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'");
|
||||
}
|
||||
// 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);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { nonIdleSlackIssueCondition } from "./slack-conversation-state.js";
|
||||
import { and, isNull, isNotNull, ne, or, type SQL } from "drizzle-orm";
|
||||
import { and, eq, inArray, isNull, isNotNull, ne, or, type SQL } from "drizzle-orm";
|
||||
import { issues } from "@paperclipai/db";
|
||||
import { ISSUE_SCOPES, type IssueScope } from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
|
||||
export function visibleIssueCondition(): SQL {
|
||||
return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!;
|
||||
@@ -15,6 +17,51 @@ export function nonChatAndChannelIssueCondition(): SQL {
|
||||
return and(ne(issues.scope, "chat"), ne(issues.scope, "channel"), isNull(issues.conversationAgentId))!;
|
||||
}
|
||||
|
||||
/** Parse and validate comma-separated or repeated issue scope filters. */
|
||||
export function parseScopeFilter(
|
||||
input: IssueScope | string | readonly string[] | undefined,
|
||||
): IssueScope[] {
|
||||
if (input === undefined || input === null) return [];
|
||||
const entries = Array.isArray(input)
|
||||
? input
|
||||
: typeof input === "string"
|
||||
? [input]
|
||||
: [];
|
||||
const scopes = [
|
||||
...new Set(
|
||||
entries
|
||||
.flatMap((entry) => (typeof entry === "string" ? entry.split(",") : []))
|
||||
.map((scope) => scope.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
];
|
||||
for (const scope of scopes) {
|
||||
if (!ISSUE_SCOPES.includes(scope as IssueScope)) {
|
||||
throw unprocessable(`Invalid issue scope: ${scope}`);
|
||||
}
|
||||
}
|
||||
return scopes as IssueScope[];
|
||||
}
|
||||
|
||||
/** Resolve the surface scope SQL condition for issue list, count, and inbox queries. */
|
||||
export function surfaceScopeCondition(filters?: {
|
||||
scope?: IssueScope | string | readonly IssueScope[];
|
||||
q?: string;
|
||||
issueIds?: string[];
|
||||
}): { scopes: IssueScope[]; condition: SQL | undefined } {
|
||||
const scopes = parseScopeFilter(filters?.scope);
|
||||
if (scopes.length > 0) {
|
||||
return {
|
||||
scopes,
|
||||
condition: scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes),
|
||||
};
|
||||
}
|
||||
if (!filters?.q?.trim() && !filters?.issueIds) {
|
||||
return { scopes, condition: nonChatAndChannelIssueCondition() };
|
||||
}
|
||||
return { scopes, condition: undefined };
|
||||
}
|
||||
|
||||
/** Work queues and execution totals omit persistent conversation containers. */
|
||||
export function executionIssueCondition(): SQL {
|
||||
return and(visibleIssueCondition(), ne(issues.scope, "chat"), isNull(issues.conversationAgentId), nonIdleSlackIssueCondition())!;
|
||||
|
||||
@@ -269,7 +269,13 @@ import {
|
||||
type IssueGraphLivenessInput,
|
||||
type IssueLivenessFinding,
|
||||
} from "./recovery/issue-graph-liveness.js";
|
||||
import { nonChatAndChannelIssueCondition, visibleIssueCondition } from "./issue-visibility.js";
|
||||
import {
|
||||
nonChatAndChannelIssueCondition,
|
||||
parseScopeFilter,
|
||||
surfaceScopeCondition,
|
||||
visibleIssueCondition,
|
||||
} from "./issue-visibility.js";
|
||||
export { parseScopeFilter };
|
||||
import { finalizeStatusCardsForStalledGeneration } from "./status-card-finalization.js";
|
||||
import { finalizeSummarySlotsForTerminalIssue } from "./summary-slot-finalization.js";
|
||||
import {
|
||||
@@ -1880,18 +1886,6 @@ export type IssueListPhase =
|
||||
| "candidates" | "query" | "labels" | "active_runs" | "user_stats" | "read_stats" | "last_activity"
|
||||
| "archives" | "active_archives" | "blocked_by" | "live_descendants" | "attention";
|
||||
|
||||
export function parseScopeFilter(
|
||||
input: IssueScope | string | readonly string[] | undefined,
|
||||
): IssueScope[] {
|
||||
const scopes = [...new Set(parseStatusFilter(input))];
|
||||
for (const scope of scopes) {
|
||||
if (!ISSUE_SCOPES.includes(scope as IssueScope)) {
|
||||
throw unprocessable(`Invalid issue scope: ${scope}`);
|
||||
}
|
||||
}
|
||||
return scopes as IssueScope[];
|
||||
}
|
||||
|
||||
export interface IssueListOptions {
|
||||
/** Wraps each internal read so callers can report per-phase timing. */
|
||||
timePhase?: <T>(phase: IssueListPhase, read: () => Promise<T>) => Promise<T>;
|
||||
@@ -6724,6 +6718,7 @@ function assertValidAssigneeAgentFilter(
|
||||
|
||||
function creationVisibilityCondition(companyId: string, filters?: IssueFilters) {
|
||||
if (filters?.includeAgentCreatedTasks !== false) return undefined;
|
||||
if (parseScopeFilter(filters?.scope).length > 0) return undefined;
|
||||
const boardScopeCondition = eq(issues.scope, "board");
|
||||
return filters.creationVisibilityUserId
|
||||
? or(boardScopeCondition, touchedByUserCondition(companyId, filters.creationVisibilityUserId))!
|
||||
@@ -6740,12 +6735,8 @@ async function blockedInboxIssueConditions(
|
||||
visibleIssueCondition(),
|
||||
notInArray(issues.status, [...BLOCKED_INBOX_TERMINAL_STATUSES]),
|
||||
];
|
||||
const scopes = parseScopeFilter(filters?.scope);
|
||||
if (scopes.length > 0) {
|
||||
conditions.push(scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes));
|
||||
} else if (!filters?.q?.trim() && !filters?.issueIds) {
|
||||
conditions.push(nonChatAndChannelIssueCondition());
|
||||
}
|
||||
const { condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||
if (scopeCondition) conditions.push(scopeCondition);
|
||||
if (filters?.readCondition) conditions.push(filters.readCondition);
|
||||
const creationCondition = creationVisibilityCondition(companyId, filters);
|
||||
if (creationCondition) conditions.push(creationCondition);
|
||||
@@ -8643,12 +8634,8 @@ export function issueService(db: Db) {
|
||||
? sql<boolean>`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})`
|
||||
: undefined;
|
||||
if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition);
|
||||
const scopes = parseScopeFilter(filters?.scope);
|
||||
if (scopes.length > 0) {
|
||||
conditions.push(scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes));
|
||||
} else if (!filters?.q?.trim() && !filters?.issueIds) {
|
||||
conditions.push(nonChatAndChannelIssueCondition());
|
||||
}
|
||||
const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||
if (scopeCondition) conditions.push(scopeCondition);
|
||||
// Explicit child navigation includes waiting chat tasks, just like
|
||||
// readable-child counts. Ambient lists still omit idle conversations.
|
||||
if (!filters?.q?.trim() && !filters?.issueIds && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.descendantOf && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId && inboxArchive?.mode !== "archived") {
|
||||
@@ -9055,12 +9042,8 @@ export function issueService(db: Db) {
|
||||
if (filters?.readCondition) conditions.push(filters.readCondition);
|
||||
const creationCondition = creationVisibilityCondition(companyId, filters);
|
||||
if (creationCondition) conditions.push(creationCondition);
|
||||
const scopes = parseScopeFilter(filters?.scope);
|
||||
if (scopes.length > 0) {
|
||||
conditions.push(scopes.length === 1 ? eq(issues.scope, scopes[0]!) : inArray(issues.scope, scopes));
|
||||
} else if (!filters?.q?.trim() && !filters?.issueIds) {
|
||||
conditions.push(nonChatAndChannelIssueCondition());
|
||||
}
|
||||
const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||
if (scopeCondition) conditions.push(scopeCondition);
|
||||
if (!filters?.q?.trim() && !filters?.issueIds && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
|
||||
conditions.push(nonIdleSlackIssueCondition());
|
||||
}
|
||||
@@ -10714,6 +10697,9 @@ export function issueService(db: Db) {
|
||||
if (issueData.conversationAgentId != null && issueData.scope !== undefined && issueData.scope !== null && issueData.scope !== "chat") {
|
||||
throw unprocessable("Conversation issues must have scope 'chat'");
|
||||
}
|
||||
if (issueData.conversationAgentId == null && issueData.scope === "chat") {
|
||||
throw unprocessable("Non-conversation issues cannot have scope 'chat'");
|
||||
}
|
||||
if (data.assigneeAgentId) {
|
||||
await assertAssignableAgent(db, companyId, data.assigneeAgentId, {
|
||||
kind: "work",
|
||||
@@ -11824,6 +11810,8 @@ export function issueService(db: Db) {
|
||||
|| data.conversationBoundaryCommentId !== undefined || data.status === "done" || data.status === "cancelled") {
|
||||
throw unprocessable("Conversation identity is fixed; finish the reply instead of completing or reassigning the conversation");
|
||||
}
|
||||
} else if (data.scope === "chat") {
|
||||
throw unprocessable("Non-conversation issues cannot have scope 'chat'");
|
||||
}
|
||||
|
||||
const {
|
||||
|
||||
Reference in new issue
Block a user