diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index f0bc8433..de4989ad 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -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. * diff --git a/packages/api/migrations/0028_allow_manual_self_invocation.sql b/packages/api/migrations/0028_allow_manual_self_invocation.sql new file mode 100644 index 00000000..0bc178c1 --- /dev/null +++ b/packages/api/migrations/0028_allow_manual_self_invocation.sql @@ -0,0 +1,2 @@ +ALTER TABLE app.manual_invocation_permissions + DROP CONSTRAINT manual_invocation_permissions_check; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 01d2e9c5..f5397520 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -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", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 151d4332..e11bc3a9 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -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]); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index a8306ee6..6c84c911 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -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().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id").notNull(), context: jsonb("context").$type>().notNull(), occurrence: jsonb("occurrence").$type(), 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'`)]); diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index 4e9d2365..c7434b92 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -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, { diff --git a/packages/api/test/manual-invocation-permissions.test.ts b/packages/api/test/manual-invocation-permissions.test.ts index 0a1313b3..32de0bee 100644 --- a/packages/api/test/manual-invocation-permissions.test.ts +++ b/packages/api/test/manual-invocation-permissions.test.ts @@ -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 }; } @@ -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" }); diff --git a/packages/api/test/manual-invocation.test.ts b/packages/api/test/manual-invocation.test.ts index ec1e9e5c..19156cfb 100644 --- a/packages/api/test/manual-invocation.test.ts +++ b/packages/api/test/manual-invocation.test.ts @@ -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"); }); diff --git a/packages/app/src/features/jobs/invocation-permission-editor.tsx b/packages/app/src/features/jobs/invocation-permission-editor.tsx index 287c0cf0..94004723 100644 --- a/packages/app/src/features/jobs/invocation-permission-editor.tsx +++ b/packages/app/src/features/jobs/invocation-permission-editor.tsx @@ -23,6 +23,7 @@ export function InvocationPermissionEditor({ jobId }: { jobId: string }) { {configured.isPending &&

Loading permissions…

}{configured.error &&

{configured.error.message}

} {jobs.isPending &&

Loading jobs…

}{jobs.error &&

{jobs.error.message}

} + {jobs.data?.items.filter(job => job.id !== jobId).map(job => )} {save.error &&

{save.error.message}

} diff --git a/packages/app/test/editor.browser.test.mjs b/packages/app/test/editor.browser.test.mjs index 8769bcdf..3cf88b39 100644 --- a/packages/app/test/editor.browser.test.mjs +++ b/packages/app/test/editor.browser.test.mjs @@ -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; @@ -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(); }); diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 6e7dfbbb..c9fbab30 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -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. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 2f632e9c..b92df4c0 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -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. diff --git a/packages/docs/work/manual-invocation-permissions.mdx b/packages/docs/work/manual-invocation-permissions.mdx index d6c52006..584c5cbc 100644 --- a/packages/docs/work/manual-invocation-permissions.mdx +++ b/packages/docs/work/manual-invocation-permissions.mdx @@ -3,7 +3,7 @@ title: Manual job invocation permissions description: Authorize jobs to start other jobs with run-scoped credentials and manage destination 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.