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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1566,7 +1566,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. 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.
* @description Requires an owner session, scoped API key, or authorized OAuth client with jobs:write. Destinations must belong to the source job's project; self-invocation is allowed. A run token may invoke a configured destination only while both jobs remain in the same project. Lifecycle subscriptions do not create permissions.
*
* Requires the jobs:write scope.
*
Expand Down Expand Up @@ -6656,7 +6656,7 @@ export interface operations {
};
requestBody?: never;
responses: {
/** @description Configured tenant-local destination jobs */
/** @description Configured destination jobs in the same project */
200: {
headers: {
[name: string]: unknown;
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -829,8 +829,8 @@ export const API_ROUTES: RouteContract[] = [
description: "Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments.",
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. 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}/invocation-permissions", "jobs:read", { summary: "List a source job's manual invocation destinations", responses: { "200": { description: "Configured destination jobs in the same project", 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 belong to the source job's project; self-invocation is allowed. A run token may invoke a configured destination only while both jobs remain in the same project. Lifecycle subscriptions do not create permissions.", responses: { "200": { description: "Saved manual invocation permissions", content: { "application/json": { schema: jsonSchema(invocationPermissionsResponse, "output") } } } } }, (service, { params, body }) => service.setInvocationPermissions(params.jobId, body.destinationJobIds), { body: invocationPermissionsInput }),
route(
"GET",
"/api/v1/jobs/{jobId}/events",
Expand Down
13 changes: 9 additions & 4 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,8 @@ export class ApiService {
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.jobs source ON source.tenant_id=r.tenant_id AND source.id=r.job_id
JOIN app.jobs destination ON destination.tenant_id=source.tenant_id AND destination.id=$3 AND destination.project_id=source.project_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.");
Expand All @@ -473,7 +475,10 @@ export class ApiService {
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]);
const rows = await databaseFor(this.env).pool.query<{ destination_job_id: string }>(`SELECT p.destination_job_id FROM app.manual_invocation_permissions p
JOIN app.jobs source ON source.tenant_id=p.tenant_id AND source.id=p.source_job_id
JOIN app.jobs destination ON destination.tenant_id=p.tenant_id AND destination.id=p.destination_job_id AND destination.project_id=source.project_id
WHERE p.tenant_id=$1 AND p.source_job_id=$2 ORDER BY p.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[]) {
Expand All @@ -485,11 +490,11 @@ export class ApiService {
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]);
const sources = await client.query<{ project_id: string }>("SELECT project_id 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.");
const found = await client.query("SELECT id FROM app.jobs WHERE tenant_id=$1 AND project_id=$3 AND id=ANY($2::uuid[])", [this.auth.tenantId, unique, sources.rows[0].project_id]);
if (found.rowCount !== unique.length) throw new ServiceError(400, "invalid_request", "Every destination must be an existing job in the source job's project.");
}
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]);
Expand Down
20 changes: 16 additions & 4 deletions packages/api/test/manual-invocation-permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,22 @@ const tenantId = "00000000-0000-4000-8000-000000000001";
const sourceId = "00000000-0000-4000-8000-000000000002";
const destinationId = "00000000-0000-4000-8000-000000000003";
const foreignId = "00000000-0000-4000-8000-000000000004";
const crossProjectId = "00000000-0000-4000-8000-000000000005";
const projectA = "00000000-0000-4000-8000-000000000020";

function fixture(options: { member?: boolean; activeToken?: boolean } = {}) {
const persisted: string[] = [];
const query = async (sql: string, values: unknown[] = []) => {
if (sql.includes("SELECT m.user_id,m.email")) return { rows: options.member === false ? [] : [{ user_id: "owner", email: "owner@example.com", role: "owner", session_version: 1 }], rowCount: options.member === false ? 0 : 1 };
if (sql.includes("SELECT 1 FROM app.access_tokens")) return { rows: options.activeToken === false ? [] : [{ ok: 1 }], rowCount: options.activeToken === false ? 0 : 1 };
if (sql.includes("SELECT 1 FROM app.jobs")) return { rows: values[1] === sourceId ? [{ ok: 1 }] : [], rowCount: values[1] === sourceId ? 1 : 0 };
if (sql.includes("SELECT project_id FROM app.jobs")) return { rows: values[1] === sourceId ? [{ project_id: projectA }] : [], rowCount: values[1] === sourceId ? 1 : 0 };
if (sql.includes("SELECT id FROM app.jobs")) {
const ids = (values[1] as string[]).filter(id => id === destinationId || id === sourceId);
const ids = values[2] === projectA ? (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 }; }
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 };
if (sql.includes("SELECT p.destination_job_id")) { const ids = persisted.filter(id => id === destinationId || id === sourceId); return { rows: ids.map(destination_job_id => ({ destination_job_id })), rowCount: ids.length }; }
throw new Error(`Unexpected SQL: ${sql}`);
};
const database = { pool: { query }, transaction: async (work: (client: any) => Promise<unknown>) => work({ query }) } as any;
Expand Down Expand Up @@ -64,14 +66,24 @@ describe("manual invocation permission management", () => {
}
});

it.each(["session", "access_token", "oauth"] as const)("authorizes %s at the service and preserves tenant-local destination checks", async method => {
it.each(["session", "access_token", "oauth"] as const)("authorizes %s at the service and enforces same-project 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" });
await expect(service.setInvocationPermissions(sourceId, [crossProjectId])).rejects.toMatchObject({ status: 400, code: "invalid_request" });
});

it("returns only same-project destinations and rejects cross-project grants", async () => {
const f = fixture();
f.persisted.push(destinationId, crossProjectId);
const service = new ApiService(f.env, auth("session", ["jobs:read", "jobs:write"]));
(service as any).jobs = () => ({ getJob: async () => ({ id: sourceId, projectId: projectA }) });
await expect(service.getInvocationPermissions(sourceId)).resolves.toEqual({ sourceJobId: sourceId, destinationJobIds: [destinationId] });
await expect(service.setInvocationPermissions(sourceId, [crossProjectId])).rejects.toMatchObject({ status: 400, code: "invalid_request" });
});

it("rejects missing scopes, missing credentials, invalid or revoked owner credentials, and run tokens", async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/features/jobs/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ function EditorForm({ initial, section }: { initial?: Job; section?: string }) {
</div></Card></section>}{show("context") && <section id="context" aria-labelledby="context-heading" className="grid gap-4">{(draft.executionType ?? "agent") === "agent" ? <><h2 id="context-heading" className="sr-only">Context</h2><Card className="space-y-4"><h3>Skills</h3><p className="text-sm text-slate-600 dark:text-slate-400">Ordered global instructions are composed before this job context. Bodies remain literal.</p><div className="grid gap-2">{(draft.skillIds ?? []).map((id, index) => { const skill = skills.data?.items.find(item => item.id === id); return <div key={id} className="flex flex-wrap items-center gap-2 rounded-lg border border-stone-200 p-3 dark:border-slate-700"><span className="font-semibold">{index + 1}. {skill?.key ?? "Unavailable skill"}</span><Button type="button" onClick={() => update("skillIds", (draft.skillIds ?? []).filter(value => value !== id))}>Remove</Button><Button type="button" disabled={index === 0} onClick={() => { const next = [...(draft.skillIds ?? [])]; [next[index - 1], next[index]] = [next[index], next[index - 1]]; update("skillIds", next); }}>Up</Button><Button type="button" disabled={index === (draft.skillIds ?? []).length - 1} onClick={() => { const next = [...(draft.skillIds ?? [])]; [next[index], next[index + 1]] = [next[index + 1], next[index]]; update("skillIds", next); }}>Down</Button></div>; })}</div><div className="flex flex-wrap gap-2"><Select aria-label="Add skill" value="" onChange={e => { if (e.target.value) update("skillIds", [...(draft.skillIds ?? []), e.target.value]); }}><option value="">Add skill…</option>{skills.data?.items.filter(skill => !(draft.skillIds ?? []).includes(skill.id)).map(skill => <option key={skill.id} value={skill.id}>{skill.key}</option>)}</Select><Link to="/skills" className="self-center text-sm font-semibold underline">Create or edit skills</Link></div></Card><Card className="space-y-5"><h2>Prompt and context</h2><p className="text-sm text-slate-600 dark:text-slate-400">Write instructions using context supplied by your triggers.</p><TemplateField label="Prompt template" multiline value={draft.promptTemplate} onChange={value => update("promptTemplate", value)} triggers={draft.triggers} />
<TemplateField label="Run name template" value={draft.runNameTemplate ?? ""} onChange={value => update("runNameTemplate", value)} triggers={draft.triggers} />
<Disclosure><Summary>Template variables</Summary>{metadata.error && <p role="alert">{metadata.error.message}</p>}{Object.entries(metadata.data ?? {}).map(([kind, fields]) => <Card key={kind}><h3>{kind}</h3><ul>{fields.map(field => <li key={field.path}><code>{field.path}</code> — {field.description}</li>)}</ul></Card>)}</Disclosure>
</Card></> : <Card><h2 id="context-heading">Context</h2><p>Context settings are available for agent jobs.</p></Card>}</section>}{show("permissions") && <section id="permissions" aria-label="Permissions" className="grid gap-4"><RunPermissions value={draft.runScopes ?? defaultRunScopes} onChange={value => update("runScopes", value)} />{initial && <Card><InvocationPermissionEditor jobId={initial.id} /></Card>}</section>}{show("triggers") && <section id="triggers" aria-labelledby="triggers-heading"><Card><h2 id="triggers-heading">Triggers</h2><p className="mb-5 text-sm text-slate-600 dark:text-slate-400">Choose the events that start this job.</p><TriggerEditor triggers={draft.triggers} projectId={selectedProjectId} onChange={value => update("triggers", value)} onValidityChange={setInvalidForm} />
</Card></> : <Card><h2 id="context-heading">Context</h2><p>Context settings are available for agent jobs.</p></Card>}</section>}{show("permissions") && <section id="permissions" aria-label="Permissions" className="grid gap-4"><RunPermissions value={draft.runScopes ?? defaultRunScopes} onChange={value => update("runScopes", value)} />{initial && <Card><InvocationPermissionEditor jobId={initial.id} projectId={initial.projectId ?? selectedProjectId ?? ""} /></Card>}</section>}{show("triggers") && <section id="triggers" aria-labelledby="triggers-heading"><Card><h2 id="triggers-heading">Triggers</h2><p className="mb-5 text-sm text-slate-600 dark:text-slate-400">Choose the events that start this job.</p><TriggerEditor triggers={draft.triggers} projectId={selectedProjectId} onChange={value => update("triggers", value)} onValidityChange={setInvalidForm} />
{initial?.triggers.map(trigger => trigger.kind === "webhook" && trigger.config.provider === "cloudflareTail" && trigger.config.destination ? <div key={trigger.id} className="mt-4 text-sm"><p>{trigger.slug} · Tail webhook destination</p><code className="break-all">{trigger.config.destination}</code></div> : null)}
</Card></section>}{save.error && <p role="alert">{save.error.message}</p>}
{!initial && <Button variant="primary" disabled={save.isPending || !!remote || reconciling || !!conflicts.length || targets.isPending || !!targets.error}>{save.isPending ? "Saving…" : "Create job"}</Button>}
Expand Down
Loading
Loading