[codex] Harden plugin runtime invocation scope (#6547)

## Thinking Path

> - Paperclip orchestrates AI-agent companies through a company-scoped
control plane.
> - Plugins extend that control plane, but plugin workers still call
back into host APIs.
> - Those worker-to-host calls need the same company boundary guarantees
as normal API routes.
> - Plugin action handlers also need authenticated actor context from
the host instead of trusting caller-supplied params.
> - This pull request hardens plugin bridge/action scope and keeps
plugin operation issues out of normal issue surfaces.
> - The benefit is safer plugin execution with clearer authorization
boundaries and better test coverage.

## What Changed

- Added host-owned invocation context plumbing for nested plugin worker
calls.
- Added actor context to plugin `performAction` calls and test harness
helpers.
- Enforced company invocation scope on worker-to-host calls and filtered
company lists to the active invocation scope.
- Extended plugin action route tests for board and agent actor context,
spoofed company params, and cross-company rejection.
- Extended plugin worker manager coverage for invocation-scope
propagation.
- Filtered typed and legacy plugin operation issue origins from default
issue/inbox lists.

## Verification

- `pnpm --filter @paperclipai/plugin-sdk build`
- `NODE_ENV=test pnpm exec vitest run
packages/plugins/sdk/tests/host-client-factory.test.ts
packages/plugins/sdk/tests/testing-actions.test.ts
server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/plugin-worker-manager.test.ts
server/src/__tests__/issues-service.test.ts`

Note: embedded Postgres issue-service tests reported host-level Postgres
init skip for 47 tests; the non-embedded targeted tests passed.

## Risks

- Medium: plugin host authorization paths are sensitive, and external
plugins may rely on previously loose company params.
- Mitigation: the change only tightens calls when the host attached a
company invocation scope and includes explicit tests for board, agent,
and nested worker calls.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI GPT-5 Codex via `codex_local`, tool-enabled coding session;
exact context window not exposed by this runtime.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta 2026-05-22 09:16:24 -05:00 committed by GitHub
parent 38c185fb8b
commit a1835cfa5e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 749 additions and 30 deletions

View file

@ -68,13 +68,13 @@ rl.on("line", (line) => {
id: message.id,
result: {
ok: true,
supportedMethods: ["getData"],
supportedMethods: ["getData", "performAction"],
},
});
return;
}
if (method === "getData") {
if (method === "getData" || method === "performAction") {
sendNestedHostRequest(message, message.paperclipInvocation?.id);
return;
}

View file

@ -773,6 +773,8 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
const normalIssueId = randomUUID();
const pluginVisibleIssueId = randomUUID();
const operationIssueId = randomUUID();
const typedOperationIssueId = randomUUID();
const legacyContentMachineOperationIssueId = randomUUID();
await db.insert(companies).values({
id: companyId,
@ -826,12 +828,36 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
originKind: "plugin:paperclip.missions:operation",
originId: "mission-alpha:operation-1",
},
{
id: typedOperationIssueId,
companyId,
projectId,
title: "Typed plugin operation issue",
status: "todo",
priority: "medium",
assigneeAgentId: agentId,
originKind: "plugin:paperclip.missions:operation:evaluation",
originId: "mission-alpha:operation-2",
},
{
id: legacyContentMachineOperationIssueId,
companyId,
projectId,
title: "Legacy Content Machine operation issue",
status: "todo",
priority: "medium",
assigneeAgentId: agentId,
originKind: "plugin:paperclipai.content-machine:evaluation",
originId: "content-machine-operation-1",
},
]);
const defaultIssueIds = (await svc.list(companyId)).map((issue) => issue.id);
expect(defaultIssueIds).toContain(normalIssueId);
expect(defaultIssueIds).toContain(pluginVisibleIssueId);
expect(defaultIssueIds).not.toContain(operationIssueId);
expect(defaultIssueIds).not.toContain(typedOperationIssueId);
expect(defaultIssueIds).not.toContain(legacyContentMachineOperationIssueId);
const inboxIssueIds = (await svc.list(companyId, {
assigneeAgentId: agentId,
@ -840,17 +866,28 @@ describeEmbeddedPostgres("issueService.list participantAgentId", () => {
})).map((issue) => issue.id);
expect(inboxIssueIds).toContain(normalIssueId);
expect(inboxIssueIds).not.toContain(operationIssueId);
expect(inboxIssueIds).not.toContain(typedOperationIssueId);
expect(inboxIssueIds).not.toContain(legacyContentMachineOperationIssueId);
await expect(svc.list(companyId, { originKind: "plugin:paperclip.missions:operation" }))
.resolves.toEqual([expect.objectContaining({ id: operationIssueId })]);
await expect(svc.list(companyId, { originId: "mission-alpha:operation-1" }))
.resolves.toEqual([expect.objectContaining({ id: operationIssueId })]);
await expect(svc.list(companyId, { originKindPrefix: "plugin:paperclip.missions:operation" }))
.resolves.toEqual(expect.arrayContaining([
expect.objectContaining({ id: operationIssueId }),
expect.objectContaining({ id: typedOperationIssueId }),
]));
const projectIssueIds = (await svc.list(companyId, { projectId })).map((issue) => issue.id);
expect(projectIssueIds).toContain(operationIssueId);
expect(projectIssueIds).toContain(typedOperationIssueId);
expect(projectIssueIds).toContain(legacyContentMachineOperationIssueId);
const advancedIssueIds = (await svc.list(companyId, { includePluginOperations: true })).map((issue) => issue.id);
expect(advancedIssueIds).toContain(operationIssueId);
expect(advancedIssueIds).toContain(typedOperationIssueId);
expect(advancedIssueIds).toContain(legacyContentMachineOperationIssueId);
});
it("excludes plugin operation issues from unread inbox counts", async () => {

View file

@ -114,6 +114,17 @@ function boardActor(overrides: Record<string, unknown> = {}) {
};
}
function agentActor(overrides: Record<string, unknown> = {}) {
return {
type: "agent",
agentId: agentA,
companyId: companyA,
runId: runA,
source: "agent_jwt",
...overrides,
};
}
function readyPlugin() {
mockRegistry.getById.mockResolvedValue({
id: pluginId,
@ -656,10 +667,160 @@ describe.sequential("plugin tool and bridge authz", () => {
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
key: "sync",
params: {},
actorContext: {
type: "user",
userId: "admin-1",
agentId: null,
runId: null,
companyId: null,
},
renderEnvironment: null,
});
});
it("passes authenticated actor context and overrides spoofed company scope for plugin actions", async () => {
readyPlugin();
const call = vi.fn().mockResolvedValue({ ok: true });
const { app } = await createApp(boardActor({ runId: runA }), {}, {
bridgeDeps: {
workerManager: { call },
},
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/actions/sync`)
.send({
companyId: companyA,
params: {
companyId: companyB,
reviewerUserId: "spoofed-user",
},
});
expect(res.status).toBe(200);
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
key: "sync",
params: {
companyId: companyA,
reviewerUserId: "spoofed-user",
},
actorContext: {
type: "user",
userId: "user-1",
agentId: null,
runId: runA,
companyId: companyA,
},
renderEnvironment: null,
});
});
it("uses null for board actor userId when no authenticated user id is present", async () => {
readyPlugin();
const call = vi.fn().mockResolvedValue({ ok: true });
const { app } = await createApp(boardActor({ userId: undefined }), {}, {
bridgeDeps: {
workerManager: { call },
},
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/actions/sync`)
.send({ companyId: companyA });
expect(res.status).toBe(200);
expect(call).toHaveBeenCalledWith(pluginId, "performAction", expect.objectContaining({
actorContext: expect.objectContaining({
type: "user",
userId: null,
companyId: companyA,
}),
}));
});
it("allows agent-scoped plugin actions with authenticated actor context", async () => {
readyPlugin();
const call = vi.fn().mockResolvedValue({ ok: true });
const { app } = await createApp(agentActor(), {}, {
bridgeDeps: {
workerManager: { call },
},
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/actions/sync`)
.send({
companyId: companyA,
params: {
companyId: companyB,
reviewerAgentId: "spoofed-agent",
},
});
expect(res.status).toBe(200);
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
key: "sync",
params: {
companyId: companyA,
reviewerAgentId: "spoofed-agent",
},
actorContext: {
type: "agent",
userId: null,
agentId: agentA,
runId: runA,
companyId: companyA,
},
renderEnvironment: null,
});
call.mockClear();
const legacyRes = await request(app)
.post(`/api/plugins/${pluginId}/bridge/action`)
.send({
key: "sync",
companyId: companyA,
params: {
companyId: companyB,
reviewerAgentId: "spoofed-agent",
},
});
expect(legacyRes.status).toBe(200);
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
key: "sync",
params: {
companyId: companyA,
reviewerAgentId: "spoofed-agent",
},
actorContext: {
type: "agent",
userId: null,
agentId: agentA,
runId: runA,
companyId: companyA,
},
renderEnvironment: null,
});
});
it("rejects agent plugin actions outside the authenticated company scope", async () => {
readyPlugin();
const call = vi.fn().mockResolvedValue({ ok: true });
const { app } = await createApp(agentActor(), {}, {
bridgeDeps: {
workerManager: { call },
},
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/actions/sync`)
.send({ companyId: companyB });
expect(res.status).toBe(403);
expect(call).not.toHaveBeenCalled();
});
it("attaches worker bridge errors to the HTTP logger context", async () => {
readyPlugin();
const call = vi.fn().mockRejectedValue(new Error("missing source_objects column"));

View file

@ -186,6 +186,58 @@ describe("plugin-worker-manager stderr failure context", () => {
}
});
it("passes performAction invocation scope to nested worker host calls", async () => {
const companiesGet = vi.fn(async (
params: { companyId: string },
context?: { invocationScope?: { companyId?: string | null } | null },
) => ({
id: params.companyId,
scopedCompanyId: context?.invocationScope?.companyId ?? null,
}));
const handle = createPluginWorkerHandle("test.plugin", {
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT,
manifest: TEST_MANIFEST,
config: {},
instanceInfo: {
instanceId: "instance-1",
hostVersion: "1.0.0",
},
apiVersion: 1,
hostHandlers: {
"companies.get": companiesGet as never,
},
});
try {
await handle.start();
await expect(handle.call("performAction", {
key: "probe",
params: {
mode: "echo",
requestedCompanyId: "company-a",
},
actorContext: {
type: "agent",
userId: null,
agentId: "agent-1",
runId: "run-1",
companyId: "company-a",
},
renderEnvironment: null,
})).resolves.toEqual({
id: "company-a",
scopedCompanyId: "company-a",
});
expect(companiesGet).toHaveBeenCalledWith(
{ companyId: "company-a" },
{ invocationScope: { companyId: "company-a" } },
);
} finally {
await handle.stop().catch(() => undefined);
}
});
it("passes echoed invocation scope to worker-to-host handlers", async () => {
const companiesGet = vi.fn(async () => ({ id: "company-1" }));
const handle = createPluginWorkerHandle("test.plugin", {
@ -223,6 +275,104 @@ describe("plugin-worker-manager stderr failure context", () => {
}
});
it("rejects performAction nested host calls that omit the invocation id", async () => {
const handlers = createHostClientHandlers({
pluginId: "test.plugin",
capabilities: ["companies.read"],
services: {
companies: {
list: vi.fn(async () => []),
get: vi.fn(async (params: { companyId: string }) => ({ id: params.companyId })),
},
} as unknown as HostServices,
});
const handle = createPluginWorkerHandle("test.plugin", {
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT,
manifest: TEST_MANIFEST,
config: {},
instanceInfo: {
instanceId: "instance-1",
hostVersion: "1.0.0",
},
apiVersion: 1,
hostHandlers: handlers,
});
try {
await handle.start();
await expect(handle.call("performAction", {
key: "probe",
params: {
requestedCompanyId: "company-b",
},
actorContext: {
type: "agent",
userId: null,
agentId: "agent-1",
runId: "run-1",
companyId: "company-a",
},
renderEnvironment: null,
})).rejects.toMatchObject({
code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED,
message: expect.stringContaining("unknown invocation scope"),
});
} finally {
await handle.stop().catch(() => undefined);
}
});
it("rejects nested worker host calls that forge an unknown invocation id", async () => {
const companiesGet = vi.fn(async (params: { companyId: string }) => ({ id: params.companyId }));
const handlers = createHostClientHandlers({
pluginId: "test.plugin",
capabilities: ["companies.read"],
services: {
companies: {
get: companiesGet,
},
} as unknown as HostServices,
});
const handle = createPluginWorkerHandle("test.plugin", {
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT,
manifest: TEST_MANIFEST,
config: {},
instanceInfo: {
instanceId: "instance-1",
hostVersion: "1.0.0",
},
apiVersion: 1,
hostHandlers: handlers,
});
try {
await handle.start();
await expect(handle.call("performAction", {
key: "probe",
params: {
mode: "unknown",
requestedCompanyId: "company-a",
},
actorContext: {
type: "agent",
userId: null,
agentId: "agent-1",
runId: "run-1",
companyId: "company-a",
},
renderEnvironment: null,
})).rejects.toMatchObject({
code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED,
message: expect.stringContaining("unknown invocation scope"),
});
expect(companiesGet).not.toHaveBeenCalled();
} finally {
await handle.stop().catch(() => undefined);
}
});
it("rejects missing or unknown invocation ids while a company invocation is active", async () => {
const companiesGet = vi.fn(async () => ({ id: "company-2" }));
const hostHandlers = createHostClientHandlers({
@ -258,7 +408,7 @@ describe("plugin-worker-manager stderr failure context", () => {
requestedCompanyId: "company-2",
},
} as HostToWorkerMethods["getData"][0])).rejects.toMatchObject({
code: PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED,
code: PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED,
});
}

View file

@ -55,7 +55,7 @@ import type { PluginJobStore } from "../services/plugin-job-store.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import type { PluginStreamBus } from "../services/plugin-stream-bus.js";
import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js";
import type { ToolRunContext } from "@paperclipai/plugin-sdk";
import type { PluginPerformActionActorContext, ToolRunContext } from "@paperclipai/plugin-sdk";
import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES } from "@paperclipai/plugin-sdk";
import {
assertAuthenticated,
@ -572,6 +572,43 @@ export function pluginRoutes(
return companyId;
}
function performActionActorContext(req: Request, companyId: string | undefined): PluginPerformActionActorContext {
const scopedCompanyId = companyId ?? null;
if (req.actor.type === "agent") {
return {
type: "agent",
userId: null,
agentId: req.actor.agentId ?? null,
runId: req.actor.runId ?? null,
companyId: scopedCompanyId,
};
}
if (req.actor.type === "board") {
return {
type: "user",
userId: req.actor.userId ?? null,
agentId: null,
runId: req.actor.runId ?? null,
companyId: scopedCompanyId,
};
}
return {
type: "system",
userId: null,
agentId: null,
runId: req.actor.runId ?? null,
companyId: scopedCompanyId,
};
}
function actionParamsWithAuthorizedCompanyScope(
params: Record<string, unknown> | undefined,
companyId: string | undefined,
): Record<string, unknown> {
const base = params ?? {};
return companyId === undefined ? base : { ...base, companyId };
}
async function validateToolRunContextScope(runContext: ToolRunContext): Promise<string | null> {
const [agent] = await db
.select({ companyId: agents.companyId })
@ -984,6 +1021,12 @@ export function pluginRoutes(
message: err.message,
details: err.data,
};
case PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED:
return {
code: "INVOCATION_SCOPE_DENIED",
message: err.message,
details: err.data,
};
case PLUGIN_RPC_ERROR_CODES.TIMEOUT:
return {
code: "TIMEOUT",
@ -1171,7 +1214,7 @@ export function pluginRoutes(
* @see PLUGIN_SPEC.md §19.7 Error Propagation Through The Bridge
*/
router.post("/plugins/:pluginId/bridge/action", async (req, res) => {
assertBoardOrgAccess(req);
assertAuthenticated(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@ -1217,8 +1260,8 @@ export function pluginRoutes(
"performAction",
{
key: body.key,
...(companyId ? { companyId } : {}),
params: body.params ?? {},
params: actionParamsWithAuthorizedCompanyScope(body.params, companyId),
actorContext: performActionActorContext(req, companyId),
renderEnvironment: body.renderEnvironment ?? null,
},
);
@ -1355,7 +1398,7 @@ export function pluginRoutes(
* @see PLUGIN_SPEC.md §19.7 Error Propagation Through The Bridge
*/
router.post("/plugins/:pluginId/actions/:key", async (req, res) => {
assertBoardOrgAccess(req);
assertAuthenticated(req);
if (!bridgeDeps) {
res.status(501).json({ error: "Plugin bridge is not enabled" });
@ -1401,8 +1444,8 @@ export function pluginRoutes(
"performAction",
{
key,
...(companyId ? { companyId } : {}),
params: body?.params ?? {},
params: actionParamsWithAuthorizedCompanyScope(body?.params, companyId),
actorContext: performActionActorContext(req, companyId),
renderEnvironment: body?.renderEnvironment ?? null,
},
);
@ -1606,7 +1649,10 @@ export function pluginRoutes(
} catch (err) {
const status = typeof (err as { status?: unknown }).status === "number"
? (err as { status: number }).status
: err instanceof JsonRpcCallError && err.code === PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED
: err instanceof JsonRpcCallError && (
err.code === PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED ||
err.code === PLUGIN_RPC_ERROR_CODES.INVOCATION_SCOPE_DENIED
)
? 403
: err instanceof JsonRpcCallError && err.code === PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED
? 501

View file

@ -683,14 +683,25 @@ function inboxVisibleForUserCondition(companyId: string, userId: string) {
`;
}
const LEGACY_PLUGIN_OPERATION_ORIGIN_KINDS = [
"plugin:paperclipai.content-machine:case",
"plugin:paperclipai.content-machine:evaluation",
"plugin:paperclipai.content-machine:source-sync",
] as const;
function nonPluginOperationIssueCondition() {
return sql<boolean>`NOT (${issues.originKind} LIKE 'plugin:%:operation' OR ${issues.originKind} LIKE 'plugin:%:operation:%')`;
return sql<boolean>`NOT (
${issues.originKind} LIKE 'plugin:%:operation'
OR ${issues.originKind} LIKE 'plugin:%:operation:%'
OR ${inArray(issues.originKind, LEGACY_PLUGIN_OPERATION_ORIGIN_KINDS)}
)`;
}
function shouldIncludePluginOperationIssues(filters: IssueFilters | undefined) {
return Boolean(
filters?.includePluginOperations ||
filters?.originKind ||
filters?.originKindPrefix ||
filters?.originId ||
filters?.projectId,
);

View file

@ -204,6 +204,8 @@ interface PendingRequest {
timer: ReturnType<typeof setTimeout>;
/** Timestamp when the request was sent. */
sentAt: number;
/** Active host-owned invocation id attached to this host→worker call. */
invocationId?: string;
}
interface ActiveInvocation {
@ -435,6 +437,14 @@ export function createPluginWorkerHandle(
childProcess.stdin.write(serialized);
}
function errorCodeForWorkerHostError(err: unknown): number {
const code = (err as { code?: unknown } | null)?.code;
const pluginErrorCodes: readonly number[] = Object.values(PLUGIN_RPC_ERROR_CODES);
return typeof code === "number" && pluginErrorCodes.includes(code)
? code
: JSONRPC_ERROR_CODES.INTERNAL_ERROR;
}
// -----------------------------------------------------------------------
// Incoming message handling
// -----------------------------------------------------------------------
@ -503,6 +513,11 @@ export function createPluginWorkerHandle(
const directCompanyId = readNonEmptyString(params.companyId);
if (directCompanyId) return { companyId: directCompanyId };
if (method === "performAction" && isRecord(params.actorContext)) {
const companyId = readNonEmptyString(params.actorContext.companyId);
return companyId ? { companyId } : null;
}
if (method === "executeTool" && isRecord(params.runContext)) {
const companyId = readNonEmptyString(params.runContext.companyId);
return companyId ? { companyId } : null;
@ -585,15 +600,12 @@ export function createPluginWorkerHandle(
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
const errorCode = typeof (err as { code?: unknown }).code === "number"
? (err as { code: number }).code
: JSONRPC_ERROR_CODES.INTERNAL_ERROR;
log.error({ method, err: errorMessage }, "host handler error");
try {
sendMessage(
createErrorResponse(
request.id,
errorCode,
errorCodeForWorkerHostError(err),
errorMessage,
),
);
@ -1161,6 +1173,7 @@ export function createPluginWorkerHandle(
},
timer,
sentAt: Date.now(),
invocationId: invocation?.id,
};
pendingRequests.set(id, pending);