From 9decc3fc24582e9df982076ff82bfa3f918044a8 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 5 Nov 2026 19:44:32 +0000 Subject: [PATCH 1/3] Authorize run-scoped manual job invocation --- packages/api-client/src/schema.d.ts | 105 +++++++++++++ .../0026_manual_invocation_permissions.sql | 28 ++++ packages/api/src/api-contract.ts | 6 +- packages/api/src/exe-vm-backend.ts | 5 +- packages/api/src/flow-schemas.ts | 2 + packages/api/src/flow-service.ts | 40 ++++- packages/api/src/job-domain.ts | 6 +- packages/api/src/postgres/job-repository.ts | 6 +- .../api/src/postgres/run-query-repository.ts | 2 +- packages/api/src/postgres/run-scheduler.ts | 3 + packages/api/src/postgres/schema.ts | 8 +- packages/api/src/protected-api.ts | 2 + packages/api/src/run-credentials.ts | 36 +++++ packages/api/src/run-read-contracts.ts | 2 +- packages/api/src/types.ts | 6 +- packages/api/src/worker.ts | 6 + packages/api/test/api-boundary.test.ts | 2 +- packages/api/test/execution-backend.test.ts | 6 +- .../api/test/job-lifecycle.postgres.test.ts | 10 ++ .../manual-invocation-permissions.test.ts | 46 ++++++ packages/api/test/manual-invocation.test.ts | 15 +- packages/api/test/run-credentials.test.ts | 23 +++ packages/app/src/features/jobs/editor.tsx | 3 +- .../jobs/invocation-permission-editor.tsx | 31 ++++ packages/app/test/editor.browser.test.mjs | 21 ++- packages/docs/docs.json | 1 + packages/docs/llms-full.txt | 22 +++ packages/docs/llms.txt | 1 + packages/docs/mcp/tools.mdx | 2 + packages/docs/openapi.yaml | 140 ++++++++++++++++++ .../work/manual-invocation-permissions.mdx | 21 +++ 31 files changed, 584 insertions(+), 23 deletions(-) create mode 100644 packages/api/migrations/0026_manual_invocation_permissions.sql create mode 100644 packages/api/src/run-credentials.ts create mode 100644 packages/api/test/manual-invocation-permissions.test.ts create mode 100644 packages/api/test/run-credentials.test.ts create mode 100644 packages/app/src/features/jobs/invocation-permission-editor.tsx create mode 100644 packages/docs/work/manual-invocation-permissions.mdx diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 95b3b0fd..e7cda244 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1278,6 +1278,36 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/jobs/{jobId}/invocation-permissions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List a source job's manual invocation destinations + * @description Requires the jobs:read scope. + * + * Accepts a scoped bearer token or interactive owner session. + */ + 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. + * + * Requires the jobs:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_jobs_jobId_invocation_permissions"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/jobs/{jobId}/events": { parameters: { query?: never; @@ -5542,6 +5572,81 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_jobs_jobId_invocation_permissions: { + parameters: { + query?: never; + header?: never; + path: { + jobId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Configured tenant-local destination jobs */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + sourceJobId: string; + destinationJobIds: string[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_jobs_jobId_invocation_permissions: { + parameters: { + query?: never; + header?: never; + path: { + jobId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + destinationJobIds: string[]; + }; + }; + }; + responses: { + /** @description Saved manual invocation permissions */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + sourceJobId: string; + destinationJobIds: string[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_jobs_jobId_events: { parameters: { query?: { diff --git a/packages/api/migrations/0026_manual_invocation_permissions.sql b/packages/api/migrations/0026_manual_invocation_permissions.sql new file mode 100644 index 00000000..253de6d7 --- /dev/null +++ b/packages/api/migrations/0026_manual_invocation_permissions.sql @@ -0,0 +1,28 @@ +CREATE TABLE app.manual_invocation_permissions ( + tenant_id uuid NOT NULL, + source_job_id uuid NOT NULL, + destination_job_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, source_job_id, destination_job_id), + FOREIGN KEY (tenant_id, source_job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, + FOREIGN KEY (tenant_id, destination_job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, + CHECK (source_job_id <> destination_job_id) +); +CREATE INDEX manual_invocation_permissions_destination ON app.manual_invocation_permissions(tenant_id,destination_job_id); + +CREATE TABLE app.run_credentials ( + tenant_id uuid NOT NULL, + run_id uuid NOT NULL, + digest text NOT NULL, + user_id uuid NOT NULL, + session_version integer NOT NULL, + expires_at timestamptz NOT NULL, + PRIMARY KEY (tenant_id,run_id), + FOREIGN KEY (tenant_id,run_id) REFERENCES app.job_runs(tenant_id,id) ON DELETE CASCADE, + FOREIGN KEY (tenant_id,user_id) REFERENCES app.members(tenant_id,user_id) ON DELETE CASCADE +); +CREATE INDEX run_credentials_digest ON app.run_credentials(digest); + +ALTER TABLE app.invocations ADD COLUMN source_job_id uuid; +ALTER TABLE app.invocations ADD COLUMN source_run_id uuid; +CREATE INDEX invocations_source_run ON app.invocations(tenant_id,source_run_id) WHERE source_run_id IS NOT NULL; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 89028036..47a0a16b 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -13,6 +13,8 @@ import { manualInvocationSchema, renameRunSchema, reportRunErrorSchema, + invocationPermissionsInput, + invocationPermissionsResponse, reportRunErrorResponse, jobConditionsTestSchema, listRunsSchema, @@ -712,7 +714,7 @@ export const API_ROUTES: RouteContract[] = [ route( "POST", "/api/v1/jobs/{jobId}/invocations", - "runs:write", + "runs:invoke", { summary: "Invoke job", responses: { @@ -742,6 +744,8 @@ export const API_ROUTES: RouteContract[] = [ (service, { params, body }) => service.invokeJob(params.jobId, body), { body: manualInvocationSchema }, ), + 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( "GET", "/api/v1/jobs/{jobId}/events", diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index 82c8bf8a..73b8abbf 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -19,7 +19,10 @@ export function isOwnedVmName(vm: string): boolean { } function harnessCommand(harness: NonNullable): string { - const environment = Object.entries(harness.env).map(([name, value]) => `${name}=${shellAtom(value)}`); + const environment = Object.entries(harness.env).map(([name, value]) => { + if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) throw new Error("Invalid harness environment variable name"); + return shellAtom(`--setenv=${name}=${value}`); + }); return [...environment, harness.executable, ...harness.args].map((value, index) => index < environment.length ? value : shellAtom(value)).join(" "); } diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 4ca77536..181bc8c1 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -15,6 +15,8 @@ export const listRunsSchema = z.object({ limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), }).refine(value => !value.direction || value.sort, { message: "direction requires sort" }); export const runIdSchema = z.object({ runId: z.string().min(1) }); +export const invocationPermissionsInput = z.object({ destinationJobIds: z.array(z.guid()).max(1000) }).strict(); +export const invocationPermissionsResponse = z.object({ sourceJobId: z.guid(), destinationJobIds: z.array(z.guid()) }); export const renameRunSchema = z.object({ name: z.string().trim().min(1).max(120), expectedName: z.string().max(120).optional() }).strict(); export const reportRunErrorSchema = z.object({ reason: z.string().trim().min(1).max(2000) }).strict(); export const reportRunErrorResponse = z.object({ reported: z.literal(true), reason: z.string(), retry: z.boolean() }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 322830ba..84445e88 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -24,7 +24,7 @@ import { IntegrationService } from "./postgres/integration-service"; import { OperationsRepository } from "./postgres/operations-repository"; import { installedTriggerAvailability } from "./trigger-availability"; import { evaluateWebhookConditions } from "./webhook-conditions"; -import { jobConditionsTestSchema } from "./flow-schemas"; +import { jobConditionsTestSchema, invocationPermissionsResponse } from "./flow-schemas"; import { ProviderCatalog } from "./postgres/provider-catalog"; import { ArtifactRepository } from "./postgres/artifact-repository"; import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken, normalizeScopes } from "./access-tokens"; @@ -187,7 +187,7 @@ export class ApiService { const run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); - delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; + delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, source_job_id: run.invocation_source_job_id ?? null, source_run_id: run.invocation_source_run_id ?? null, created_at: run.invocation_created_at }; const [activity, projection, cursor, artifacts] = await Promise.all([ repository.activity(runId), databaseFor(this.env).pool.query("SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId]), @@ -333,13 +333,45 @@ export class ApiService { } async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("jobs:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); await this.wakeScheduler(); return { id: jobId, enabled }; } async invokeJob(jobId: string, input: ManualInvocationInput) { - await this.authorize("runs:cancel"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); + await this.authorize("runs:invoke"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); + if (this.auth.authMethod === "run_token") { + if (!this.auth.runId || !this.auth.runJobId) throw new ServiceError(401, "invalid_token", "A verified run identity is required."); + const permission = await databaseFor(this.env).pool.query(`SELECT 1 FROM app.run_credentials c + JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id + JOIN app.manual_invocation_permissions p ON p.tenant_id=c.tenant_id AND p.source_job_id=r.job_id AND p.destination_job_id=$3 + WHERE c.tenant_id=$1 AND c.run_id=$2 AND c.digest=$4 AND c.expires_at>now() AND r.state IN ('reserved','starting','running','blocked','stopping')`, [this.auth.tenantId, this.auth.runId, jobId, this.auth.runCredentialDigest]); + if (!permission.rowCount) throw new ServiceError(403, "forbidden", "This run is no longer active or its source job is not authorized to invoke the destination."); + } const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled"); const service = new InvocationService(repository, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); - const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey: input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`, context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); + const claimKey = input.idempotencyKey ? `manual:${this.auth.authMethod === "run_token" ? `run:${this.auth.runId}:` : ""}${input.idempotencyKey}` : `manual:${crypto.randomUUID()}`; + const result = await service.invoke(jobId, { source: "manual", name: input.name, triggerId: trigger.id, claimKey, ...(this.auth.authMethod === "run_token" ? { sourceJobId: this.auth.runJobId, sourceRunId: this.auth.runId } : {}), context: { [trigger.slug]: { prompt: input.prompt, data: input.data ?? {} } } }); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; } + async getInvocationPermissions(sourceJobId: string) { + await this.authorize("jobs:read"); + if (!await this.jobs().getJob(sourceJobId)) throw new ServiceError(404, "not_found", "Job not found"); + const rows = await databaseFor(this.env).pool.query<{ destination_job_id: string }>("SELECT destination_job_id FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2 ORDER BY destination_job_id", [this.auth.tenantId, sourceJobId]); + return publicValue(invocationPermissionsResponse, { sourceJobId, destinationJobIds: rows.rows.map(row => row.destination_job_id) }); + } + async setInvocationPermissions(sourceJobId: string, destinationJobIds: string[]) { + await this.authorizeOwnerSession("jobs:write"); + 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); + 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]); + if (!sources.rowCount) throw new ServiceError(404, "not_found", "Source job not found"); + if (unique.length) { + const found = await client.query("SELECT id FROM app.jobs WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [this.auth.tenantId, unique]); + if (found.rowCount !== unique.length) throw new ServiceError(400, "invalid_request", "Every destination must be an existing job in this tenant."); + } + await client.query("DELETE FROM app.manual_invocation_permissions WHERE tenant_id=$1 AND source_job_id=$2", [this.auth.tenantId, sourceJobId]); + if (unique.length) await client.query("INSERT INTO app.manual_invocation_permissions(tenant_id,source_job_id,destination_job_id) SELECT $1,$2,unnest($3::uuid[])", [this.auth.tenantId, sourceJobId, unique]); + }); + return publicValue(invocationPermissionsResponse, { sourceJobId, destinationJobIds: unique }); + } async diagnoseExeIntegration(connectionId: string) { await this.authorize("integrations:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; } async listJobTriggerAvailability() { await this.authorize("jobs:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } async previewSchedule(input: unknown) { diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 5a6cd760..79ff56c1 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -53,6 +53,8 @@ export interface InvocationRequest { context: Record; /** Stable, source-owned key used to claim this occurrence exactly once. */ claimKey: string; + sourceJobId?: string; + sourceRunId?: string; occurrence?: { occurredAt?: string; externalId?: string; metadata?: Record }; } @@ -63,6 +65,8 @@ export interface Invocation { claimKey: string; triggerId: string; context: Record; + sourceJobId?: string; + sourceRunId?: string; occurrence?: InvocationRequest["occurrence"]; createdAt: string; } @@ -140,7 +144,7 @@ export class InvocationService { if (!input.triggerId || !input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new InvocationError("invalid_invocation", "A trigger and structured context are required."); const createdAt = this.clock(); - const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; + const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.sourceJobId ? { sourceJobId: input.sourceJobId } : {}), ...(input.sourceRunId ? { sourceRunId: input.sourceRunId } : {}), ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; const selectedSkills = (job.selectedSkills ?? []).sort((a, b) => a.position - b.position); const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), encryptedSkillSnapshot: selectedSkills.length ? await this.encryptSnapshot(JSON.stringify(selectedSkills.map(skill => ({ id: skill.id, key: skill.key, revision: skill.revision, body: skill.body, order: skill.position })))) : undefined, runName: (input.source === "manual" ? input.name?.trim() : undefined) || renderRunName(job.runNameTemplate ?? "", input.context, job.name), createdAt, updatedAt: createdAt }; if (!await this.repository.insertInvocationAndRun(invocation, run)) { diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 70fd7778..7d3416d3 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -142,15 +142,15 @@ export class PostgresJobRepository implements JobRepository { async delete(id: string): Promise { return Boolean((await this.database.orm.delete(jobs).where(and(eq(jobs.tenantId, this.tenantId), eq(jobs.id, id))).returning({ id: jobs.id })).length); } async findInvocation(jobId: string, claimKey: string) { - const result = await this.database.pool.query(`SELECT i.id invocation_id,i.job_id,i.source,i.claim_key,i.trigger_id,i.context,i.occurrence,i.created_at invocation_created_at,r.id run_id,r.state run_state,r.encrypted_prompt,r.encrypted_skill_snapshot,r.run_name,r.created_at run_created_at,r.updated_at run_updated_at,r.started_at + const result = await this.database.pool.query(`SELECT i.id invocation_id,i.job_id,i.source,i.claim_key,i.trigger_id,i.context,i.occurrence,i.source_job_id,i.source_run_id,i.created_at invocation_created_at,r.id run_id,r.state run_state,r.encrypted_prompt,r.encrypted_skill_snapshot,r.run_name,r.created_at run_created_at,r.updated_at run_updated_at,r.started_at FROM app.invocations i JOIN app.job_runs r ON r.tenant_id=i.tenant_id AND r.invocation_id=i.id WHERE i.tenant_id=$1 AND i.job_id=$2 AND i.claim_key=$3`, [this.tenantId, jobId, claimKey]); const row = result.rows[0]; if (!row) return null; - return { invocation: { id: row.invocation_id, jobId: row.job_id, source: row.source, claimKey: row.claim_key, triggerId: row.trigger_id, context: row.context, ...(row.occurrence ? { occurrence: row.occurrence } : {}), createdAt: row.invocation_created_at.toISOString() } as Invocation, run: { id: row.run_id, jobId: row.job_id, invocationId: row.invocation_id, state: row.run_state, encryptedPrompt: row.encrypted_prompt, ...(row.encrypted_skill_snapshot ? { encryptedSkillSnapshot: row.encrypted_skill_snapshot } : {}), ...(row.run_name ? { runName: row.run_name } : {}), createdAt: row.run_created_at.toISOString(), updatedAt: row.run_updated_at.toISOString(), ...(row.started_at ? { startedAt: row.started_at.toISOString() } : {}) } as JobRun }; + return { invocation: { id: row.invocation_id, jobId: row.job_id, source: row.source, claimKey: row.claim_key, triggerId: row.trigger_id, context: row.context, ...(row.source_job_id ? { sourceJobId: row.source_job_id } : {}), ...(row.source_run_id ? { sourceRunId: row.source_run_id } : {}), ...(row.occurrence ? { occurrence: row.occurrence } : {}), createdAt: row.invocation_created_at.toISOString() } as Invocation, run: { id: row.run_id, jobId: row.job_id, invocationId: row.invocation_id, state: row.run_state, encryptedPrompt: row.encrypted_prompt, ...(row.encrypted_skill_snapshot ? { encryptedSkillSnapshot: row.encrypted_skill_snapshot } : {}), ...(row.run_name ? { runName: row.run_name } : {}), createdAt: row.run_created_at.toISOString(), updatedAt: row.run_updated_at.toISOString(), ...(row.started_at ? { startedAt: row.started_at.toISOString() } : {}) } as JobRun }; } async insertInvocationAndRun(invocation: Invocation, run: JobRun): Promise { return this.database.transaction(async client => { const concurrencyLimit = await lockJobQueue(client, this.tenantId, invocation.jobId); - const inserted = await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING", [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.createdAt]); + const inserted = await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,source_job_id,source_run_id,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING", [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.sourceJobId ?? null, invocation.sourceRunId ?? null, invocation.createdAt]); if (!inserted.rowCount) return false; await reserveExecutionSlot(client, this.tenantId, invocation.jobId, run, concurrencyLimit); await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,encrypted_skill_snapshot,run_name,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)", [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, run.encryptedSkillSnapshot ?? null, run.runName ?? "", run.createdAt, run.updatedAt]); diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 0d5cfaf2..1c0e0c7a 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -64,7 +64,7 @@ export class RunQueryRepository { return { items: rows, nextCursor }; } async get(runId: string) { - return (await this.database.pool.query(`SELECT r.*,j.name job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.created_at invocation_created_at + return (await this.database.pool.query(`SELECT r.*,j.name job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.source_job_id invocation_source_job_id,i.source_run_id invocation_source_run_id,i.created_at invocation_created_at FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id WHERE r.tenant_id=$1 AND r.id=$2`, [this.tenantId, runId])).rows[0] ?? null; } async status(runId: string) { diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 2e564006..27b23458 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -18,6 +18,7 @@ import { rolloutTraceSources } from "../trace-source"; import { TraceProjectionRepository, TRACE_PARSER_VERSION } from "./trace-projection-repository"; import { LiveTraceRepository } from "./live-trace-repository"; import { JOB_RESULT_INSTRUCTIONS, parseJobResult } from "../job-result"; +import { issueRunCredential } from "../run-credentials"; export class RunScheduler { private runs: RunRepository; @@ -43,6 +44,8 @@ export class RunScheduler { const backend = await this.backend(run), driver = agentDriver(run.executionConfig.agentKind as AgentKind), harness = driver.launch(run.id, { model: run.executionConfig.model, effort: run.executionConfig.effort }); const sources = rolloutTraceSources(driverTraceSources(driver.kind, harness), run.tenantId, this.env); validateTraceSources(sources); + const runToken = await issueRunCredential(this.env, run.tenantId, run.id); + Object.assign(harness.env, { FACTORIZE_API_URL: `${this.env.APP_ORIGIN}/api/v1`, FACTORIZE_RUN_TOKEN: runToken }); const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const launched = await backend.launch({ runId: run.id, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}`, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env } }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 22fb9c19..a8a5b668 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -63,8 +63,9 @@ export const webhookConditionsCutover = app.table("webhook_conditions_cutover", tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), wasEnabled: boolean("was_enabled").notNull(), conditions: jsonb("conditions").$type>().notNull(), restoredAt: timestamp("restored_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade")]); 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(), 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')`)]); + 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 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'`)]); @@ -81,6 +82,7 @@ export const runTraceEvents = app.table("run_trace_events", { }, t => [primaryKey({ columns: [t.tenantId, t.runId, t.sequence] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("run_trace_events_search").using("gin", t.searchVector), index("run_trace_events_by_type").on(t.tenantId, t.runId, t.eventType, t.sequence)]); export const runActivity = app.table("run_activity", { tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), runId: uuid("run_id").notNull(), action: text("action").notNull(), detail: text("detail").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.id] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); export const activeClaims = app.table("active_claims", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), claimKey: text("claim_key").notNull(), runId: uuid("run_id").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.jobId, t.claimKey] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade")]); +export const runCredentials = app.table("run_credentials", { tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), digest: text("digest").notNull(), userId: uuid("user_id").notNull(), sessionVersion: integer("session_version").notNull(), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull() }, t => [primaryKey({ columns: [t.tenantId, t.runId] }), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [jobRuns.tenantId, jobRuns.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.userId], foreignColumns: [members.tenantId, members.userId] }).onDelete("cascade"), index("run_credentials_digest").on(t.digest)]); export const scheduleState = app.table("schedule_state", { tenantId: uuid("tenant_id").notNull(), triggerId: uuid("trigger_id").notNull(), jobId: uuid("job_id").notNull(), nextRunAt: timestamp("next_run_at", { withTimezone: true }), lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }) }, t => [primaryKey({ columns: [t.tenantId, t.triggerId] }), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("schedules_due").on(t.nextRunAt).where(sql`${t.nextRunAt} is not null`)]); export const automaticWakes = app.table("automatic_wakes", { tenantId: uuid("tenant_id").notNull(), jobId: uuid("job_id").notNull(), trailingPending: boolean("trailing_pending").notNull().default(false), summary: jsonb("summary").$type>().notNull().default({}), updatedAt: updatedAt() }, t => [primaryKey({ columns: [t.tenantId, t.jobId] }), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade")]); @@ -133,7 +135,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, jobRuns, runs, runArtifacts, + connections, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runCredentials, runs, runArtifacts, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, jobEditDeliveries, jobEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, runTraceCursors, runTraceChunks, runTraceProjections, traceReplayLimits, traceReplayOperations, diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index 7678e8a5..54d1ff33 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -136,6 +136,8 @@ function createMcpServer(service: ApiService): McpServer { tool("enable_job", "Enable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, true)); 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("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)); diff --git a/packages/api/src/run-credentials.ts b/packages/api/src/run-credentials.ts new file mode 100644 index 00000000..372a21b2 --- /dev/null +++ b/packages/api/src/run-credentials.ts @@ -0,0 +1,36 @@ +import type { Env, OAuthProps } from "./types"; +import { databaseFor } from "./postgres/database"; +import { accessTokenDigest } from "./access-tokens"; + +const encode = (value: string) => btoa(String.fromCharCode(...new TextEncoder().encode(value))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +const encodeBytes = (value: Uint8Array) => btoa(String.fromCharCode(...value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +const decode = (value: string) => new TextDecoder().decode(Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4)), c => c.charCodeAt(0))); + +/** One-use issuance per launch attempt; only a digest is persisted. */ +export async function issueRunCredential(env: Env, tenantId: string, runId: string): Promise { + const secret = crypto.getRandomValues(new Uint8Array(32)); + const token = `fzt_run_${encode(runId)}_${encodeBytes(secret)}`; + const db = databaseFor(env); + const owner = (await db.pool.query<{ user_id: string; session_version: number }>("SELECT user_id,session_version FROM app.members WHERE tenant_id=$1 AND role='owner' ORDER BY user_id LIMIT 1", [tenantId])).rows[0]; + if (!owner) throw new Error("Run owner is unavailable"); + await db.pool.query(`INSERT INTO app.run_credentials(tenant_id,run_id,digest,user_id,session_version,expires_at) + VALUES ($1,$2,$3,$4,$5,now()+interval '24 hours') ON CONFLICT (tenant_id,run_id) DO UPDATE SET digest=excluded.digest,user_id=excluded.user_id,session_version=excluded.session_version,expires_at=excluded.expires_at`, [tenantId, runId, await accessTokenDigest(token), owner.user_id, owner.session_version]); + return token; +} + +export async function authenticateRunCredential(request: Request, env: Env): Promise { + const value = request.headers.get("Authorization")?.match(/^Bearer (fzt_run_[A-Za-z0-9_-]+_[A-Za-z0-9_-]{43})$/)?.[1]; + if (!value) return null; + const match = value.match(/^fzt_run_([A-Za-z0-9_-]+)_([A-Za-z0-9_-]{43})$/); + if (!match) return null; + let runId: string; + try { runId = decode(match[1]!); } catch { return null; } + if (!/^[0-9a-f-]{36}$/i.test(runId)) return null; + const digest = await accessTokenDigest(value); + const result = await databaseFor(env).pool.query<{ tenant_id: string; user_id: string; session_version: number; job_id: string }>(`SELECT c.tenant_id,c.user_id,c.session_version,r.job_id + FROM app.run_credentials c JOIN app.job_runs r ON r.tenant_id=c.tenant_id AND r.id=c.run_id + JOIN app.members m ON m.tenant_id=c.tenant_id AND m.user_id=c.user_id AND m.role='owner' AND m.session_version=c.session_version + WHERE c.run_id=$1 AND c.digest=$2 AND c.expires_at>now() AND r.state IN ('reserved','starting','running','blocked','stopping')`, [runId, digest]); + const row = result.rows[0]; + return row ? { tenantId: row.tenant_id, userId: row.user_id, sessionVersion: row.session_version, scopes: ["runs:invoke"], authMethod: "run_token", runId, runJobId: row.job_id, runCredentialDigest: digest } : null; +} diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index e12ae53d..95f70e17 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -38,7 +38,7 @@ export const fullRunResponse = runSummaryResponse.extend({ execution_backend_kind: z.string(), execution_capabilities: z.array(z.string()), claim_released: z.boolean(), vm_cleanup_attempt: z.number().int(), cleanup_next_at: z.string().nullable(), vm_cleanup_complete: z.boolean(), job_name: z.string(), prompt: z.string(), context: record, occurrence: record.nullable(), - invocation: z.object({ id: z.string(), source: z.string(), claim_key: z.string(), trigger_id: z.string().nullable(), context: record, occurrence: record.nullable(), created_at: z.string() }), + invocation: z.object({ id: z.string(), source: z.string(), claim_key: z.string(), trigger_id: z.string().nullable(), context: record, occurrence: record.nullable(), source_job_id: z.string().nullable(), source_run_id: z.string().nullable(), created_at: z.string() }), invocation_source: z.string(), invocation_claim_key: z.string(), invocation_trigger_id: z.string().nullable(), invocation_created_at: z.string(), activity: z.array(z.object({ action: z.string(), detail: z.string(), created_at: z.string() })), execution_diagnostics: record.nullable(), trace_sources: z.object({ primary: traceSource, nativeSession: traceSource.optional() }).nullable(), trace_projection: record.nullable(), trace_generation: z.string().nullable(), harness_log: record.nullable(), diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 494f42bc..e494c1cb 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -40,10 +40,14 @@ export type OAuthProps = { sessionVersion: number; scopes: string[]; accessTokenId?: string; + /** Set only by a verified, active execution credential. */ + runId?: string; + runJobId?: string; + runCredentialDigest?: string; /** Stable identifier for the OAuth authorization grant; never a bearer token. */ oauthGrantId?: string; oauthClientId?: string; - authMethod?: "session" | "oauth" | "access_token"; + authMethod?: "session" | "oauth" | "access_token" | "run_token"; }; export interface WorkItem { diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index 4b220e61..d7868347 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -9,6 +9,7 @@ import { consentDecision } from "./consent-api"; import { addDeviceMetadata, DEVICE_GRANT, deviceAuthorization, deviceClientRegistration, deviceToken, deviceVerification } from "./device-oauth"; import type { Env, OAuthProps } from "./types"; import { ACCESS_SCOPES, authenticateAccessToken } from "./access-tokens"; +import { authenticateRunCredential } from "./run-credentials"; import { artifactUpload } from "./artifact-upload"; import { traceChunkUpload } from "./trace-chunk-upload"; import { databaseFor } from "./postgres/database"; @@ -102,6 +103,11 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) return protectedApiFetch(request, apiEnv, { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes, authMethod: "session" }, ctx); } if ((url.pathname === "/mcp" || url.pathname.startsWith("/api/v1")) && request.headers.get("Authorization")?.startsWith("Bearer fzt_")) { + if (request.headers.get("Authorization")?.startsWith("Bearer fzt_run_")) { + const auth = await authenticateRunCredential(request, env); + if (!auth) return Response.json({ error: { code: "invalid_token", message: "The run credential is invalid, expired, revoked, or no longer active." } }, { status: 401, headers: { "WWW-Authenticate": "Bearer error=\"invalid_token\"" } }); + return protectedApiFetch(request, apiEnv, auth, ctx); + } const auth = await authenticateAccessToken(request, env); if (!auth) return Response.json({ error: { code: "invalid_token", message: "The access token is invalid, expired, or revoked." } }, { status: 401, headers: { "WWW-Authenticate": "Bearer error=\"invalid_token\"" } }); return protectedApiFetch(request, apiEnv, auth, ctx); diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index 7cd7909b..6908c1ee 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -176,7 +176,7 @@ describe("Worker OpenAPI request/response boundaries", () => { }); it("documents the job name in run detail for clients with only runs:read", async () => { - vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, job_result: null, run_artifacts: [], prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); + vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, source_job_id: null, source_run_id: null, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); const result = await assertResponse(await request("GET", "/api/v1/runs/run-1", undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", "/api/v1/runs/{runId}", 200); expect(result.job_name).toBe("Job name"); }); diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index 1e8b4e98..1ad1dc9e 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -66,7 +66,9 @@ describe("ExeVmBackend", () => { requests.push(String(init.body)); return new Response(requests.length === 1 ? '{"name":"factorize-run-1"}' : "started", { headers: { "X-Exe-Exit": "0" } }); })); - const launched = await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "do the work", harness: agentDriver("codex").launch("run-1", {}), traceSources: { primary: { kind: "execution_stream", path: "/tmp/trace/events.jsonl", mediaType: "application/x-ndjson", provider: "codex" } } }); + const harness = agentDriver("codex").launch("run-1", {}); + harness.env = { FACTORIZE_API_URL: "https://app.test/api/v1", FACTORIZE_RUN_TOKEN: "secret-run-token" }; + const launched = await new ExeVmBackend(connection).launch({ runId: "run-1", prompt: "do the work", harness, traceSources: { primary: { kind: "execution_stream", path: "/tmp/trace/events.jsonl", mediaType: "application/x-ndjson", provider: "codex" } } }); expect(launched.handle).toEqual({ backendKind: "exe-vm", id: "factorize-run-1" }); expect(requests[0]).toContain("new --name='factorize-run-1'"); expect(requests[0]).toContain("--tag='github'"); @@ -79,6 +81,8 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("model_provider=exe-llm"); expect(requests[1]).toContain("model_providers.exe-llm.base_url=\"https://llm.int.exe.xyz/v1\""); expect(requests[1]).toContain("sudo systemd-run"); + expect(requests[1]).toContain("'--setenv=FACTORIZE_API_URL=https://app.test/api/v1'"); + expect(requests[1]).toContain("'--setenv=FACTORIZE_RUN_TOKEN=secret-run-token'"); expect(requests[1]).toContain("--uid=exedev --gid=exedev"); expect(requests[1]).toContain("--property=Type=exec"); expect(requests[1]).toContain("--property=RemainAfterExit=yes"); diff --git a/packages/api/test/job-lifecycle.postgres.test.ts b/packages/api/test/job-lifecycle.postgres.test.ts index f00d3296..affd6019 100644 --- a/packages/api/test/job-lifecycle.postgres.test.ts +++ b/packages/api/test/job-lifecycle.postgres.test.ts @@ -73,6 +73,16 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po expect(await deliveries()).toHaveLength(1); }); + it("stores manual permissions tenant-locally and removes their edges when a job is deleted", async () => { + 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("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 new file mode 100644 index 00000000..f01361dc --- /dev/null +++ b/packages/api/test/manual-invocation-permissions.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ApiService, ServiceError } from "../src/flow-service"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {} })); +afterEach(() => vi.restoreAllMocks()); + +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) => 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 }); + 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"); + }); + + 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) => 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 }); + }); +}); diff --git a/packages/api/test/manual-invocation.test.ts b/packages/api/test/manual-invocation.test.ts index 9a181126..ec1e9e5c 100644 --- a/packages/api/test/manual-invocation.test.ts +++ b/packages/api/test/manual-invocation.test.ts @@ -10,7 +10,7 @@ afterEach(() => vi.restoreAllMocks()); describe("manual invocation API and shared service", () => { const name = "GEN-2106 — Issue title"; - async function invoke(input: Record, template = "{{trigger-1.data.identifier}} — {{trigger-1.data.title}}", transport = "REST") { + async function invoke(input: Record, template = "{{trigger-1.data.identifier}} — {{trigger-1.data.title}}", transport = "REST", sourceAuth?: { runId: string; runJobId: string; allowed: boolean }) { const job: Job = { id: "job-1", name: "dev", slug: "dev", promptTemplate: "{{trigger-1.prompt}} {{trigger-1.data.identifier}}", runNameTemplate: template, model: "", executionConfig: { connectionId: "exe-1", workspace: "", cwd: "", agentKind: "codex" }, @@ -26,12 +26,12 @@ describe("manual invocation API and shared service", () => { vi.spyOn(ApiService.prototype as any, "authorize").mockResolvedValue(undefined); vi.spyOn(ApiService.prototype as any, "jobs").mockReturnValue(repository); const key = btoa("a".repeat(32)); - const env = { CREDENTIAL_ENCRYPTION_KEY: key, APP_ORIGIN: "https://example.com" } as any; + const env = { CREDENTIAL_ENCRYPTION_KEY: key, APP_ORIGIN: "https://example.com", DATABASE: { pool: { query: async () => ({ rows: sourceAuth?.allowed ? [{ ok: 1 }] : [], rowCount: sourceAuth?.allowed ? 1 : 0 }) } } } as any; const request = async (body: Record) => { const response = await protectedApiFetch(new Request("https://example.com" + (transport === "REST" ? "/api/v1/jobs/job-1/invocations" : "/mcp"), { method: "POST", headers: { Origin: env.APP_ORIGIN, Host: "example.com", "Content-Type": "application/json", Accept: "application/json, text/event-stream" }, body: JSON.stringify(transport === "REST" ? body : { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "invoke_job", arguments: { jobId: "job-1", ...body } } }), - }), env, { scopes: ["runs:write"], authMethod: "session" } as any, {} as any); + }), env, sourceAuth ? { scopes: ["runs:invoke"], authMethod: "run_token", runId: sourceAuth.runId, runJobId: sourceAuth.runJobId } as any : { scopes: ["runs:write"], authMethod: "session" } as any, {} as any); if (transport === "REST") return response; expect(response.status).toBe(200); const text = await response.text(); @@ -61,6 +61,15 @@ describe("manual invocation API and shared service", () => { expect((await invoke({})).persisted.run.runName).toBe(name); }); + it.each(["REST", "MCP"]) ("derives job/run provenance and enforces permission through %s", async transport => { + const identity = { runId: "run-source", runJobId: "job-source", allowed: true }; + const accepted = await invoke({ idempotencyKey: "retry-1" }, undefined, transport, identity); + expect(accepted.persisted.invocation).toMatchObject({ sourceJobId: "job-source", sourceRunId: "run-source" }); + expect(await (await accepted.request({ idempotencyKey: "retry-1" })).json()).toEqual({ ...accepted.result, duplicate: true }); + await expect(invoke({}, undefined, transport, { ...identity, allowed: false })).rejects.toThrow(); + await expect(invoke({ sourceJobId: "forged", sourceRunId: "other-run" }, undefined, transport, identity)).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/api/test/run-credentials.test.ts b/packages/api/test/run-credentials.test.ts new file mode 100644 index 00000000..39bc122a --- /dev/null +++ b/packages/api/test/run-credentials.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { authenticateRunCredential, issueRunCredential } from "../src/run-credentials"; + +describe("run-scoped execution credentials", () => { + it("binds a short-lived bearer credential to its active tenant, job, and run", async () => { + let storedDigest = "", active = true; + const database = { pool: { query: async (sql: string, values: unknown[] = []) => { + if (sql.includes("SELECT user_id,session_version")) return { rows: [{ user_id: "owner-1", session_version: 7 }], rowCount: 1 }; + if (sql.includes("INSERT INTO app.run_credentials")) { storedDigest = String(values[2]); return { rows: [], rowCount: 1 }; } + if (sql.includes("FROM app.run_credentials c")) return active && values[1] === storedDigest ? { rows: [{ tenant_id: "tenant-1", user_id: "owner-1", session_version: 7, job_id: "job-1" }], rowCount: 1 } : { rows: [], rowCount: 0 }; + throw new Error(`Unexpected SQL: ${sql}`); + } } } as any; + const env = { DATABASE: database } as any; + const token = await issueRunCredential(env, "tenant-1", "00000000-0000-4000-8000-000000000001"); + const request = (credential: string) => new Request("https://example.test/api/v1", { headers: { Authorization: `Bearer ${credential}` } }); + const auth = await authenticateRunCredential(request(token), env); + expect(auth).toMatchObject({ tenantId: "tenant-1", userId: "owner-1", scopes: ["runs:invoke"], authMethod: "run_token", runJobId: "job-1", runId: "00000000-0000-4000-8000-000000000001" }); + expect(auth?.runCredentialDigest).toBe(storedDigest); + expect(await authenticateRunCredential(request(token + "forged"), env)).toBeNull(); + active = false; + expect(await authenticateRunCredential(request(token), env)).toBeNull(); + }); +}); diff --git a/packages/app/src/features/jobs/editor.tsx b/packages/app/src/features/jobs/editor.tsx index 6630e038..773563af 100644 --- a/packages/app/src/features/jobs/editor.tsx +++ b/packages/app/src/features/jobs/editor.tsx @@ -12,6 +12,7 @@ import { metadataQuery, targetsQuery } from "./editor-queries"; import { canonicalizeVmImage, editableJob, emptyJob, reconcile, validateJobInput, writeInput, type Job, type JobInput } from "./editor-state"; import { TemplateField } from "./template-field"; import { TriggerEditor } from "./trigger-editor"; +import { InvocationPermissionEditor } from "./invocation-permission-editor"; import { messageOf } from "../auth/session"; import { projectQuery, projectsQuery } from "../projects/queries"; import { AutosaveStatus, useDebouncedAutosave } from "../../shared/use-debounced-autosave"; @@ -95,7 +96,7 @@ function EditorForm({ initial }: { initial?: Job }) {

Skills

Ordered global instructions are composed before this job context. Bodies remain literal.

{(draft.skillIds ?? []).map((id, index) => { const skill = skills.data?.items.find(item => item.id === id); return
{index + 1}. {skill?.key ?? "Unavailable skill"}
; })}
Create or edit skills

Prompt and context

Write instructions using context supplied by your triggers.

update("promptTemplate", value)} triggers={draft.triggers} /> update("runNameTemplate", value)} triggers={draft.triggers} /> Template variables{metadata.error &&

{metadata.error.message}

}{Object.entries(metadata.data ?? {}).map(([kind, fields]) =>

{kind}

    {fields.map(field =>
  • {field.path} — {field.description}
  • )}
)}
-

Triggers

Choose the events that start this job.

update("triggers", value)} onValidityChange={setInvalidForm} /> +
{initial && }

Triggers

Choose the events that start this job.

update("triggers", value)} onValidityChange={setInvalidForm} /> {initial?.triggers.map(trigger => trigger.kind === "webhook" && trigger.config.provider === "cloudflareTail" && trigger.config.destination ?

{trigger.slug} · Tail webhook destination

{trigger.config.destination}
: null)}
{save.error &&

{save.error.message}

} {!initial && } diff --git a/packages/app/src/features/jobs/invocation-permission-editor.tsx b/packages/app/src/features/jobs/invocation-permission-editor.tsx new file mode 100644 index 00000000..287c0cf0 --- /dev/null +++ b/packages/app/src/features/jobs/invocation-permission-editor.tsx @@ -0,0 +1,31 @@ +import { useEffect, useState } from "react"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Button, Input, Label } from "../../shared/ui"; +import { selectorQuery } from "./editor-queries"; +import { messageOf } from "../auth/session"; + +export function InvocationPermissionEditor({ jobId }: { jobId: string }) { + const [search, setSearch] = useState(""), [selected, setSelected] = useState([]); + const configured = useQuery({ queryKey: ["job-invocation-permissions", jobId], queryFn: async ({ signal }) => { + const { data, error } = await api.GET("/api/v1/jobs/{jobId}/invocation-permissions", { params: { path: { jobId } }, signal }); + if (!data || error) throw new Error(messageOf(error)); return data; + } }); + useEffect(() => { if (configured.data) setSelected(configured.data.destinationJobIds); }, [configured.data]); + const jobs = useQuery(selectorQuery(search)); + const save = useMutation({ retry: false, mutationFn: async () => { + const { data, error } = await api.PUT("/api/v1/jobs/{jobId}/invocation-permissions", { params: { path: { jobId } }, body: { destinationJobIds: selected } }); + if (!data || error) throw new Error(messageOf(error)); return data; + }, onSuccess: value => { setSelected(value.destinationJobIds); void configured.refetch(); } }); + return
+

Manual invocation permissions

+

Choose jobs this job may manually invoke during a run. Lifecycle triggers are managed separately.

+ + {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}

} + {save.isSuccess &&

Manual invocation permissions saved.

} +
; +} diff --git a/packages/app/test/editor.browser.test.mjs b/packages/app/test/editor.browser.test.mjs index f71eb8ee..8769bcdf 100644 --- a/packages/app/test/editor.browser.test.mjs +++ b/packages/app/test/editor.browser.test.mjs @@ -60,12 +60,31 @@ test("All runs complete source jobs stay within the edited job project during se assert.equal(await page.getByLabel("Alpha other", { exact: true }).count(), 0); await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor(); assert.ok(selectorRequests.length > 0); - assert.ok(selectorRequests.every(url => url.searchParams.get("projectId") === projectA)); + assert.ok(selectorRequests.filter(url => url.searchParams.has("projectId")).every(url => url.searchParams.get("projectId") === projectA)); + assert.ok(selectorRequests.some(url => !url.searchParams.has("projectId")), "manual permission selector lists tenant jobs across projects"); assert.ok(selectorRequests.some(url => url.searchParams.get("q") === "Alpha")); assert.deepEqual(saved.triggers[0].config.sourceJobIds, [sameProjectJob]); 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 () => { + const { context, page } = await setup(); + const projectA = "00000000-0000-4000-8000-000000000020", destination = "00000000-0000-4000-8000-000000000024"; + let saved, selectorUrl; + await page.route(`**/api/v1/jobs/${id}`, route => route.fulfill({ json: { ...initial, projectId: projectA } })); + await page.route(`**/api/v1/jobs/${id}/invocation-permissions`, route => { + if (route.request().method() === "GET") return route.fulfill({ json: { sourceJobId: id, destinationJobIds: [] } }); + saved = route.request().postDataJSON(); return route.fulfill({ json: { sourceJobId: id, ...saved } }); + }); + 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("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.equal(selectorUrl.searchParams.has("projectId"), false); + await context.close(); +}); test("create uses bounded lifecycle selector, lazy provider reads, schedule preview and typed form submission on mobile", async () => { const { context, page } = await setup({ viewport: { width: 390, height: 844 } }); let body, providerReads = 0; const selectors = []; const projectId = "00000000-0000-4000-8000-000000000010"; diff --git a/packages/docs/docs.json b/packages/docs/docs.json index c8eae4f3..447f012b 100644 --- a/packages/docs/docs.json +++ b/packages/docs/docs.json @@ -39,6 +39,7 @@ "integrations/github", "integrations/clickup", "recipes/chaining", + "work/manual-invocation-permissions", "integrations/oauth", "integrations/triggers" ] diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index d47bec1e..45b44886 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -270,6 +270,26 @@ Expected result: a successful source run produces a destination run. Invoke the Available states are `succeeded`, `failed`, `stopped`, and `edited`. **Edited** fires on successful saves (including enable/disable), even unchanged saves, not creation or run-state changes. Edited context has `source_job_id`, `event: "edited"`, and `edited_at`; it has no source run ID. Only same-tenant enabled subscribers match, and a job cannot subscribe to its own edits. Pending edit events wait while disabled/unmatched; deleting the source or removing the trigger discards them. Verify an edited recipe by saving the source and inspecting the destination context. +## 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 an owner-session-only `PUT` containing `{"destinationJobIds":["..."]}`. Destinations must exist in the same tenant. 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. + +While an agent or code job is executing on an exe.dev VM, Factorize provides `FACTORIZE_API_URL` and `FACTORIZE_RUN_TOKEN` to its process environment. The token is bound to the actual source job and run, expires after 24 hours, and stops authorizing requests when that run is no longer active. Do not pass a source job or run ID: the service derives both from the credential. + +Use the normal manual invocation endpoint, which is also the `invoke_job` MCP tool: + +```sh +curl --fail-with-body -X POST "$FACTORIZE_API_URL/jobs/DESTINATION_JOB_ID/invocations" \ + -H "Authorization: Bearer $FACTORIZE_RUN_TOKEN" \ + -H 'Content-Type: application/json' \ + --data '{"prompt":"Run the authorized follow-up","data":{"key":"value"},"idempotencyKey":"source-run-step-1"}' +``` + +Only explicitly configured destinations may be invoked with a run token. Factorize checks the permission, active source run, destination enabled state, enabled manual trigger, and queue capacity at invocation time. Reuse the same `idempotencyKey` when retrying an uncertain request. Destination run details expose `invocation.source_job_id` and `invocation.source_run_id`; human and external invocations leave these values null. + ## Connect your accounts Source: https://docs.factorize.sh/integrations/oauth @@ -434,6 +454,8 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `get_run_diagnostics` | runs:read | Required string `runId` | | `report_run_error` | runs:write | Required `runId` and `reason`; records an error without stopping execution | | `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `get_job_invocation_permissions` | jobs:read | Required string `jobId` | +| `set_job_invocation_permissions` | jobs:write (owner session) | Required `jobId` and `destinationJobIds` UUID array | | `stop_run` | runs:cancel | Required string `runId` | | `kill_run` | runs:cancel | Required string `runId`; currently the same stop operation | | `list_job_webhook_activity` | runs:read | Required `jobId`; optional integer `limit` (1–100, default 50) | diff --git a/packages/docs/llms.txt b/packages/docs/llms.txt index 4a9a6068..b4c511b2 100644 --- a/packages/docs/llms.txt +++ b/packages/docs/llms.txt @@ -29,6 +29,7 @@ Current MCP does not return execution output; inspect browser traces or REST tra - [Automate from GitHub](https://docs.factorize.sh/integrations/github): Select an installation, repository, and event. - [Automate from ClickUp](https://docs.factorize.sh/integrations/clickup): Connect a workspace and select matching tasks. - [Chain jobs](https://docs.factorize.sh/recipes/chaining): Start a follow-up after another job finishes or is edited. +- [Manual job invocation permissions](https://docs.factorize.sh/work/manual-invocation-permissions): Authorize jobs to start other jobs with run-scoped credentials. - [Connect your accounts](https://docs.factorize.sh/integrations/oauth): Browser setup, resource access, and delivery verification. - [Trigger configuration](https://docs.factorize.sh/integrations/triggers): Configure schedules, provider webhooks, and lifecycle triggers. diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 190c98ff..5ae4b6fd 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -34,6 +34,8 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `get_run_diagnostics` | runs:read | Required string `runId` | | `report_run_error` | runs:write | Required `runId` and `reason`; records an error without stopping execution | | `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `get_job_invocation_permissions` | jobs:read | Required string `jobId` | +| `set_job_invocation_permissions` | jobs:write (owner session) | Required `jobId` and `destinationJobIds` UUID array | | `stop_run` | runs:cancel | Required string `runId` | | `kill_run` | runs:cancel | Required string `runId`; currently the same stop operation | | `list_job_webhook_activity` | runs:read | Required `jobId`; optional integer `limit` (1–100, default 50) | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 59500292..f82ccc46 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -8245,6 +8245,146 @@ paths: application/json: schema: $ref: "#/components/schemas/ManualInvocation" + /api/v1/jobs/{jobId}/invocation-permissions: + get: + summary: List a source job's manual invocation destinations + responses: + "200": + description: Configured tenant-local destination jobs + content: + application/json: + schema: + type: object + properties: + sourceJobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + destinationJobIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + required: + - sourceJobId + - destinationJobIds + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the jobs:read scope. + + Accepts a scoped bearer token or interactive owner session. + operationId: get_api_v1_jobs_jobId_invocation_permissions + tags: + - jobs + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: jobs:read + x-owner-session-required: false + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + put: + 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. + + Requires the jobs:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Saved manual invocation permissions + content: + application/json: + schema: + type: object + properties: + sourceJobId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + destinationJobIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + required: + - sourceJobId + - destinationJobIds + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: put_api_v1_jobs_jobId_invocation_permissions + tags: + - jobs + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: jobs:write + x-owner-session-required: true + parameters: + - name: jobId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + destinationJobIds: + maxItems: 1000 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + required: + - destinationJobIds + additionalProperties: false /api/v1/jobs/{jobId}/events: get: summary: List webhook activity diff --git a/packages/docs/work/manual-invocation-permissions.mdx b/packages/docs/work/manual-invocation-permissions.mdx new file mode 100644 index 00000000..3abdeaa4 --- /dev/null +++ b/packages/docs/work/manual-invocation-permissions.mdx @@ -0,0 +1,21 @@ +--- +title: Manual job invocation permissions +description: Authorize jobs to start other jobs with run-scoped credentials. +--- + +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 an owner-session-only `PUT` containing `{"destinationJobIds":["..."]}`. Destinations must exist in the same tenant. 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. + +While an agent or code job is executing on an exe.dev VM, Factorize provides `FACTORIZE_API_URL` and `FACTORIZE_RUN_TOKEN` to its process environment. The token is bound to the actual source job and run, expires after 24 hours, and stops authorizing requests when that run is no longer active. Do not pass a source job or run ID: the service derives both from the credential. + +Use the normal manual invocation endpoint, which is also the `invoke_job` MCP tool: + +```sh +curl --fail-with-body -X POST "$FACTORIZE_API_URL/jobs/DESTINATION_JOB_ID/invocations" \ + -H "Authorization: Bearer $FACTORIZE_RUN_TOKEN" \ + -H 'Content-Type: application/json' \ + --data '{"prompt":"Run the authorized follow-up","data":{"key":"value"},"idempotencyKey":"source-run-step-1"}' +``` + +Only explicitly configured destinations may be invoked with a run token. Factorize checks the permission, active source run, destination enabled state, enabled manual trigger, and queue capacity at invocation time. Reuse the same `idempotencyKey` when retrying an uncertain request. Destination run details expose `invocation.source_job_id` and `invocation.source_run_id`; human and external invocations leave these values null. From f63ca41cbea410793a2dea3cc36ba555a3f64439 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 5 Nov 2026 20:42:22 +0000 Subject: [PATCH 2/3] docs: update invocation provenance contracts --- packages/api-client/src/schema.d.ts | 2 ++ packages/docs/openapi.yaml | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index e7cda244..78ec3414 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -2060,6 +2060,8 @@ export interface components { occurrence: { [key: string]: unknown; } | null; + source_job_id: string | null; + source_run_id: string | null; created_at: string; }; invocation_source: string; diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index f82ccc46..9bc95dcb 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -964,6 +964,14 @@ components: type: string additionalProperties: {} - type: "null" + source_job_id: + type: + - string + - "null" + source_run_id: + type: + - string + - "null" created_at: type: string required: @@ -973,6 +981,8 @@ components: - trigger_id - context - occurrence + - source_job_id + - source_run_id - created_at additionalProperties: false invocation_source: From 535468859be2fb5a6c1da352c8894cb20d31ee87 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 5 Nov 2026 20:47:34 +0000 Subject: [PATCH 3/3] test: preserve structured result run fixture --- packages/api/test/api-boundary.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index 6908c1ee..b2c34e07 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -176,7 +176,7 @@ describe("Worker OpenAPI request/response boundaries", () => { }); it("documents the job name in run detail for clients with only runs:read", async () => { - vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, source_job_id: null, source_run_id: null, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); + vi.spyOn(ApiService.prototype, "getRun").mockResolvedValue({ id: "run-1", tenant_id: "tenant", execution_handle: null, job_id: "job-1", issue_id: "", issue_url: null, issue_title: "", run_name: "", agent_name: "", workspace_name: "", agent_kind: "codex", state: "queued", failure_source: null, agent_error: null, provider: "manual", backend_kind: "exe-vm", capabilities: [], destination_url: null, artifact_state: "pending", artifact_error: null, created_at: "2026-10-09T12:00:00.000Z", updated_at: "2026-10-09T12:00:00.000Z", started_at: null, job_name: "Job name", invocation_id: "invocation", execution_backend_kind: "exe-vm", execution_capabilities: [], claim_released: false, vm_cleanup_attempt: 0, cleanup_next_at: null, vm_cleanup_complete: false, occurrence: {}, invocation_source: "manual", invocation_claim_key: "manual:key", invocation_trigger_id: null, invocation_created_at: "2026-10-09T12:00:00.000Z", trace_sources: null, trace_projection: null, trace_generation: null, execution_diagnostics: null, harness_log: null, job_result: null, run_artifacts: [], prompt: "Prompt", context: {}, invocation: { id: "invocation", source: "manual", claim_key: "manual:key", trigger_id: null, context: {}, occurrence: {}, source_job_id: null, source_run_id: null, created_at: "2026-10-09T12:00:00.000Z" }, activity: [] }); const result = await assertResponse(await request("GET", "/api/v1/runs/run-1", undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", "/api/v1/runs/{runId}", 200); expect(result.job_name).toBe("Job name"); });