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
2 changes: 1 addition & 1 deletion packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1342,7 +1342,7 @@ export interface paths {
get: operations["get_api_v1_jobs_jobId_invocation_permissions"];
/**
* 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.
* @description Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must exist in the same tenant. A source job may include itself to opt in to explicitly requested successor runs; this does not schedule runs automatically. Lifecycle subscriptions do not create permissions.
*
* Requires the jobs:write scope.
*
Expand Down
2 changes: 2 additions & 0 deletions packages/api/migrations/0028_allow_manual_self_invocation.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE app.manual_invocation_permissions
DROP CONSTRAINT manual_invocation_permissions_check;
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,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: "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("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. A source job may include itself to opt in to explicitly requested successor runs; this does not schedule runs automatically. 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
2 changes: 1 addition & 1 deletion packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ export class ApiService {
// 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.");
if (unique.length !== destinationJobIds.length) throw new ServiceError(400, "invalid_request", "Destination jobs must be unique.");
const db = databaseFor(this.env);
await db.transaction(async client => {
const sources = await client.query("SELECT 1 FROM app.jobs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [this.auth.tenantId, sourceJobId]);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/postgres/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const webhookConditionsCutover = app.table("webhook_conditions_cutover",
export const invocations = app.table("invocations", {
tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), source: text("source").$type<InvocationSource>().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id").notNull(), context: jsonb("context").$type<Record<string, unknown>>().notNull(), occurrence: jsonb("occurrence").$type<InvocationRequest["occurrence"]>(), sourceJobId: uuid("source_job_id"), sourceRunId: uuid("source_run_id"), createdAt: createdAt(),
}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle','jobIdle')`), index("invocations_source_run").on(t.tenantId, t.sourceRunId).where(sql`${t.sourceRunId} is not null`)]);
export const manualInvocationPermissions = app.table("manual_invocation_permissions", { tenantId: uuid("tenant_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), destinationJobId: uuid("destination_job_id").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.sourceJobId, t.destinationJobId] }), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.destinationJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), check("manual_invocation_permissions_not_self", sql`${t.sourceJobId} <> ${t.destinationJobId}`), index("manual_invocation_permissions_destination").on(t.tenantId, t.destinationJobId)]);
export const manualInvocationPermissions = app.table("manual_invocation_permissions", { tenantId: uuid("tenant_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), destinationJobId: uuid("destination_job_id").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.sourceJobId, t.destinationJobId] }), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.destinationJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("manual_invocation_permissions_destination").on(t.tenantId, t.destinationJobId)]);
export const jobRuns = app.table("job_runs", {
tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), state: text("state").$type<"queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped">().notNull(), encryptedPrompt: text("encrypted_prompt").notNull(), runName: text("run_name").notNull().default(""), launchLeaseExpiresAt: timestamp("launch_lease_expires_at", { withTimezone: true }), nextPollAt: timestamp("next_poll_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), startedAt: timestamp("started_at", { withTimezone: true }),
}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`)]);
Expand Down
9 changes: 8 additions & 1 deletion packages/api/test/job-lifecycle.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,19 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po
const a = await tenant(), b = await tenant(), source = await job(a), destination = await job(a), foreign = await job(b);
await database.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) VALUES ($1,$2,$3)", [a, source.id, destination.id]);
await expect(database.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) VALUES ($1,$2,$3)", [a, source.id, foreign.id])).rejects.toMatchObject({ code: "23503" });
await expect(database.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) VALUES ($1,$2,$2)", [a, source.id])).rejects.toMatchObject({ code: "23514" });
await repository(a).delete(source.id);
const edges = await database.pool.query("SELECT 1 FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2", [a, source.id]);
expect(edges.rowCount).toBe(0);
});

it("stores and revokes an explicit self-invocation permission", async () => {
const a = await tenant(), self = await job(a);
await database.pool.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) VALUES ($1,$2,$2)", [a, self.id]);
expect((await database.pool.query("SELECT 1 FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2 AND destination_job_id=$2", [a, self.id])).rowCount).toBe(1);
await database.pool.query("DELETE FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2 AND destination_job_id=$2", [a, self.id]);
expect((await database.pool.query("SELECT 1 FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2 AND destination_job_id=$2", [a, self.id])).rowCount).toBe(0);
});

it("preserves one accepted stop across a stale poll and late launch completion", async () => {
const a = await tenant(), source = await job(a);
const create = (claimKey: string) => new InvocationService(repository(a), value => encrypt(value, key)).invoke(source.id, {
Expand Down
12 changes: 7 additions & 5 deletions packages/api/test/manual-invocation-permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function fixture(options: { member?: boolean; activeToken?: boolean } = {}) {
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);
const ids = (values[1] as string[]).filter(id => id === destinationId || id === sourceId);
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 }; }
Expand Down Expand Up @@ -56,17 +56,19 @@ async function mcpMessage(response: Response) {
describe("manual invocation permission management", () => {
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));
const { response, f } = await request(transport, auth(method, ["jobs:write"], method === "access_token" ? "token-id" : undefined), undefined, [sourceId, destinationId]);
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]);
if (transport === "REST") expect(await response.json()).toEqual({ sourceJobId: sourceId, destinationJobIds: [sourceId, destinationId] });
else expect((await mcpMessage(response)).result.structuredContent).toEqual({ sourceJobId: sourceId, destinationJobIds: [sourceId, destinationId] });
expect(f.persisted).toEqual([sourceId, 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, [sourceId, destinationId])).resolves.toEqual({ sourceJobId: sourceId, destinationJobIds: [sourceId, destinationId] });
expect(f.persisted).toEqual([sourceId, destinationId]);
await expect(service.setInvocationPermissions(sourceId, [destinationId])).resolves.toEqual({ sourceJobId: sourceId, destinationJobIds: [destinationId] });
expect(f.persisted).toEqual([destinationId]);
await expect(service.setInvocationPermissions(sourceId, [foreignId])).rejects.toMatchObject({ status: 400, code: "invalid_request" });
Expand Down
7 changes: 7 additions & 0 deletions packages/api/test/manual-invocation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ describe("manual invocation API and shared service", () => {
await expect(invoke({ sourceJobId: "forged", sourceRunId: "other-run" }, undefined, transport, identity)).rejects.toThrow();
});

it("allows an active run to invoke its own job only while its self-permission exists", async () => {
const self = { runId: "run-self", runJobId: "job-1", allowed: true };
const accepted = await invoke({ idempotencyKey: "successor-1" }, undefined, "REST", self);
expect(accepted.persisted.invocation).toMatchObject({ jobId: "job-1", sourceJobId: "job-1", sourceRunId: "run-self" });
await expect(invoke({}, undefined, "REST", { ...self, allowed: false })).rejects.toThrow();
});

it.each(["", "{{trigger-1.data.missing}}", "{{#invalid}}"])("falls back to the Job name for template %j", async template => {
expect((await invoke({}, template)).persisted.run.runName).toBe("dev");
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export function InvocationPermissionEditor({ jobId }: { jobId: string }) {
<Label>Search destination jobs <Input value={search} maxLength={120} onKeyDown={event => { if (event.key === "Enter") event.preventDefault(); }} onChange={event => setSearch(event.target.value)} /></Label>
{configured.isPending && <p role="status">Loading permissions…</p>}{configured.error && <p role="alert">{configured.error.message}</p>}
{jobs.isPending && <p role="status">Loading jobs…</p>}{jobs.error && <p role="alert">{jobs.error.message}</p>}
<Label className="block"><Input type="checkbox" checked={selected.includes(jobId)} onChange={event => setSelected(event.target.checked ? [...selected, jobId] : selected.filter(id => id !== jobId))} /> Current job (allow this job to invoke itself)</Label>
{jobs.data?.items.filter(job => job.id !== jobId).map(job => <Label key={job.id} className="block"><Input type="checkbox" checked={selected.includes(job.id)} onChange={event => setSelected(event.target.checked ? [...selected, job.id] : selected.filter(id => id !== job.id))} /> {job.name}</Label>)}
<Button type="button" disabled={save.isPending || configured.isPending} onClick={() => save.mutate()}>{save.isPending ? "Saving…" : "Save permissions"}</Button>
{save.error && <p role="alert">{save.error.message}</p>}
Expand Down
5 changes: 3 additions & 2 deletions packages/app/test/editor.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ test("All runs complete source jobs stay within the edited job project during se
assert.equal(projectA, current.projectId); assert.notEqual(projectA, projectB);
await context.close();
});
test("manual invocation permissions include tenant jobs from other projects and save selected destinations", async () => {
test("manual invocation permissions include the current job and tenant jobs from other projects", async () => {
const { context, page } = await setup();
const projectA = "00000000-0000-4000-8000-000000000020", destination = "00000000-0000-4000-8000-000000000024";
let saved, selectorUrl;
Expand All @@ -78,10 +78,11 @@ test("manual invocation permissions include tenant jobs from other projects and
});
await page.route("**/api/v1/job-selector?**", route => { selectorUrl = new URL(route.request().url()); return route.fulfill({ json: { items: [{ id: destination, name: "Cross project destination", slug: "cross-project", enabled: true }], nextCursor: null } }); });
await page.goto(origin + `/jobs/${id}/edit`);
await page.getByLabel("Current job (allow this job to invoke itself)", { exact: true }).check();
await page.getByLabel("Cross project destination", { exact: true }).check();
await page.getByRole("button", { name: "Save permissions" }).click();
await page.getByRole("status").filter({ hasText: "Manual invocation permissions saved." }).waitFor();
assert.deepEqual(saved, { destinationJobIds: [destination] });
assert.deepEqual(saved, { destinationJobIds: [id, destination] });
assert.equal(selectorUrl.searchParams.has("projectId"), false);
await context.close();
});
Expand Down
2 changes: 1 addition & 1 deletion packages/docs/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ Available states are `succeeded`, `failed`, `stopped`, and `edited`. **Edited**
## Manual job invocation permissions
Source: https://docs.factorize.sh/work/manual-invocation-permissions

