Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1318,11 +1318,11 @@ export interface paths {
get: operations["get_api_v1_jobs_jobId_invocation_permissions"];
/**
* Replace a source job's manual invocation destinations
* @description Owner session only. Destinations must exist in the same tenant. Lifecycle subscriptions do not create permissions.
* @description Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must exist in the same tenant. Lifecycle subscriptions do not create permissions.
*
* Requires the jobs:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
* Accepts a scoped bearer token or interactive owner session.
*/
put: operations["put_api_v1_jobs_jobId_invocation_permissions"];
post?: never;
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ export const API_ROUTES: RouteContract[] = [
responses: { "200": { description: "Verified runtime identity", content: { "application/json": { schema: jsonSchema(runtimeContextResponse, "output") } } } } },
service => service.getRuntimeContext()),
route("GET", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:read", { summary: "List a source job's manual invocation destinations", responses: { "200": { description: "Configured tenant-local destination jobs", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params }) => service.getInvocationPermissions(params.jobId)),
route("PUT", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:write", { summary: "Replace a source job's manual invocation destinations", description: "Owner session only. Destinations must exist in the same tenant. Lifecycle subscriptions do not create permissions.", responses: { "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.jobId, body.destinationJobIds), { body: invocationPermissionsInput, ownerSession: true }),
route("PUT", "/api/v1/jobs/{jobId}/invocation-permissions", "jobs:write", { summary: "Replace a source job's manual invocation destinations", description: "Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must exist in the same tenant. Lifecycle subscriptions do not create permissions.", responses: { "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.jobId, body.destinationJobIds), { body: invocationPermissionsInput }),
route(
"GET",
"/api/v1/jobs/{jobId}/events",
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,10 @@ export class ApiService {
return publicValue(invocationPermissionsResponse, { sourceJobId, destinationJobIds: rows.rows.map(row => row.destination_job_id) });
}
async setInvocationPermissions(sourceJobId: string, destinationJobIds: string[]) {
await this.authorizeOwnerSession("jobs:write");
await this.authorize("jobs:write");
// Run credentials intentionally have a read/invoke-only scope set. Keep this
// service guard as defense in depth if a future run credential gains scopes.
if (this.auth.authMethod === "run_token") throw new ServiceError(403, "insufficient_scope", "Run credentials cannot change invocation permissions.");
const unique = [...new Set(destinationJobIds)];
if (unique.length !== destinationJobIds.length || unique.includes(sourceJobId)) throw new ServiceError(400, "invalid_request", "Destination jobs must be unique and cannot include the source job.");
const db = databaseFor(this.env);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ function createMcpServer(service: ApiService): McpServer {
tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false));
tool("invoke_job", "Invoke a job's manual trigger with an optional display name, prompt, and JSON data exposed beneath that trigger's stable slug. Manual invocations are never coalesced; a full job queue returns queue_full. idempotencyKey is a client value and must not include the internal manual: claim-key prefix; reuse invocation.idempotency_key from get_run.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input));
tool("get_job_invocation_permissions", "List the destinations a source job may manually invoke.", jobIdSchema, ({ jobId }: any) => service.getInvocationPermissions(jobId));
tool("set_job_invocation_permissions", "Replace manual invocation destinations for a source job. Owner session required; destination IDs must belong to the same tenant.", z.object({ jobId: z.string().min(1), destinationJobIds: z.array(z.string().uuid()).max(1000) }).strict(), ({ jobId, destinationJobIds }: any) => service.setInvocationPermissions(jobId, destinationJobIds));
tool("set_job_invocation_permissions", "Replace manual invocation destinations for a source job. Requires an owner session, scoped API key, or authorized OAuth client with jobs:write; destination IDs must belong to the same tenant.", z.object({ jobId: z.string().min(1), destinationJobIds: z.array(z.string().uuid()).max(1000) }).strict(), ({ jobId, destinationJobIds }: any) => service.setInvocationPermissions(jobId, destinationJobIds));
tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit));
tool("list_webhook_deliveries", "Search tenant-scoped webhook deliveries by provider, delivery ID, event, outcome, job, time range, or safe diagnostic text. Results are newest first and cursor paginated.", z.object({ provider: z.string().optional(), deliveryId: z.string().optional(), event: z.string().optional(), action: z.string().optional(), outcome: z.string().optional(), jobId: z.string().optional(), q: z.string().optional(), from: z.string().optional(), to: z.string().optional(), limit: z.number().int().min(1).max(100).default(50), cursor: z.string().optional() }), (input: any) => service.listWebhookDeliveries(queryOf(input)));
tool("get_webhook_delivery", "Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned.", z.object({ deliveryId: z.string().min(1) }), ({ deliveryId }: any) => service.getWebhookDelivery(deliveryId));
Expand Down
143 changes: 109 additions & 34 deletions packages/api/test/manual-invocation-permissions.test.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,121 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ApiService, ServiceError } from "../src/flow-service";
import { protectedApiFetch } from "../src/protected-api";

vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {} }));
afterEach(() => vi.restoreAllMocks());

const tenantId = "00000000-0000-4000-8000-000000000001";
const sourceId = "00000000-0000-4000-8000-000000000002";
const destinationId = "00000000-0000-4000-8000-000000000003";
const foreignId = "00000000-0000-4000-8000-000000000004";

function fixture(options: { member?: boolean; activeToken?: boolean } = {}) {
const persisted: string[] = [];
const query = async (sql: string, values: unknown[] = []) => {
if (sql.includes("SELECT m.user_id,m.email")) return { rows: options.member === false ? [] : [{ user_id: "owner", email: "owner@example.com", role: "owner", session_version: 1 }], rowCount: options.member === false ? 0 : 1 };
if (sql.includes("SELECT 1 FROM app.access_tokens")) return { rows: options.activeToken === false ? [] : [{ ok: 1 }], rowCount: options.activeToken === false ? 0 : 1 };
if (sql.includes("SELECT 1 FROM app.jobs")) return { rows: values[1] === sourceId ? [{ ok: 1 }] : [], rowCount: values[1] === sourceId ? 1 : 0 };
if (sql.includes("SELECT id FROM app.jobs")) {
const ids = (values[1] as string[]).filter(id => id === destinationId);
return { rows: ids.map(id => ({ id })), rowCount: ids.length };
}
if (sql.includes("DELETE FROM app.manual_invocation_permissions")) { persisted.length = 0; return { rows: [], rowCount: 1 }; }
if (sql.includes("INSERT INTO app.manual_invocation_permissions")) { persisted.push(...values[2] as string[]); return { rows: [], rowCount: persisted.length }; }
if (sql.includes("SELECT destination_job_id")) return { rows: persisted.map(destination_job_id => ({ destination_job_id })), rowCount: persisted.length };
throw new Error(`Unexpected SQL: ${sql}`);
};
const database = { pool: { query }, transaction: async (work: (client: any) => Promise<unknown>) => work({ query }) } as any;
const env = { APP_ORIGIN: "https://example.com", DATABASE: database } as any;
return { env, database, persisted };
}

function auth(authMethod: "session" | "access_token" | "oauth" | "run_token", scopes = ["jobs:write"], accessTokenId?: string) {
return { tenantId, userId: "owner", sessionVersion: 1, scopes, authMethod, accessTokenId } as any;
}

async function request(transport: "REST" | "MCP", credential: ReturnType<typeof auth> | null, scopes?: string[], destinationJobIds = [destinationId]) {
const f = fixture();
const rest = transport === "REST";
const url = f.env.APP_ORIGIN + (rest ? `/api/v1/jobs/${sourceId}/invocation-permissions` : "/mcp");
const body = { destinationJobIds };
const payload = rest ? body : { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "set_job_invocation_permissions", arguments: { jobId: sourceId, ...body } } };
const response = await protectedApiFetch(new Request(url, {
method: rest ? "PUT" : "POST",
headers: { Host: "example.com", Origin: f.env.APP_ORIGIN, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
body: JSON.stringify(payload),
}), f.env, credential ? { ...credential, ...(scopes ? { scopes } : {}) } : null, {} as any);
return { response, f };
}

async function mcpMessage(response: Response) {
const text = await response.text();
return JSON.parse(text.startsWith("event:") ? text.split("\n").find(line => line.startsWith("data:"))!.slice(5) : text);
}

describe("manual invocation permission management", () => {
const tenantId = "00000000-0000-4000-8000-000000000001", sourceId = "00000000-0000-4000-8000-000000000002";
const destinationId = "00000000-0000-4000-8000-000000000003", foreignId = "00000000-0000-4000-8000-000000000004";
it("replaces and lists tenant-local permissions through the authorized service", async () => {
const persisted: string[] = [], queries: unknown[][] = [];
const query = async (sql: string, values: unknown[] = []) => {
queries.push(values);
if (sql.includes("SELECT 1 FROM app.jobs")) return { rows: values[1] === sourceId ? [{ ok: 1 }] : [], rowCount: values[1] === sourceId ? 1 : 0 };
if (sql.includes("SELECT id FROM app.jobs")) return { rows: (values[1] as string[]).filter(id => id === destinationId).map(id => ({ id })), rowCount: (values[1] as string[]).filter(id => id === destinationId).length };
if (sql.includes("DELETE FROM app.manual_invocation_permissions")) { persisted.length = 0; return { rows: [], rowCount: 1 }; }
if (sql.includes("INSERT INTO app.manual_invocation_permissions")) { persisted.push(...values[2] as string[]); return { rows: [], rowCount: persisted.length }; }
if (sql.includes("SELECT destination_job_id")) return { rows: persisted.map(destination_job_id => ({ destination_job_id })), rowCount: persisted.length };
throw new Error(`Unexpected SQL: ${sql}`);
};
const database = { pool: { query }, transaction: async (work: (client: any) => Promise<unknown>) => work({ query }) } as any;
const service = new ApiService({ DATABASE: database } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["jobs:read", "jobs:write"], authMethod: "session" });
const ownerAuthorization = vi.spyOn(service as any, "authorizeOwnerSession").mockResolvedValue(undefined);
vi.spyOn(service as any, "authorize").mockResolvedValue(undefined);
vi.spyOn(service as any, "jobs").mockReturnValue({ getJob: async (id: string) => id === sourceId ? { id } : null });
it.each(["session", "access_token", "oauth"] as const)("accepts %s credentials at the REST route and MCP tool", async method => {
for (const transport of ["REST", "MCP"] as const) {
const { response, f } = await request(transport, auth(method, ["jobs:write"], method === "access_token" ? "token-id" : undefined));
expect(response.status).toBe(200);
if (transport === "REST") expect(await response.json()).toEqual({ sourceJobId: sourceId, destinationJobIds: [destinationId] });
else expect((await mcpMessage(response)).result.structuredContent).toEqual({ sourceJobId: sourceId, destinationJobIds: [destinationId] });
expect(f.persisted).toEqual([destinationId]);
}
});

it.each(["session", "access_token", "oauth"] as const)("authorizes %s at the service and preserves tenant-local destination checks", async method => {
const f = fixture();
const service = new ApiService(f.env, auth(method, ["jobs:write"], method === "access_token" ? "token-id" : undefined));
await expect(service.setInvocationPermissions(sourceId, [destinationId])).resolves.toEqual({ sourceJobId: sourceId, destinationJobIds: [destinationId] });
await expect(service.getInvocationPermissions(sourceId)).resolves.toEqual({ sourceJobId: sourceId, destinationJobIds: [destinationId] });
expect(queries.every(values => values[0] === tenantId)).toBe(true);
expect(ownerAuthorization).toHaveBeenCalledWith("jobs:write");
expect(f.persisted).toEqual([destinationId]);
await expect(service.setInvocationPermissions(sourceId, [foreignId])).rejects.toMatchObject({ status: 400, code: "invalid_request" });
});

it("rejects missing scopes, missing credentials, invalid or revoked owner credentials, and run tokens", async () => {
for (const transport of ["REST", "MCP"] as const) {
const noScope = await request(transport, auth("oauth", ["jobs:read"]));
if (transport === "REST") {
expect(noScope.response.status).toBe(403);
expect((await noScope.response.json() as any).error.code).toBe("insufficient_scope");
} else expect((await mcpMessage(noScope.response)).result.isError).toBe(true);
const missing = await request(transport, null);
if (transport === "REST") expect(missing.response.status).toBe(401);
else expect(missing.response.status).toBe(401);
}

for (const transport of ["REST", "MCP"] as const) {
const foreign = await request(transport, auth("session"), undefined, [foreignId]);
if (transport === "REST") {
expect(foreign.response.status).toBe(400);
expect((await foreign.response.json() as any).error.code).toBe("invalid_request");
} else expect((await mcpMessage(foreign.response)).result.isError).toBe(true);
}

for (const [options, credential] of [
[{ member: false }, auth("oauth")],
[{ activeToken: false }, auth("access_token", ["jobs:write"], "revoked-token")],
] as const) {
const f = fixture(options);
await expect(new ApiService(f.env, credential).setInvocationPermissions(sourceId, [destinationId]))
.rejects.toMatchObject({ status: 401, code: "invalid_token" });
}

const f = fixture();
await expect(new ApiService(f.env, auth("run_token", ["jobs:write"])).setInvocationPermissions(sourceId, [destinationId]))
.rejects.toBeInstanceOf(ServiceError);
await expect(new ApiService(f.env, auth("session", ["jobs:write"])).setInvocationPermissions(foreignId, [destinationId]))
.rejects.toMatchObject({ status: 404, code: "not_found" });
});

it("rejects cross-tenant, duplicate, self, and missing source grants", async () => {
const query = async (sql: string, values: unknown[] = []) => {
if (sql.includes("SELECT 1 FROM app.jobs")) return { rows: values[1] === sourceId ? [{ ok: 1 }] : [], rowCount: values[1] === sourceId ? 1 : 0 };
if (sql.includes("SELECT id FROM app.jobs")) return { rows: [], rowCount: 0 };
return { rows: [], rowCount: 0 };
};
const database = { pool: { query }, transaction: async (work: (client: any) => Promise<unknown>) => work({ query }) } as any;
const service = new ApiService({ DATABASE: database } as any, { tenantId, userId: "owner", sessionVersion: 1, scopes: ["jobs:write"], authMethod: "session" });
vi.spyOn(service as any, "authorizeOwnerSession").mockResolvedValue(undefined);
await expect(service.setInvocationPermissions(sourceId, [foreignId])).rejects.toMatchObject({ status: 400 });
await expect(service.setInvocationPermissions(sourceId, [destinationId, destinationId])).rejects.toBeInstanceOf(ServiceError);
await expect(service.setInvocationPermissions(sourceId, [sourceId])).rejects.toBeInstanceOf(ServiceError);
await expect(service.setInvocationPermissions(foreignId, [destinationId])).rejects.toMatchObject({ status: 404 });
it("keeps the API route's browser origin check for owner sessions", async () => {
const f = fixture();
const response = await protectedApiFetch(new Request(`${f.env.APP_ORIGIN}/api/v1/jobs/${sourceId}/invocation-permissions`, {
method: "PUT", headers: { Host: "example.com", Origin: "https://attacker.example", "Content-Type": "application/json" },
body: JSON.stringify({ destinationJobIds: [destinationId] }),
}), f.env, auth("session"), {} as any);
expect(response.status).toBe(403);
expect((await response.json() as any).error.code).toBe("invalid_origin");
expect(f.persisted).toEqual([]);
});
});
Loading
Loading