Manual invocation permissions are separate from lifecycle subscriptions. Configure the allowed destination jobs in a source job's editor. The public API can read them with `GET /api/v1/jobs/{jobId}/invocation-permissions` and replace them with a `PUT` containing `{"destinationJobIds":["..."]}`. The write requires `jobs:write` and accepts a browser owner session, scoped API key, or authorized OAuth client. Destinations must exist in the same tenant. Deleting either job removes its permission edges. Revocation takes effect on the next invocation request.
Manual invocation permissions are separate from lifecycle subscriptions. Configure the allowed destination jobs in a source job's editor. The public API can read them with `GET /api/v1/jobs/{jobId}/invocation-permissions` and replace them with a `PUT` containing `{"destinationJobIds":["..."]}`. The write requires `jobs:write` and accepts a browser owner session, scoped API key, or authorized OAuth client. Destinations must exist in the same tenant. A job can include itself as a destination to opt in to explicitly requested successor runs; this does not schedule another run automatically. Deleting either job removes its permission edges. Revocation takes effect on the next invocation request.

Permissions are tenant-local. A destination may be in another project in the same tenant; graph consumers should render that as a cross-project edge. Existing lifecycle, edited, idle, schedule, and webhook triggers remain independent and do not grant manual invocation.

Expand Down
2 changes: 1 addition & 1 deletion packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8586,7 +8586,7 @@ paths:
put:
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.
Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must exist in the same tenant. A source job may include itself to opt in to explicitly requested successor runs; this does not schedule runs automatically. Lifecycle subscriptions do not create permissions.

Requires the jobs:write scope.

Expand Down
Loading
Loading