From cdadeae50bbb4a9932f339b982c3ebc12abd0e4c Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Thu, 19 Nov 2026 19:18:17 +0000 Subject: [PATCH] Use HTTP for agent proxy access and delegate integration grants to exe.dev VMs --- packages/api-client/src/schema.d.ts | 146 ++++++++++- .../migrations/0060_external_vm_grants.sql | 14 ++ packages/api/src/access-tokens.ts | 3 +- packages/api/src/agent-api-contracts.ts | 11 +- packages/api/src/agent-api.ts | 28 ++- packages/api/src/api-contract.ts | 12 +- packages/api/src/consent-api.ts | 6 +- packages/api/src/exe-vm-backend.ts | 24 +- packages/api/src/flow-service.ts | 3 + packages/api/src/postgres/run-scheduler.ts | 2 + packages/api/src/postgres/schema.ts | 17 +- packages/api/src/protected-api.ts | 31 +-- packages/api/src/run-outbound-forwarder.ts | 2 +- packages/api/src/types.ts | 3 +- packages/api/src/vendor-run-identity.ts | 13 +- packages/api/src/vm-grants.ts | 226 ++++++++++++++++++ packages/api/src/worker.ts | 28 ++- .../test/fixtures/agent-api-runtime-worker.ts | 3 +- packages/docs/integrations/oauth.mdx | 24 +- packages/docs/llms-full.txt | 30 ++- packages/docs/mcp/tools.mdx | 6 +- packages/docs/openapi.yaml | 216 ++++++++++++++++- scripts/agent-api-runtime.test.mjs | 118 ++++++++- scripts/agent-login.mjs | 83 +++++++ 24 files changed, 961 insertions(+), 88 deletions(-) create mode 100644 packages/api/migrations/0060_external_vm_grants.sql create mode 100644 packages/api/src/vm-grants.ts create mode 100644 scripts/agent-login.mjs diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index bb1d1697..c25bc7e0 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1806,6 +1806,54 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/agent/vm-grants": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Delegate selected proxy integrations to an exe.dev VM + * @description Requires an OAuth agent with proxy:use, vm:grant and access to the provider and each selected integration. Expires with the issuing access token. + * + * Requires the vm:grant and proxy:use scopes. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_agent_vm_grants"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/agent/vm-grants/{grantId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Revoke an external VM grant + * @description Only the issuing OAuth grant can revoke. Access stops before provider cleanup. + * + * Requires the vm:grant scope. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + delete: operations["delete_api_v1_agent_vm_grants_grantId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/agent/reflection": { parameters: { query?: never; @@ -1839,7 +1887,7 @@ export interface paths { put?: never; /** * Make an authorized credential-injected API request - * @description Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. + * @description OAuth requires proxy:use. An external VM sends its short-lived exe.dev WIF bearer token, X-Factorize-VM-Grant and X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ @@ -1861,7 +1909,7 @@ export interface paths { put?: never; /** * Read up to 64 KiB of an identity-bound retained response - * @description Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe. + * @description Accepts the same OAuth, run or external VM authentication as the request endpoint. Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe. * * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. */ @@ -7647,6 +7695,91 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + post_api_v1_agent_vm_grants: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + providerIntegrationId: string; + vm: string; + integrationIds: string[]; + idempotencyKey: string; + }; + }; + }; + responses: { + /** @description Verified VM grant */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + grantId: string; + vm: string; + integrationIds: string[]; + expiresAt: string; + /** Format: uri */ + tokenUrl: string; + proofFile: string; + /** Format: uri */ + requestUrl: string; + instructions: 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"]; + }; + }; + delete_api_v1_agent_vm_grants_grantId: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Revoked grant */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + grantId: string; + revoked: boolean; + }; + }; + }; + 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"]; + }; + }; get_api_v1_agent_reflection: { parameters: { query?: never; @@ -7670,6 +7803,13 @@ export interface operations { kind: "oauth" | "run"; }; scopes: string[]; + proxy: { + /** Format: uri */ + requestUrl: string; + /** Format: uri */ + readResponseUrl: string; + authentication: string; + }; integrations: { /** Format: uuid */ id: string; @@ -7686,6 +7826,8 @@ export interface operations { /** @enum {string} */ access: "granted" | "requestable" | "unavailable"; instructions: string; + /** @constant */ + vmGrantProvider?: "exe.dev"; }[]; }; }; diff --git a/packages/api/migrations/0060_external_vm_grants.sql b/packages/api/migrations/0060_external_vm_grants.sql new file mode 100644 index 00000000..27d6599b --- /dev/null +++ b/packages/api/migrations/0060_external_vm_grants.sql @@ -0,0 +1,14 @@ +ALTER TABLE app.agent_identities DROP CONSTRAINT agent_identities_kind_check; +ALTER TABLE app.agent_identities ADD CHECK(kind IN ('oauth','run','vm')); +CREATE TABLE app.vm_grants ( + tenant_id uuid NOT NULL, id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + parent_id uuid NOT NULL, provider_id uuid NOT NULL, provider_epoch integer NOT NULL, + vm text NOT NULL, permissions jsonb NOT NULL, parent_scopes jsonb NOT NULL, + request_key text NOT NULL, issuer text, subject text, proof_hash text, + expires_at timestamptz NOT NULL, revoked_at timestamptz, cleaned_at timestamptz, cleanup_after timestamptz NOT NULL DEFAULT now(), + UNIQUE(tenant_id,parent_id,request_key), + FOREIGN KEY(tenant_id,parent_id) REFERENCES app.agent_identities(tenant_id,id) ON DELETE CASCADE, + FOREIGN KEY(tenant_id,provider_id) REFERENCES app.agent_integrations(tenant_id,id) +); +CREATE INDEX vm_grant_cleanup ON app.vm_grants(expires_at) WHERE cleaned_at IS NULL; +INSERT INTO app.schema_migrations(version) VALUES ('0060_external_vm_grants'); diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index 39c8cb27..54459b1e 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -4,6 +4,7 @@ import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const; +export const AGENT_SCOPES: readonly string[] = [...ACCESS_SCOPES, "proxy:use", "vm:grant"]; export type AccessScope = typeof ACCESS_SCOPES[number]; export type LegacyScope = "flows:read" | "flows:write"; @@ -14,7 +15,7 @@ export function normalizeScopes(scopes: readonly string[]): string[] { if (scope === "flows:read") ["projects:read", "jobs:read", "integrations:read"].forEach(value => result.add(value)); else if (scope === "flows:write") ["projects:write", "jobs:write", "integrations:write"].forEach(value => result.add(value)); else if (scope === "runs:write") ["runs:read", "runs:invoke", "runs:cancel", "runs:write"].forEach(value => result.add(value)); - else if (ACCESS_SCOPES.includes(scope as AccessScope) || isIntegrationScope(scope)) result.add(scope); + else if (AGENT_SCOPES.includes(scope) || isIntegrationScope(scope)) result.add(scope); } return [...result]; } diff --git a/packages/api/src/agent-api-contracts.ts b/packages/api/src/agent-api-contracts.ts index 0be22e46..9c8a4e41 100644 --- a/packages/api/src/agent-api-contracts.ts +++ b/packages/api/src/agent-api-contracts.ts @@ -5,7 +5,7 @@ export const integrationRef = z.uuid(); export const apiPolicyInput = z.object({ policy: z.enum(["baseline", "requestable", "disabled"]), expectedRevision: z.number().int().positive() }).strict(); export const apiPolicy = z.object({ id: integrationRef, credentialId: z.string(), name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model", "fly", "exe", "amp", "clickup", "x"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() }); export const apiPolicyList = z.object({ integrations: z.array(apiPolicy) }); -export const apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "run"]) }), scopes: z.array(z.string()), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string() })) }); +export const apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "run"]) }), scopes: z.array(z.string()), proxy: z.object({ requestUrl: z.url(), readResponseUrl: z.url(), authentication: z.string() }), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string(), vmGrantProvider: z.literal("exe.dev").optional() })) }); export const requestApiInput = z.object({ integration: integrationRef, method: z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]), @@ -16,3 +16,12 @@ export const requestApiInput = z.object({ export const readApiResponseInput = z.object({ handle: z.uuid(), offset: z.number().int().nonnegative().default(0) }).strict(); export const apiResponseChunk = z.object({ handle: z.uuid(), offset: z.number().int().nonnegative(), nextOffset: z.number().int().nonnegative(), size: z.number().int().nonnegative(), encoding: z.literal("base64"), body: z.string(), done: z.boolean() }); export const requestApiResponse = z.object({ status: z.number().int(), headers: z.record(z.string(), z.string()), size: z.number().int().nonnegative(), encoding: z.enum(["utf8", "base64"]), body: z.string().optional(), handle: z.uuid().optional(), expiresAt: z.string().optional() }); + +export const grantVmInput = z.object({ + providerIntegrationId: integrationRef, + vm: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/), + integrationIds: z.array(integrationRef).min(1).max(64).refine(ids => new Set(ids).size === ids.length), + idempotencyKey: z.string().min(1).max(160), +}).strict(); +export const revokeVmInput = z.object({ grantId: z.uuid() }).strict(); +export const vmGrantReceipt = z.object({ grantId: z.uuid(), vm: z.string(), integrationIds: z.array(integrationRef), expiresAt: z.string(), tokenUrl: z.url(), proofFile: z.string(), requestUrl: z.url(), instructions: z.string() }); diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index bf4a3b70..01bbd559 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -57,7 +57,7 @@ export class AgentApiService { const auth = this.auth; const member = await new IdentityRepository(this.database, auth.tenantId).member(auth.userId); if (member?.role !== "owner" || member.sessionVersion !== auth.sessionVersion) throw invalidIdentity(); - let kind: "run" | "oauth", subject: string, config: Record | null = null; + let kind: "run" | "oauth" | "vm", subject: string, config: Record | null = null; if (auth.authMethod === "vendor_identity" && auth.runId) { kind = "run"; subject = auth.runId; const row = (await this.database.pool.query<{execution_config: Record}>(`SELECT r.execution_config FROM app.runs r @@ -69,6 +69,18 @@ export class AgentApiService { AND r.state IN ('starting','running','blocked') AND j.state IN ('starting','running','blocked')`, [auth.tenantId, auth.runId, auth.runIdentityProvider, auth.userId, auth.sessionVersion])).rows[0]; if (!row) throw invalidIdentity(); config = row.execution_config; + } else if (auth.authMethod === "vm_grant" && auth.vmGrantId) { + kind = "vm"; subject = auth.vmGrantId; + const grant = (await this.database.pool.query(`SELECT g.permissions, g.parent_scopes FROM app.vm_grants g + JOIN app.agent_identities parent ON parent.tenant_id=g.tenant_id AND parent.id=g.parent_id + JOIN app.agent_integrations provider ON provider.tenant_id=g.tenant_id AND provider.id=g.provider_id + WHERE g.tenant_id=$1 AND g.id=$2 AND parent.user_id=$3 AND parent.session_version=$4 + AND parent.revoked_at IS NULL AND g.issuer IS NOT NULL AND g.revoked_at IS NULL AND g.expires_at>now() + AND provider.available AND provider.epoch=g.provider_epoch AND (provider.policy='baseline' OR + (provider.policy='requestable' AND g.parent_scopes @> to_jsonb(ARRAY['integration:' || provider.id::text || ':' || provider.epoch::text])))`, + [auth.tenantId, subject, auth.userId, auth.sessionVersion])).rows[0]; + if (!grant) throw invalidIdentity(); + config = grant; } else if (auth.authMethod === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) { kind = "oauth"; subject = auth.oauthGrantId; } else throw invalidIdentity(); @@ -93,7 +105,11 @@ export class AgentApiService { const identity = await this.identity(); const row = (await this.database.pool.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId, integration])).rows[0]; if (!row) throw forbidden(); - if (identity.kind === "run") { + if (identity.kind === "vm") { + const grant = identity.config!; + if (grant.permissions[row.id] !== row.epoch || !row.available || row.policy === "disabled" + || (row.policy !== "baseline" && !grant.parent_scopes.includes(requiredIntegrationScope(row)))) throw forbidden(); + } else if (identity.kind === "run") { if (!this.selected(row, identity.config!)) throw forbidden(); const revoked = await this.database.pool.query("SELECT 1 FROM app.run_credential_revocations WHERE tenant_id=$1 AND run_id=$2 AND kind=$3 AND credential_id=$4", [this.auth.tenantId, this.auth.runId, row.kind, row.credential_id]); if (revoked.rowCount || !row.available) throw forbidden(); @@ -114,9 +130,13 @@ export class AgentApiService { if (!(error instanceof AgentApiError) || error.status === 401) throw error; access = error.code === "insufficient_scope" ? "requestable" : "unavailable"; } - result.push({...publicIntegration(row), access, instructions: row.kind === "x" ? "Use request_api with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use request_api with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use request_api with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use request_api with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use request_api with a path relative to /api/v2." : row.kind === "fly" ? "Use request_api with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use request_api with an OpenAI-compatible path relative to /v1." : "Use request_api with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."}); + result.push({...publicIntegration(row), access, ...(row.kind === "exe" && identity.kind === "oauth" && access === "granted" ? {vmGrantProvider: "exe.dev" as const} : {}), instructions: row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."}); } - return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), integrations: result}; + return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), proxy: { + requestUrl: this.env.APP_ORIGIN + "/api/v1/agent/requests", + readResponseUrl: this.env.APP_ORIGIN + "/api/v1/agent/responses/read", + authentication: identity.kind === "run" ? "Use your run identity helper." : "POST JSON with integration, method, and path. Use the agent OAuth credential with proxy:use. With the Factorize device launcher, curl -H @\"$FACTORIZE_AGENT_AUTH_FILE\" reads the authorization header.", + }, integrations: result}; } async forward(integration: string, path: string, request: Request) { const grant = await this.authorize(integration); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index b962a44e..bc5af2d1 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,4 +1,4 @@ -import { apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "./agent-api-contracts"; +import { grantVmInput, vmGrantReceipt, apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "./agent-api-contracts"; import { queryOf } from "./query-params"; import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; @@ -899,9 +899,11 @@ export const API_ROUTES: RouteContract[] = [ description: "Requires the vendor-verified identity of an active run. Returns only that run's encrypted-at-rest scheduler snapshot, including the rendered prompt and harness or code context. No application scope is required. Sessions, API keys, OAuth clients, other runs and terminal runs cannot retrieve it. Responses are never cached.", responses: { "200": { description: "Launch payload for the calling run", content: { "application/json": { schema: jsonSchema(launchPayloadResponse, "output") } } } } }, service => service.getRuntimeLaunchPayload(), { vendorIdentityOnly: true }), + route("POST", "/api/v1/agent/vm-grants", "vm:grant+proxy:use", { summary: "Delegate selected proxy integrations to an exe.dev VM", description: "Requires an OAuth agent with proxy:use, vm:grant and access to the provider and each selected integration. Expires with the issuing access token.", responses: { "200": { description: "Verified VM grant", content: { "application/json": { schema: jsonSchema(vmGrantReceipt, "output") } } } } }, (service,{body}) => service.grantVm(body), {body: grantVmInput}), + route("DELETE", "/api/v1/agent/vm-grants/{grantId}", "vm:grant", { summary: "Revoke an external VM grant", description: "Only the issuing OAuth grant can revoke. Access stops before provider cleanup.", responses: { "200": { description: "Revoked grant", content: { "application/json": { schema: jsonSchema(z.object({grantId:z.uuid(),revoked:z.boolean()}), "output") } } } } }, (service,{params}) => service.revokeVmGrant(params.grantId!), {parameters:z.object({grantId:z.uuid()})}), route("GET", "/api/v1/agent/reflection", "", { summary: "Discover agent identity and granted or requestable integration APIs", description: "OAuth authorization or verified active run required. Availability reports connection state, without probing credential health. OAuth integration scopes are integration:{stable UUID}:{revocation epoch}; initial login need not request any integration scopes.", responses: { "200": { description: "Agent reflection", content: { "application/json": { schema: jsonSchema(apiReflection, "output") } } } } }, service => service.getApiReflection(), {scope: []}), - route("POST", "/api/v1/agent/requests", "", { summary: "Make an authorized credential-injected API request", description: "Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects.", responses: { "200": { description: "Upstream response or retained response handle", content: { "application/json": { schema: jsonSchema(requestApiResponse, "output") } } } } }, (service,{body,signal}) => service.requestApi(body,signal), {body: requestApiInput, maxBodyBytes: 45_000_000, scope: []}), - route("POST", "/api/v1/agent/responses/read", "", { summary: "Read up to 64 KiB of an identity-bound retained response", description: "Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe.", responses: { "200": { description: "Response chunk", content: { "application/json": { schema: jsonSchema(apiResponseChunk, "output") } } } } }, (service,{body}) => service.readApiResponse(body), {body: readApiResponseInput, scope: []}), + route("POST", "/api/v1/agent/requests", "", { summary: "Make an authorized credential-injected API request", description: "OAuth requires proxy:use. An external VM sends its short-lived exe.dev WIF bearer token, X-Factorize-VM-Grant and X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects.", responses: { "200": { description: "Upstream response or retained response handle", content: { "application/json": { schema: jsonSchema(requestApiResponse, "output") } } } } }, (service,{body,signal}) => service.requestApi(body,signal), {body: requestApiInput, maxBodyBytes: 45_000_000, scope: []}), + route("POST", "/api/v1/agent/responses/read", "", { summary: "Read up to 64 KiB of an identity-bound retained response", description: "Accepts the same OAuth, run or external VM authentication as the request endpoint. Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe.", responses: { "200": { description: "Response chunk", content: { "application/json": { schema: jsonSchema(apiResponseChunk, "output") } } } } }, (service,{body}) => service.readApiResponse(body), {body: readApiResponseInput, scope: []}), route("GET", "/api/v1/integration-api-policies", "integrations:read", { summary: "List tenant MCP API access policies", responses: { "200": { description: "Policies", content: { "application/json": { schema: jsonSchema(apiPolicyList, "output") } } } } }, service => service.listApiPolicies(), {ownerSession: true}), route("PUT", "/api/v1/integration-api-policies/{integrationId}", "integrations:write", { summary: "Set baseline, requestable or disabled MCP access", description: "Baseline changes apply immediately. Disabling invalidates approvals permanently; re-enabling requires fresh consent. Run selections remain independent.", responses: { "200": { description: "Updated policies", content: { "application/json": { schema: jsonSchema(apiPolicyList, "output") } } } } }, (service,{params,body}) => service.updateApiPolicy(params.integrationId,body), {ownerSession: true, body: apiPolicyInput}), route("GET", "/api/v1/runtime-context", "runs:read", { @@ -1345,7 +1347,7 @@ export function generateOpenApi() { .join("\n\n"), operationId: `${route.method.toLowerCase()}_${route.path.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_|_$/g, "")}`, tags: [route.path.split("/")[3]], - security: route.vendorIdentityOnly ? [{ vendorRunIdentity: [], runIdentityHeader: [] }] : route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }], + security: ["/api/v1/agent/requests","/api/v1/agent/responses/read"].includes(route.path) ? [{bearerAuth:[]}, {vendorRunIdentity:[],runIdentityHeader:[]}, {vmWif:[],vmGrantHeader:[],vmProofHeader:[]}] : route.vendorIdentityOnly ? [{ vendorRunIdentity: [], runIdentityHeader: [] }] : route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }], ...(route.authOperation ? { "x-browser-auth-operation": route.authOperation } : { "x-required-scope": route.scope }), "x-owner-session-required": route.ownerSession, ...(parameters.length ? { parameters } : {}), @@ -1364,7 +1366,7 @@ export function generateOpenApi() { } return { ...document, - components: { ...document.components, securitySchemes: { ...document.components.securitySchemes, cookieAuth: { type: "apiKey", in: "cookie", name: "factorize_session" }, vendorRunIdentity: { type: "http", scheme: "bearer", bearerFormat: "JWT", description: "Fresh vendor-signed exe.dev WIF or Fly Machine OIDC token matching the provisioned active run. Must be combined with X-Factorize-Run-Id; a vendor token alone grants no access." }, runIdentityHeader: { type: "apiKey", in: "header", name: "X-Factorize-Run-Id", description: "Provisioned run UUID. Used only to locate the immutable vendor/VM binding; this header is not a credential. Scopes and tenant come from the server-side run snapshot." } }, schemas, responses: errorResponses }, + components: { ...document.components, securitySchemes: { ...document.components.securitySchemes, vmWif: {type:"http",scheme:"bearer",bearerFormat:"JWT"}, vmGrantHeader:{type:"apiKey",in:"header",name:"X-Factorize-VM-Grant"}, vmProofHeader:{type:"apiKey",in:"header",name:"X-Factorize-VM-Proof"}, cookieAuth: { type: "apiKey", in: "cookie", name: "factorize_session" }, vendorRunIdentity: { type: "http", scheme: "bearer", bearerFormat: "JWT", description: "Fresh vendor-signed exe.dev WIF or Fly Machine OIDC token matching the provisioned active run. Must be combined with X-Factorize-Run-Id; a vendor token alone grants no access." }, runIdentityHeader: { type: "apiKey", in: "header", name: "X-Factorize-Run-Id", description: "Provisioned run UUID. Used only to locate the immutable vendor/VM binding; this header is not a credential. Scopes and tenant come from the server-side run snapshot." } }, schemas, responses: errorResponses }, paths, }; } diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index 09ea9cb0..fa05e21d 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -7,12 +7,12 @@ import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; import { hmac } from "./crypto"; import type { Env, OAuthProps } from "./types"; import type { Session } from "./session"; -import { ACCESS_SCOPES, normalizeScopes } from "./access-tokens"; +import { AGENT_SCOPES, normalizeScopes } from "./access-tokens"; export const consentPreviewInput = z.object({ authorizationQuery: z.string().min(1).max(8192) }).strict(); export const consentDecisionInput = z.object({ request: z.string().min(1).max(16384), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]), scopes: z.array(z.string()) }).strict(); export const consentPreviewResponse = z.object({ clientName: z.string(), scopes: z.array(z.string()), request: z.string(), signature: z.string(), expiresAt: z.string(), integrationLabels: z.array(z.object({ scope: z.string(), name: z.string(), description: z.string().nullable() })).optional() }); export const consentDecisionResponse = z.object({ redirectTo: z.string() }); -const supported = [...ACCESS_SCOPES, "flows:read", "flows:write", "runs:write"]; +const supported = [...AGENT_SCOPES, "flows:read", "flows:write", "runs:write"]; const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))); const decode = (value: string) => JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)))); const binding = (payload: string, session: Session) => `${payload}.${session.tenantId}.${session.userId}.${session.sessionVersion}`; @@ -54,7 +54,7 @@ export async function consentDecision(env: Env, session: Session, input: z.infer const legacyRequest = parsed.scope.some(scope => scope === "flows:read" || scope === "flows:write"); const selected = normalizeScopes(input.scopes); const issuedScopes = legacyRequest ? input.scopes : selected; - if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !ACCESS_SCOPES.includes(scope as typeof ACCESS_SCOPES[number]) && !isIntegrationScope(scope))) return null; + if (input.scopes.some(scope => !allowed.has(scope) && !allowed.has(normalizeScopes([scope])[0] ?? "") ) || selected.some(scope => !AGENT_SCOPES.includes(scope) && !isIntegrationScope(scope))) return null; return databaseFor(env).transaction(async transaction => { const preview = await transaction.query("UPDATE app.oauth_consent_previews SET used_at=now() WHERE id=$1 AND used_at IS NULL AND expires_at>clock_timestamp() RETURNING id", [envelope.nonce]); if (!preview.rows.length) return null; diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index 7bd03544..fe7f4ce0 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -75,8 +75,22 @@ export class ExeVmBackend implements ExecutionBackend { return result.body.trim(); } + /** Pin a guest-generated random value as well as the provider attachment. + * Recreating a VM under the same name does not recreate this file. */ + async enrollGuest(vm: string, grantId: string, integrationName: string) { + const file = `.factorize-vm-grants/${grantId}`; + const command = `set -eu; umask 077; cd "$HOME"; mkdir -p .factorize-vm-grants; if [ ! -f ${file} ]; then openssl rand -hex 32 > ${file}; fi; sha256sum ${file}`; + const result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(command)}`); + const hash = result.body.trim().split(/\s+/)[0]; + if (!result.ok || !hash || !/^[a-f0-9]{64}$/.test(hash)) throw new Error("VM enrollment failed"); + return { proofHash: hash, token: await this.exeWifToken(vm, integrationName) }; + } + private async ensureExeWif(vm: string, runId: string, create = true): Promise { - const name = exeWifIntegrationNameFor(runId), audience = `factorize://runs/${runId}`; + return this.identityIntegration(vm, exeWifIntegrationNameFor(runId), `factorize://runs/${runId}`, create); + } + + async identityIntegration(vm: string, name: string, audience: string, create: boolean): Promise { if (create) { const created = await this.api(`integrations add wif --name=${shellAtom(name)} --audience=${shellAtom(audience)} --consumer=gcp --attach=${shellAtom(`vm:${vm}`)}`); if (!created.ok) throw new Error(`exe.dev WIF integration setup failed (${created.status})`); @@ -102,6 +116,10 @@ export class ExeVmBackend implements ExecutionBackend { private async removeExeWif(vm: string, runId: string, name: string): Promise { if (name !== exeWifIntegrationNameFor(runId)) throw new Error("Refusing to remove an unrelated exe.dev WIF integration"); + return this.removeIdentityIntegration(vm, name, `factorize://runs/${runId}`); + } + + async removeIdentityIntegration(vm: string, name: string, audience: string, expected?: {issuer: string; subject: string}): Promise { const listed = await this.api("integrations list --json"); if (!listed.ok) throw new Error("exe.dev WIF cleanup could not verify integration ownership"); let integrations: any[]; @@ -112,11 +130,13 @@ export class ExeVmBackend implements ExecutionBackend { } catch { throw new Error("exe.dev WIF cleanup inventory is invalid"); } const matches = integrations.filter(item => item?.name === name); if (!matches.length) return; - const audience = `factorize://runs/${runId}`; if (matches.length !== 1 || matches[0]?.type !== "wif" || matches[0]?.config?.audience !== audience || !Array.isArray(matches[0]?.attachments) || matches[0].attachments.length !== 1 || matches[0].attachments[0] !== `vm:${vm}`) { throw new Error("exe.dev WIF ownership or attachment does not match"); } + if (expected && (matches[0].config.subject !== expected.subject || `https://exe.dev/issuer/${matches[0].config.issuer_id}` !== expected.issuer)) { + throw new Error("Refusing to remove a replacement WIF integration"); + } const removed = await this.api(`integrations remove ${shellAtom(name)}`); if (!removed.ok && removed.status !== 404) throw new Error("exe.dev WIF removal failed"); } diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 84f59956..6610cf1b 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,3 +1,4 @@ +import { grantVm, revokeVmGrant } from "./vm-grants"; import { AgentApiService, listAgentPolicies } from "./agent-api"; import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; import { DEFAULT_RUN_SCOPES } from "./run-scopes"; @@ -214,6 +215,8 @@ export class ApiService { private async authorizeOwnerSession(scope: Scope): Promise { await this.authorize(scope); if (this.auth.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); } agentApi() { return new AgentApiService(this.env, this.auth); } + grantVm(input: unknown) { return grantVm(this.env,this.auth,input); } + revokeVmGrant(id: string) { return revokeVmGrant(this.env,this.auth,id); } async getApiReflection() { return this.agentApi().reflection(); } async requestApi(input: unknown, signal?: AbortSignal) { return this.agentApi().request(requestApiInput.parse(input), signal); } async readApiResponse(input: unknown) { return this.agentApi().read(readApiResponseInput.parse(input)); } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 9ad604c1..df570c9c 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -1,3 +1,4 @@ +import { cleanupVmGrants } from "../vm-grants"; import { cleanupAgentResponses } from "../agent-api"; import { validateTraceSources, type TraceSource, type TraceSources } from "../trace-source"; import { AmpBackend, type AmpConnection } from "../amp-backend"; @@ -54,6 +55,7 @@ export class RunScheduler { await this.reconcileProviderCleanup(); await this.runRetentionMaintenance(retention); await cleanupAgentResponses(this.env); + await cleanupVmGrants(this.env); } private async runRetentionMaintenance(retention = new RunRetentionRepository(this.database)): Promise { diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 031725e3..6a4fa537 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -69,8 +69,21 @@ export const agentIntegrations = app.table("agent_integrations", { policy:text("policy").$type<"baseline"|"requestable"|"disabled">().notNull().default("requestable"),epoch:integer("epoch").notNull().default(1),revision:integer("revision").notNull().default(1), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.credentialId)]); export const agentIdentities = app.table("agent_identities", { - tenantId:uuid("tenant_id").notNull().references(()=>tenants.id,{onDelete:"cascade"}),id:uuid("id").notNull().defaultRandom(),kind:text("kind").$type<"oauth"|"run">().notNull(),subject:text("subject").notNull(),userId:uuid("user_id").notNull(),sessionVersion:integer("session_version").notNull(),revokedAt:timestamp("revoked_at",{withTimezone:true}),createdAt:createdAt(), + tenantId:uuid("tenant_id").notNull().references(()=>tenants.id,{onDelete:"cascade"}),id:uuid("id").notNull().defaultRandom(),kind:text("kind").$type<"oauth"|"run"|"vm">().notNull(),subject:text("subject").notNull(),userId:uuid("user_id").notNull(),sessionVersion:integer("session_version").notNull(),revokedAt:timestamp("revoked_at",{withTimezone:true}),createdAt:createdAt(), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.subject)]); +export const vmGrants = app.table("vm_grants", { + tenantId: uuid("tenant_id").notNull(), id: uuid("id").primaryKey().defaultRandom(), + parentId: uuid("parent_id").notNull(), providerId: uuid("provider_id").notNull(), + providerEpoch: integer("provider_epoch").notNull(), vm: text("vm").notNull(), + permissions: jsonb("permissions").notNull(), parentScopes: jsonb("parent_scopes").notNull(), + requestKey: text("request_key").notNull(), issuer: text("issuer"), subject: text("subject"), proofHash: text("proof_hash"), + expiresAt: timestamp("expires_at", {withTimezone:true}).notNull(), + cleanupAfter: timestamp("cleanup_after",{withTimezone:true}).notNull().defaultNow(), + revokedAt: timestamp("revoked_at", {withTimezone:true}), cleanedAt: timestamp("cleaned_at", {withTimezone:true}), +}, t => [unique().on(t.tenantId,t.parentId,t.requestKey), + foreignKey({columns:[t.tenantId,t.parentId],foreignColumns:[agentIdentities.tenantId,agentIdentities.id]}).onDelete("cascade"), + foreignKey({columns:[t.tenantId,t.providerId],foreignColumns:[agentIntegrations.tenantId,agentIntegrations.id]}), + index("vm_grant_cleanup").on(t.expiresAt).where(sql`${t.cleanedAt} IS NULL`)]); export const agentProxyResponses = app.table("agent_proxy_responses", { tenantId:uuid("tenant_id").notNull(),id:uuid("id").notNull(),identityId:uuid("identity_id").notNull(),integrationId:uuid("integration_id").notNull(),integrationEpoch:integer("integration_epoch").notNull(),objectKey:text("object_key").notNull().unique(),size:integer("size"),expiresAt:timestamp("expires_at",{withTimezone:true}).notNull(), },t=>[primaryKey({columns:[t.tenantId,t.id]}),foreignKey({columns:[t.tenantId,t.identityId],foreignColumns:[agentIdentities.tenantId,agentIdentities.id]}),foreignKey({columns:[t.tenantId,t.integrationId],foreignColumns:[agentIntegrations.tenantId,agentIntegrations.id]}),index("agent_proxy_response_expiry").on(t.expiresAt)]); @@ -182,7 +195,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, agentIntegrations, agentIdentities, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, + connections, agentIntegrations, agentIdentities, vmGrants, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, runTraceEvents, runActivity, activeClaims, scheduleState, automaticWakes, lifecycleDeliveries, lifecycleEvents, 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 4fa682f0..043dd4c0 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,12 +1,12 @@ import { Hono } from "hono"; import { AgentApiError } from "./agent-api"; -import { requestApiInput, readApiResponseInput } from "./agent-api-contracts"; +import { grantVmInput, revokeVmInput } from "./agent-api-contracts"; import { ExeIntegrationError } from "./exe-vm-backend"; import { queryOf } from "./query-params"; import { jobUpdateInput } from "./job-contracts"; import { InvocationError } from "./job-domain"; import { WorkerEntrypoint } from "cloudflare:workers"; -import { createMcpHandler, McpServer, type ServerContext } from "@modelcontextprotocol/server"; +import { createMcpHandler, McpServer } from "@modelcontextprotocol/server"; import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; import { ApiService, ServiceError } from "./flow-service"; @@ -64,8 +64,6 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (path === "/mcp") { if (!auth) throw new ServiceError(401, "invalid_token", "Unauthorized"); const mcpService = new ApiService(env, auth); - // Authorization challenges must leave the HTTP boundary before the MCP - // SDK translates tool exceptions to JSON-RPC tool errors. if (request.method === "POST") { let mcpBytes=0; const limited = request.body?.pipeThrough(new TransformStream({ @@ -74,11 +72,6 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP let body: any; try { body = await new Response(limited).json(); } catch(error) { if(error instanceof ServiceError) throw error; throw new ServiceError(400,"invalid_request","Request body must be valid JSON."); } mcpBodies.set(request,body); - if (body?.method === "tools/call" && body.params?.name === "request_api") { - const input = requestApiInput.parse(body.params.arguments); - await mcpService.agentApi().authorize(input.integration); - } - if (body?.method === "tools/call" && body.params?.name === "read_api_response") await mcpService.agentApi().authorizeRead(readApiResponseInput.parse(body.params.arguments)); } return await mcp(request, mcpService, env, ctx); } @@ -120,27 +113,19 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP } catch (error) { return timed(errorResponse(error, env.APP_ORIGIN)); } } -const mcpServices = new WeakMap(); const mcpBodies = new WeakMap(); +const mcpServices = new WeakMap(); + function createMcpServer(service: ApiService): McpServer { const server = new McpServer({ name: "factorize", version: "1.0.0" }); - const tool = (name: string, description: string, schema: any, action: (input: T, context: ServerContext) => Promise) => server.registerTool(name, { description, inputSchema: schema }, async (input: T, context: ServerContext) => { - try { - const progressToken = context.mcpReq._meta?.progressToken; - const notify = async (progress: number) => { - if ((typeof progressToken === "string" || typeof progressToken === "number") && name === "request_api") await context.mcpReq.notify({method:"notifications/progress",params:{progressToken,progress,total:1}}); - }; - await notify(0); - const result = await action(input, context); - await notify(1); - return structured(result); - } + const tool = (name: string, description: string, schema: any, action: (input: T) => Promise) => server.registerTool(name, { description, inputSchema: schema }, async (input: T) => { + try { return structured(await action(input)); } catch (error) { const response = errorResponse(error), detail = await response.json() as any; throw new Error(`${detail.error?.code ?? "operation_failed"}: ${detail.error?.message ?? "Operation failed"}`); } }); tool("get_api_reflection", "Discover this agent identity, effective Factorize scopes, and granted/requestable integration APIs. Availability describes connection state, not verified credential health.", z.object({}), () => service.getApiReflection()); - tool("request_api", "Make an HTTP request to a selected integration. Supply a relative path/query, never an origin or upstream credential. Small bodies return inline; larger bodies return a handle retained for 24 hours. Upstream non-2xx status is preserved.", requestApiInput, (input: any, context) => service.requestApi(input, context.mcpReq.signal)); - tool("read_api_response", "Read up to 64 KiB of a retained API response, base64 encoded. Reads recheck identity and integration authorization.", readApiResponseInput, (input: any) => service.readApiResponse(input)); + tool("grant_vm", "Delegate selected proxy integrations to a VM on a supported provider connection.", grantVmInput, (input) => service.grantVm(input)); + tool("revoke_vm_grant", "Revoke proxy access for an externally managed VM.", revokeVmInput, ({grantId}: any) => service.revokeVmGrant(grantId)); tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections()); tool("get_runtime_context", "Inspect the verified invocation identity without exposing credentials.", z.object({}), () => service.getRuntimeContext()); tool("list_github_installations", "List connected GitHub App installations, including the installation IDs needed by GitHub Job triggers. Credentials are never returned.", z.object({}), () => service.listGitHubInstallations()); diff --git a/packages/api/src/run-outbound-forwarder.ts b/packages/api/src/run-outbound-forwarder.ts index 21afc165..75353f42 100644 --- a/packages/api/src/run-outbound-forwarder.ts +++ b/packages/api/src/run-outbound-forwarder.ts @@ -7,7 +7,7 @@ export type OutboundCredential = { headers?: Record; }; const hop = new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"]); -const privateHeaders = new Set(["host", "authorization", "cookie", "content-length", "expect", "forwarded", "x-factorize-run-id"]); +const privateHeaders = new Set(["host", "authorization", "cookie", "content-length", "expect", "forwarded", "x-factorize-run-id", "x-factorize-vm-grant", "x-factorize-vm-proof"]); function filteredHeaders(input: Headers, request: boolean): Headers { const result = new Headers(); diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index c9e90c30..b1c557ca 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -51,11 +51,12 @@ export type OAuthProps = { runJobId?: string; runIdentityProvider?: "exe.dev" | "fly.io"; /** Stable identifier for the OAuth authorization grant; never a bearer token. */ + vmGrantId?: string; oauthGrantId?: string; oauthClientId?: string; /** Expiry of the presented, verified OAuth access token. */ oauthExpiresAt?: number; - authMethod?: "session" | "oauth" | "access_token" | "vendor_identity"; + authMethod?: "session" | "oauth" | "access_token" | "vendor_identity" | "vm_grant"; }; export interface WorkItem { diff --git a/packages/api/src/vendor-run-identity.ts b/packages/api/src/vendor-run-identity.ts index 8896b79c..1d36a8b4 100644 --- a/packages/api/src/vendor-run-identity.ts +++ b/packages/api/src/vendor-run-identity.ts @@ -59,7 +59,7 @@ function audiences(value: unknown): string[] { return []; } -function providerVmId(provider: VendorIdentityProvider, claims: JwtClaims, binding: VendorRunBinding): string | null { +function providerVmId(provider: VendorIdentityProvider, claims: JwtClaims, binding: Omit): string | null { if (provider === "fly.io") return typeof claims.machine_id === "string" ? claims.machine_id : null; const attachment = binding.exeAttachment; if (!attachment || attachment.mode !== "vm" || !attachment.integrationName || attachment.attachedVmId !== binding.vmId) return null; @@ -88,6 +88,14 @@ export async function verifyVendorRunIdentity(options: { nowSeconds?: number; clockSkewSeconds?: number; }): Promise { + if (!options.binding.runId || options.binding.runId !== options.binding.activeRunId) throw new Error("Vendor identity is not bound to an active run"); + return { ...await verifyVendorMachineIdentity(options), runId: options.binding.runId }; +} + +export async function verifyVendorMachineIdentity(options: { + token: string; binding: Omit; resolveKey: JwksResolver; + nowSeconds?: number; clockSkewSeconds?: number; +}) { const { token, binding } = options; const parts = token.split("."); if (parts.length !== 3 || parts.some(part => !part)) throw new Error("Invalid vendor identity token"); @@ -105,11 +113,10 @@ export async function verifyVendorRunIdentity(options: { if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp <= now) throw new Error("Vendor identity has expired"); if (typeof claims.iat !== "number" || !Number.isFinite(claims.iat) || claims.iat > now + skew || claims.exp - claims.iat > maxAge + skew) throw new Error("Vendor identity lifetime is invalid"); if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || !Number.isFinite(claims.nbf) || claims.nbf > now + skew)) throw new Error("Vendor identity is not yet valid"); - if (!binding.runId || binding.runId !== binding.activeRunId) throw new Error("Vendor identity is not bound to an active run"); const vmId = providerVmId(binding.provider, claims, binding); if (!vmId || vmId !== binding.vmId) throw new Error("Vendor identity VM mismatch"); - return { provider: binding.provider, issuer: binding.issuer, subject: claims.sub, audience: binding.audience, runId: binding.runId, vmId, issuedAt: claims.iat, expiresAt: claims.exp, keyId: header.kid }; + return { provider: binding.provider, issuer: binding.issuer, subject: claims.sub, audience: binding.audience, vmId, issuedAt: claims.iat, expiresAt: claims.exp, keyId: header.kid }; } /** A bounded JWKS cache. Unknown kids force one refresh so key rotation fails closed. */ diff --git a/packages/api/src/vm-grants.ts b/packages/api/src/vm-grants.ts new file mode 100644 index 00000000..461f1e9e --- /dev/null +++ b/packages/api/src/vm-grants.ts @@ -0,0 +1,226 @@ +import { z } from "zod"; +import { AgentApiError, AgentApiService } from "./agent-api"; +import { grantVmInput } from "./agent-api-contracts"; +import { ExeVmBackend } from "./exe-vm-backend"; +import type { ExeConnection } from "./exe"; +import { ConnectionRepository } from "./postgres/connection-repository"; +import { databaseFor } from "./postgres/database"; +import type { Env, OAuthProps } from "./types"; +import { discoverVendorIssuerTrust, verifyVendorMachineIdentity } from "./vendor-run-identity"; + +export const VM_GRANT_HEADER = "X-Factorize-VM-Grant"; +type Grant = { + id: string; + tenant_id: string; + provider_id: string; + vm: string; + permissions: Record; + expires_at: Date; + revoked_at: Date | null; + issuer: string | null; + subject: string | null; + proof_hash: string | null; +}; +const nameFor = (id: string) => "fzvm-" + id.replaceAll("-", ""); +const audienceFor = (id: string) => "factorize://vm-grants/" + id; +const forbidden = () => new AgentApiError(403, "forbidden", "VM delegation is not authorized."); + +async function backend(env: Env, row: Grant) { + const db = databaseFor(env); + const integration = ( + await db.pool.query( + "SELECT credential_id FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2 AND kind='exe'", + [row.tenant_id, row.provider_id], + ) + ).rows[0]; + const connection = + integration && + (await new ConnectionRepository(db, row.tenant_id, env.CREDENTIAL_ENCRYPTION_KEY).get( + "exe:" + integration.credential_id, + )); + if (!connection) throw forbidden(); + return new ExeVmBackend(connection); +} + +async function verify( + row: Grant, + token: string, + attachment: { issuer: string; subject: string; audience: string; integrationName: string }, +) { + if (row.issuer && (row.issuer !== attachment.issuer || row.subject !== attachment.subject)) throw forbidden(); + const trust = await discoverVendorIssuerTrust({ provider: "exe.dev", issuer: attachment.issuer }); + await verifyVendorMachineIdentity({ + token, + resolveKey: trust.resolveKey, + binding: { + provider: "exe.dev", + vmId: row.vm, + issuer: trust.issuer, + audience: attachment.audience, + subject: attachment.subject, + exeAttachment: { integrationName: attachment.integrationName, attachedVmId: row.vm, mode: "vm" }, + }, + }); +} + +async function parent(env: Env, auth: OAuthProps) { + if (auth.authMethod !== "oauth" || !auth.scopes.includes("vm:grant")) throw forbidden(); + const api = new AgentApiService(env, auth); + return { api, id: (await api.identity()).id }; +} + +export async function grantVm(env: Env, auth: OAuthProps, value: unknown) { + const input = grantVmInput.parse(value); + if (!auth.scopes.includes("proxy:use")) throw forbidden(); + const { api, id } = await parent(env, auth); + const provider = (await api.authorize(input.providerIntegrationId)).integration; + if (provider.kind !== "exe") + throw new AgentApiError(400, "unsupported_provider", "Only exe.dev connections support VM grants."); + const permissions: Record = {}; + for (const target of input.integrationIds) permissions[target] = (await api.authorize(target)).integration.epoch; + const db = databaseFor(env); + // Commit the identity before remote provisioning; a lost response must reuse the WIF name. + const reserved = ( + await db.pool.query( + `INSERT INTO app.vm_grants(tenant_id,parent_id,provider_id,provider_epoch,vm,permissions,parent_scopes,request_key,expires_at) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,to_timestamp($9)) ON CONFLICT(tenant_id,parent_id,request_key) DO UPDATE SET request_key=excluded.request_key + RETURNING *`, + [ + auth.tenantId, + id, + provider.id, + provider.epoch, + input.vm, + JSON.stringify(permissions), + JSON.stringify(auth.scopes), + input.idempotencyKey, + auth.oauthExpiresAt, + ], + ) + ).rows[0]!; + if ( + reserved.provider_id !== provider.id || + reserved.vm !== input.vm || + Object.keys(reserved.permissions).length !== input.integrationIds.length || + input.integrationIds.some((key) => reserved.permissions[key] !== permissions[key]) + ) + throw new AgentApiError(409, "conflict", "This idempotency key belongs to a different grant."); + if (env.SCHEDULER) + await env.SCHEDULER.get(env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { + method: "POST", + }); + const grant = await db.transaction(async (tx) => { + const row = (await tx.query("SELECT * FROM app.vm_grants WHERE id=$1 FOR UPDATE", [reserved.id])) + .rows[0]!; + if (row.revoked_at || row.expires_at.getTime() <= Date.now()) throw forbidden(); + if (!row.issuer) { + const exe = await backend(env, row), + name = nameFor(row.id), + audience = audienceFor(row.id); + try { + // On a retry an exact, exclusive WIF attachment may already exist. + const attachment = await exe + .identityIntegration(row.vm, name, audience, false) + .catch(() => exe.identityIntegration(row.vm, name, audience, true)); + const guest = await exe.enrollGuest(row.vm, row.id, name); + await verify(row, guest.token, attachment); + await tx.query("UPDATE app.vm_grants SET issuer=$2,subject=$3,proof_hash=$4 WHERE id=$1", [ + row.id, + attachment.issuer, + attachment.subject, + guest.proofHash, + ]); + } catch { + throw new AgentApiError( + 502, + "enrollment_failed", + "Could not verify the exe.dev VM and its exclusive identity attachment.", + ); + } + } + return row; + }); + return { + grantId: grant.id, + vm: grant.vm, + integrationIds: Object.keys(grant.permissions), + expiresAt: grant.expires_at.toISOString(), + tokenUrl: `https://${nameFor(grant.id)}.int.exe.xyz/token`, + proofFile: `.factorize-vm-grants/${grant.id}`, + requestUrl: env.APP_ORIGIN + "/api/v1/agent/requests", + instructions: + "From the guest, use tokenUrl's token as a bearer token. Send X-Factorize-VM-Grant: grantId and X-Factorize-VM-Proof: the trimmed contents of proofFile under the enrollment user's home directory.", + }; +} + +export async function revokeVmGrant(env: Env, auth: OAuthProps, grantId: string) { + const { id } = await parent(env, auth); + const result = await databaseFor(env).pool.query( + "UPDATE app.vm_grants SET revoked_at=coalesce(revoked_at,now()) WHERE tenant_id=$1 AND parent_id=$2 AND id=$3", + [auth.tenantId, id, z.uuid().parse(grantId)], + ); + if (!result.rowCount) throw new AgentApiError(404, "not_found", "VM grant not found."); + return { grantId, revoked: true }; +} + +export async function authenticateVmGrant(env: Env, request: Request): Promise { + const id = request.headers.get(VM_GRANT_HEADER), + proof = request.headers.get("X-Factorize-VM-Proof"); + const token = request.headers.get("Authorization")?.match(/^Bearer ([\w.-]+)$/)?.[1]; + if (!z.uuid().safeParse(id).success || !proof || !/^[a-f0-9]{64}$/.test(proof) || !token || token.length > 16384) + return null; + const hash = Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(proof + "\n"))).toString( + "hex", + ); + const row = ( + await databaseFor(env).pool.query( + `SELECT g.*,p.user_id,p.session_version FROM app.vm_grants g + JOIN app.agent_identities p ON p.tenant_id=g.tenant_id AND p.id=g.parent_id + WHERE g.id=$1 AND g.proof_hash=$2 AND g.revoked_at IS NULL AND p.revoked_at IS NULL AND g.expires_at>now()`, + [id, hash], + ) + ).rows[0]; + if (!row || !row.issuer) return null; + try { + const attachment = await ( + await backend(env, row) + ).identityIntegration(row.vm, nameFor(row.id), audienceFor(row.id), false); + await verify(row, token, attachment); + return { + authMethod: "vm_grant", + tenantId: row.tenant_id, + userId: row.user_id, + sessionVersion: row.session_version, + scopes: [], + vmGrantId: row.id, + }; + } catch { + return null; + } +} + +export async function cleanupVmGrants(env: Env) { + const db = databaseFor(env); + // Claim a bounded batch. An unreachable provider cannot starve later grants; + // a worker interrupted after a remote removal can safely retry it. + const { rows } = await db.pool.query(`UPDATE app.vm_grants SET cleanup_after=now()+interval '15 minutes' + WHERE id IN (SELECT g.id FROM app.vm_grants g JOIN app.agent_identities p + ON p.tenant_id=g.tenant_id AND p.id=g.parent_id + WHERE g.cleaned_at IS NULL AND g.cleanup_after<=now() AND + (g.revoked_at IS NOT NULL OR g.expires_at<=now() OR p.revoked_at IS NOT NULL) + ORDER BY g.cleanup_after LIMIT 50 FOR UPDATE OF g SKIP LOCKED) RETURNING *`); + for (const row of rows) { + try { + const exe = await backend(env, row); + await exe.removeIdentityIntegration( + row.vm, + nameFor(row.id), + audienceFor(row.id), + row.issuer && row.subject ? { issuer: row.issuer, subject: row.subject } : undefined, + ); + await db.pool.query("UPDATE app.vm_grants SET cleaned_at=now() WHERE id=$1", [row.id]); + } catch { + console.warn("VM grant identity cleanup pending", row.id); + } + } +} diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index d51e5fe3..f4c96e3a 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,3 +1,4 @@ +import { authenticateVmGrant, VM_GRANT_HEADER } from "./vm-grants"; import { staticApp, securityHeaders } from "./static-app"; import { OAuthProvider, AuthorizationError, getOAuthApi, type AuthRequest, type OAuthProviderOptions } from "@cloudflare/workers-oauth-provider"; import app from "./index"; @@ -8,7 +9,7 @@ import { startConnection, connectionFor } from "./oauth-continuation"; 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 { AGENT_SCOPES, ACCESS_SCOPES, authenticateAccessToken, normalizeScopes } from "./access-tokens"; import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; import { artifactUpload, readArtifactUploadGrant } from "./artifact-upload"; import { traceChunkUpload } from "./trace-chunk-upload"; @@ -20,7 +21,7 @@ import { xOAuthCallback } from "./x-oauth-callback"; const scopes = [...ACCESS_SCOPES]; // Keep accepting grants issued by the pre-resource-scope protocol. New // consent screens and metadata advertise only the canonical scopes above. -const oauthScopes = [...new Set([...scopes, "flows:read", "flows:write", "runs:write"])]; +const oauthScopes = [...new Set([...AGENT_SCOPES, "flows:read", "flows:write", "runs:write"])]; async function currentOwner(request: Request, env: Env) { const session = await readSession(requestCookie(request, "factorize_session"), env.SESSION_SIGNING_SECRET); if (!session) return null; @@ -81,7 +82,7 @@ function providerOptions(env: Env): OAuthProviderOptions { return { scopesSupported: oauthScopes, allowImplicitFlow: false, allowPlainPKCE: false, accessTokenTTL: 3600, refreshTokenTTL: 2_592_000, clientIdMetadataDocumentEnabled: true, - resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: scopes, bearer_methods_supported: ["header"], resource_name: "Factorize jobs" }, + resourceMetadata: { resource: `${env.APP_ORIGIN}/mcp`, authorization_servers: [env.APP_ORIGIN], scopes_supported: [...AGENT_SCOPES], bearer_methods_supported: ["header"], resource_name: "Factorize jobs" }, }; } function provider(env: Env) { return new OAuthProvider(providerOptions(env)); } @@ -108,6 +109,27 @@ const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) if (!auth) return Response.json({ error: { code: "invalid_token", message: "The vendor identity is invalid or the run is no longer authorized." } }, { status: 401, headers: { "WWW-Authenticate": 'Bearer error="invalid_token"' } }); return protectedApiFetch(request, apiEnv, auth, ctx); } + const proxyEndpoint = request.method === "POST" && ["/api/v1/agent/requests","/api/v1/agent/responses/read"].includes(url.pathname); + if (request.headers.has(VM_GRANT_HEADER)) { + if (!proxyEndpoint) return Response.json({error:{code:"forbidden"}},{status:403}); + const auth = await authenticateVmGrant(apiEnv,request); + if (!auth) return Response.json({error:{code:"invalid_token"}},{status:401}); + return protectedApiFetch(request,apiEnv,auth,ctx); + } + const grantEndpoint = (url.pathname === "/api/v1/agent/vm-grants" && request.method === "POST") + || (request.method === "DELETE" && /^\/api\/v1\/agent\/vm-grants\/[a-f0-9-]+$/.test(url.pathname)); + const reflectionEndpoint = request.method === "GET" && url.pathname === "/api/v1/agent/reflection"; + if ((proxyEndpoint || grantEndpoint || reflectionEndpoint) && request.headers.get("Authorization")?.startsWith("Bearer ")) { + // These HTTP operations are part of the agent resource only with explicit + // proxy consent. Other REST operations retain their normal audience check. + const token = await apiEnv.OAUTH_PROVIDER.unwrapToken(request.headers.get("Authorization")!.slice(7)); + const props = token?.grant.props; + if (!token || token.audience !== env.APP_ORIGIN+"/mcp" || !props || props.userId !== token.userId || token.expiresAt <= Date.now()/1000) + return Response.json({error:{code:"invalid_token"}},{status:401}); + const effective = normalizeScopes(token.scope).filter(scope => normalizeScopes(props.scopes).includes(scope)); + if (!effective.includes("proxy:use")) return Response.json({error:{code:"insufficient_scope"}},{status:403, headers:{"WWW-Authenticate":'Bearer error="insufficient_scope", scope="proxy:use"'}}); + return protectedApiFetch(request,apiEnv,{...props,authMethod:"oauth",scopes:effective,oauthGrantId:token.grantId,oauthClientId:token.grant.clientId,oauthExpiresAt:token.expiresAt},ctx); + } if (isBrowserAuthOperation(request.method, url.pathname)) return protectedApiFetch(request, apiEnv, null, ctx); if (url.pathname.startsWith("/api/v1") && !request.headers.has("Authorization")) { // Signature and expiry here; the service performs the authoritative owner, diff --git a/packages/api/test/fixtures/agent-api-runtime-worker.ts b/packages/api/test/fixtures/agent-api-runtime-worker.ts index 21b14ee5..1df44dd7 100644 --- a/packages/api/test/fixtures/agent-api-runtime-worker.ts +++ b/packages/api/test/fixtures/agent-api-runtime-worker.ts @@ -1,3 +1,4 @@ +import { cleanupVmGrants } from "../../src/vm-grants"; import { WorkerEntrypoint } from "cloudflare:workers"; import worker from "../../src/worker"; import { cleanupAgentResponses } from "../../src/agent-api"; @@ -17,5 +18,5 @@ export default { // A test-only entrypoint drives the exact production heartbeat cleanup against // real PostgreSQL/R2, without adding a deployment endpoint or waiting 24 hours. export class AgentApiMaintenance extends WorkerEntrypoint { - async fetch() { await cleanupAgentResponses(this.env); return new Response("done"); } + async fetch() { await cleanupAgentResponses(this.env); await cleanupVmGrants(this.env); return new Response("done"); } } diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index 964e5b8d..531c6def 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -67,7 +67,7 @@ readable names and descriptions, instructions, access state, connection availability, and the required integration scope. Availability describes stored connection state, not a guarantee that an upstream credential is healthy. -Use `request_api` with `integration`, an HTTP `method`, a relative `path` including +POST JSON to the reflected `proxy.requestUrl` with `integration`, an HTTP `method`, a relative `path` including an optional query, optional safe `headers`, and optional `body`. `encoding` is `utf8` by default or `base64` for binary input. The origin and upstream credentials are selected by Factorize. A grant covers the whole integration, @@ -87,20 +87,16 @@ Responses preserve the upstream `status`, safe `headers`, byte `size`, and body. An upstream non-2xx status is distinct from a local authorization or proxy error. UTF-8 responses of up to 32 KiB return inline with `encoding: "utf8"`; binary responses use `base64`. Larger responses are consumed into R2 and return a -`handle` and `expiresAt`. A supporting MCP client receives standard progress -notifications when it supplies a progress token; these are not partial tool -result bodies. +`handle` and `expiresAt`. -Call `read_api_response` with the handle and a byte `offset` (initially zero). +POST JSON to `proxy.readResponseUrl` with the handle and a byte `offset` (initially zero). Chunks are always base64, up to 64 KiB; use `nextOffset` until `done` is true. Handles are tenant/identity bound, expire after 24 hours, and recheck access on every read. Revocation blocks subsequent calls and reads but cannot undo an upstream action already accepted. Existing VM proxy URLs retain true streaming. The same operations are documented under `/api/v1/agent/reflection`, -`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. OAuth audiences remain -bound to their registered resource: an MCP-bound token does not also authorize -REST. Owner policy endpoints require an interactive browser session. Authorized +`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. Authorize `proxy:use` to use the HTTP proxy with the agent credential. Existing MCP authorizations without this scope require renewed consent. Other REST operations retain their own authentication requirements. Clients migrating from `request_api` and `read_api_response` send the same JSON arguments to the reflected HTTP endpoints with the Factorize bearer token. Owner policy endpoints require an interactive browser session. Authorized clients settings revoke individual connections; the existing client-wide revoke endpoint remains available for compatibility. @@ -109,3 +105,15 @@ PostgreSQL receipts. A receipt exists before any R2 block is written, including interrupted/unreturned responses. Object deletion failures retain receipts for retry. Operators must retain the scheduler and RUN_ARTIFACTS binding when rolling out migration `0054_agent_api_grants`. + +## External VM access + +Start Codex with the device login helper from the Factorize checkout: + +```sh +node scripts/agent-login.mjs codex +``` + +Approve the displayed code. The helper sets the short-lived Factorize credential for the child process and configures the Factorize MCP connection to use it. Supply additional integration scopes from reflection in the space-separated `FACTORIZE_SCOPES` environment variable on a subsequent login. In a shell with this environment, send JSON to the reflected request URL using `curl -H "@$FACTORIZE_AGENT_AUTH_FILE" --json ...`. The file is private to your OS user and the helper removes it when the child exits. For exe.dev, send method `POST`, path `/exec`, headers `{"Content-Type":"text/plain"}` and a command in `body`. + +After creating a VM, call `grant_vm` with the provider integration ID, VM name, selected integration IDs and an idempotency key. The guest reads its WIF token and local proof using the receipt instructions. Both authenticate only the reflected HTTP proxy operations. Grants expire with the issuing access token. Access through independent provider-native integrations is outside this grant. Revocation removes the Factorize identity integration and leaves the VM running. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 36726f5a..75dd4855 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -409,7 +409,7 @@ readable names and descriptions, instructions, access state, connection availability, and the required integration scope. Availability describes stored connection state, not a guarantee that an upstream credential is healthy. -Use `request_api` with `integration`, an HTTP `method`, a relative `path` including +POST JSON to the reflected `proxy.requestUrl` with `integration`, an HTTP `method`, a relative `path` including an optional query, optional safe `headers`, and optional `body`. `encoding` is `utf8` by default or `base64` for binary input. The origin and upstream credentials are selected by Factorize. A grant covers the whole integration, @@ -429,20 +429,16 @@ Responses preserve the upstream `status`, safe `headers`, byte `size`, and body. An upstream non-2xx status is distinct from a local authorization or proxy error. UTF-8 responses of up to 32 KiB return inline with `encoding: "utf8"`; binary responses use `base64`. Larger responses are consumed into R2 and return a -`handle` and `expiresAt`. A supporting MCP client receives standard progress -notifications when it supplies a progress token; these are not partial tool -result bodies. +`handle` and `expiresAt`. -Call `read_api_response` with the handle and a byte `offset` (initially zero). +POST JSON to `proxy.readResponseUrl` with the handle and a byte `offset` (initially zero). Chunks are always base64, up to 64 KiB; use `nextOffset` until `done` is true. Handles are tenant/identity bound, expire after 24 hours, and recheck access on every read. Revocation blocks subsequent calls and reads but cannot undo an upstream action already accepted. Existing VM proxy URLs retain true streaming. The same operations are documented under `/api/v1/agent/reflection`, -`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. OAuth audiences remain -bound to their registered resource: an MCP-bound token does not also authorize -REST. Owner policy endpoints require an interactive browser session. Authorized +`/api/v1/agent/requests`, and `/api/v1/agent/responses/read`. Authorize `proxy:use` to use the HTTP proxy with the agent credential. Existing MCP authorizations without this scope require renewed consent. Other REST operations retain their own authentication requirements. Clients migrating from `request_api` and `read_api_response` send the same JSON arguments to the reflected HTTP endpoints with the Factorize bearer token. Owner policy endpoints require an interactive browser session. Authorized clients settings revoke individual connections; the existing client-wide revoke endpoint remains available for compatibility. @@ -452,6 +448,18 @@ interrupted/unreturned responses. Object deletion failures retain receipts for retry. Operators must retain the scheduler and RUN_ARTIFACTS binding when rolling out migration `0054_agent_api_grants`. +## External VM access + +Start Codex with the device login helper from the Factorize checkout: + +```sh +node scripts/agent-login.mjs codex +``` + +Approve the displayed code. The helper sets the short-lived Factorize credential for the child process and configures the Factorize MCP connection to use it. Supply additional integration scopes from reflection in the space-separated `FACTORIZE_SCOPES` environment variable on a subsequent login. In a shell with this environment, send JSON to the reflected request URL using `curl -H "@$FACTORIZE_AGENT_AUTH_FILE" --json ...`. The file is private to your OS user and the helper removes it when the child exits. For exe.dev, send method `POST`, path `/exec`, headers `{"Content-Type":"text/plain"}` and a command in `body`. + +After creating a VM, call `grant_vm` with the provider integration ID, VM name, selected integration IDs and an idempotency key. The guest reads its WIF token and local proof using the receipt instructions. Both authenticate only the reflected HTTP proxy operations. Grants expire with the issuing access token. Access through independent provider-native integrations is outside this grant. Revocation removes the Factorize identity integration and leaves the VM running. + ## Trigger configuration Source: https://docs.factorize.sh/integrations/triggers @@ -603,8 +611,8 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `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_api_reflection` | Authenticated OAuth/run identity | `{}`. Discover the authorization identity, effective scopes, and granted/requestable integration APIs, including instructions, required OAuth scope, and connection availability. | -| `request_api` | Baseline or integration scope; selected run grant | Required `integration`, `method`, relative `path`; optional safe `headers`, `body`, `encoding`. Send an integration-wide authorized request to a fixed upstream origin with server-injected credentials. Missing requestable access returns an HTTP OAuth insufficient-scope challenge before upstream side effects. Returns upstream status, safe headers, and UTF-8/base64 body or a 24-hour response handle. | -| `read_api_response` | Same identity and current integration grant | Required `handle`; optional byte `offset`. Read up to 64 KiB from a tenant/identity-bound retained response. Chunks are base64; every read rechecks authorization, revocation and expiry. | +| `grant_vm` | vm:grant and proxy:use | OAuth agent delegates explicit integration IDs to a VM on an eligible exe.dev connection. Requires providerIntegrationId, vm, integrationIds and idempotencyKey. | +| `revoke_vm_grant` | vm:grant | Requires grantId. Invalidates guest access and schedules identity integration cleanup. | | `get_runtime_context` | Authenticated identity | `{}`; verified authentication kind, effective scopes, and source run/job IDs, without credentials | | `get_job_invocation_permissions` | jobs:read | Required string `jobId` | | `set_job_invocation_permissions` | jobs:write | Required `jobId` and `destinationJobIds` UUID array; owner session, scoped API key, or authorized OAuth client | @@ -765,7 +773,7 @@ disabling or disconnecting revokes approvals, and re-enabling requires fresh con Job runs retain their independent, explicit credential selections. `get_api_reflection` lists integration references and access instructions. -`request_api` forwards a relative path using the selected integration's stored +The reflected HTTP proxy forwards a relative path using the selected integration's stored credential. The same policy applies to Bearer APIs, GitHub, Linear, model accounts, Fly.io, exe.dev, Amp, ClickUp, and X. Credentials stay on the server. diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index f5a63aea..9488525f 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -35,8 +35,8 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `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_api_reflection` | Authenticated OAuth/run identity | `{}`. Discover the authorization identity, effective scopes, and granted/requestable integration APIs, including instructions, required OAuth scope, and connection availability. | -| `request_api` | Baseline or integration scope; selected run grant | Required `integration`, `method`, relative `path`; optional safe `headers`, `body`, `encoding`. Send an integration-wide authorized request to a fixed upstream origin with server-injected credentials. Missing requestable access returns an HTTP OAuth insufficient-scope challenge before upstream side effects. Returns upstream status, safe headers, and UTF-8/base64 body or a 24-hour response handle. | -| `read_api_response` | Same identity and current integration grant | Required `handle`; optional byte `offset`. Read up to 64 KiB from a tenant/identity-bound retained response. Chunks are base64; every read rechecks authorization, revocation and expiry. | +| `grant_vm` | vm:grant and proxy:use | OAuth agent delegates explicit integration IDs to a VM on an eligible exe.dev connection. Requires providerIntegrationId, vm, integrationIds and idempotencyKey. | +| `revoke_vm_grant` | vm:grant | Requires grantId. Invalidates guest access and schedules identity integration cleanup. | | `get_runtime_context` | Authenticated identity | `{}`; verified authentication kind, effective scopes, and source run/job IDs, without credentials | | `get_job_invocation_permissions` | jobs:read | Required string `jobId` | | `set_job_invocation_permissions` | jobs:write | Required `jobId` and `destinationJobIds` UUID array; owner session, scoped API key, or authorized OAuth client | @@ -197,7 +197,7 @@ disabling or disconnecting revokes approvals, and re-enabling requires fresh con Job runs retain their independent, explicit credential selections. `get_api_reflection` lists integration references and access instructions. -`request_api` forwards a relative path using the selected integration's stored +The reflected HTTP proxy forwards a relative path using the selected integration's stored credential. The same policy applies to Bearer APIs, GitHub, Linear, model accounts, Fly.io, exe.dev, Amp, ClickUp, and X. Credentials stay on the server. diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 1ab39c8a..507efc87 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -15,6 +15,18 @@ components: type: http scheme: bearer bearerFormat: OAuth2 + vmWif: + type: http + scheme: bearer + bearerFormat: JWT + vmGrantHeader: + type: apiKey + in: header + name: X-Factorize-VM-Grant + vmProofHeader: + type: apiKey + in: header + name: X-Factorize-VM-Proof cookieAuth: type: apiKey in: cookie @@ -11270,6 +11282,178 @@ paths: runIdentityHeader: [] x-required-scope: [] x-owner-session-required: false + /api/v1/agent/vm-grants: + post: + summary: Delegate selected proxy integrations to an exe.dev VM + description: |- + Requires an OAuth agent with proxy:use, vm:grant and access to the provider and each selected integration. Expires with the issuing access token. + + Requires the vm:grant and proxy:use scopes. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + responses: + "200": + description: Verified VM grant + content: + application/json: + schema: + type: object + properties: + grantId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + vm: + type: string + integrationIds: + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + expiresAt: + type: string + tokenUrl: + type: string + format: uri + proofFile: + type: string + requestUrl: + type: string + format: uri + instructions: + type: string + required: + - grantId + - vm + - integrationIds + - expiresAt + - tokenUrl + - proofFile + - requestUrl + - instructions + 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: post_api_v1_agent_vm_grants + tags: + - agent + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: vm:grant+proxy:use + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + providerIntegrationId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + vm: + type: string + pattern: ^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$ + integrationIds: + minItems: 1 + maxItems: 64 + type: array + items: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + idempotencyKey: + type: string + minLength: 1 + maxLength: 160 + required: + - providerIntegrationId + - vm + - integrationIds + - idempotencyKey + additionalProperties: false + /api/v1/agent/vm-grants/{grantId}: + delete: + summary: Revoke an external VM grant + description: |- + Only the issuing OAuth grant can revoke. Access stops before provider cleanup. + + Requires the vm:grant scope. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + responses: + "200": + description: Revoked grant + content: + application/json: + schema: + type: object + properties: + grantId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + revoked: + type: boolean + required: + - grantId + - revoked + 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" + operationId: delete_api_v1_agent_vm_grants_grantId + tags: + - agent + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: vm:grant + x-owner-session-required: false + parameters: + - name: grantId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ /api/v1/agent/reflection: get: summary: Discover agent identity and granted or requestable integration APIs @@ -11305,6 +11489,22 @@ paths: type: array items: type: string + proxy: + type: object + properties: + requestUrl: + type: string + format: uri + readResponseUrl: + type: string + format: uri + authentication: + type: string + required: + - requestUrl + - readResponseUrl + - authentication + additionalProperties: false integrations: type: array items: @@ -11356,6 +11556,9 @@ paths: - unavailable instructions: type: string + vmGrantProvider: + type: string + const: exe.dev required: - id - credentialId @@ -11372,6 +11575,7 @@ paths: required: - identity - scopes + - proxy - integrations additionalProperties: false "400": @@ -11404,7 +11608,7 @@ paths: post: summary: Make an authorized credential-injected API request description: |- - Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. + OAuth requires proxy:use. An external VM sends its short-lived exe.dev WIF bearer token, X-Factorize-VM-Grant and X-Factorize-VM-Proof. Only server-selected origins are used. Integration-wide grants are bounded by upstream credential permissions. Missing requestable access returns HTTP 403 with WWW-Authenticate insufficient_scope, scope and resource_metadata. Upstream status is returned in the result, including non-2xx. Text is UTF-8; other bodies are base64. Responses above 32 KiB are retained for 24 hours and read in chunks. Revocation prevents subsequent calls and reads, but cannot undo upstream side effects. Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: @@ -11473,7 +11677,9 @@ paths: - bearerAuth: [] - vendorRunIdentity: [] runIdentityHeader: [] - - cookieAuth: [] + - vmWif: [] + vmGrantHeader: [] + vmProofHeader: [] x-required-scope: [] x-owner-session-required: false requestBody: @@ -11528,7 +11734,7 @@ paths: post: summary: Read up to 64 KiB of an identity-bound retained response description: |- - Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe. + Accepts the same OAuth, run or external VM authentication as the request endpoint. Rechecks authorization, integration revocation epoch, tenant, identity and 24-hour expiry. Chunks are always base64 so arbitrary byte offsets are safe. Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. responses: @@ -11596,7 +11802,9 @@ paths: - bearerAuth: [] - vendorRunIdentity: [] runIdentityHeader: [] - - cookieAuth: [] + - vmWif: [] + vmGrantHeader: [] + vmProofHeader: [] x-required-scope: [] x-owner-session-required: false requestBody: diff --git a/scripts/agent-api-runtime.test.mjs b/scripts/agent-api-runtime.test.mjs index 318e9fcb..445d9353 100644 --- a/scripts/agent-api-runtime.test.mjs +++ b/scripts/agent-api-runtime.test.mjs @@ -28,6 +28,11 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const {privateKey,publicKey}=generateKeyPairSync('rsa',{modulusLength:2048}); const jwk={...publicKey.export({format:'jwk'}),kid:'fixture',alg:'RS256',use:'sig'}; const jwt=claims=>{const head=Buffer.from(JSON.stringify({alg:'RS256',kid:'fixture'})).toString('base64url'),body=Buffer.from(JSON.stringify(claims)).toString('base64url');return head+'.'+body+'.'+sign('RSA-SHA256',Buffer.from(head+'.'+body),privateKey).toString('base64url');}; + // Simulate the documented exe.dev HTTPS command/identity API. Sign a real + // vendor JWT and keep the guest-local proof independent of the VM name. + const guestProof=randomBytes(32).toString('hex'); + const issuer='https://exe.dev/issuer/fixture'; + let wif,failEnrollment=true,guestJwt; const observed=[];let releaseStream; try { await admin.query(`CREATE DATABASE "${name}"`);address.pathname='/'+name;db=new pg.Client({connectionString:address.href});await db.connect(); @@ -59,6 +64,27 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const chunks=[];for await(const chunk of req) chunks.push(chunk); const target=new URL(req.headers['x-fixture-target']); const body=Buffer.concat(chunks).toString();observed.push({target:target.href,method:req.method,headers:req.headers,body}); + if(target.hostname==='exe.dev') { + if(target.pathname.startsWith('/issuer/')) { + res.end(JSON.stringify(target.pathname.endsWith('openid-configuration')?{issuer,jwks_uri:issuer+'/jwks'}:{keys:[jwk]}));return; + } + if(body==='integrations list --json') {res.end(JSON.stringify(wif?[wif]:[]));return;} + if(body.startsWith('integrations add wif ')) { + const name=body.match(/--name='([^']+)'/)[1], audience=body.match(/--audience='([^']+)'/)[1]; + assert.equal(wif,undefined,'retry must reuse the original integration'); + assert.ok(body.includes("--attach='vm:external-guest'")); + wif={name,type:'wif',config:{issuer_id:'fixture',subject:name,audience},attachments:['vm:external-guest']}; + res.end('{}');return; + } + if(body.startsWith("ssh 'external-guest' ")) { + if(failEnrollment) {failEnrollment=false;res.statusCode=503;res.end();return;} + if(body.includes('sha256sum')) {res.end(createHash('sha256').update(guestProof+'\n').digest('hex'));return;} + const now=Math.floor(Date.now()/1000); + guestJwt=jwt({iss:issuer,sub:wif.name,aud:wif.config.audience,iat:now,exp:now+300}); + res.end(guestJwt);return; + } + if(body.startsWith('integrations remove ')) {wif=undefined;res.end('{}');return;} + } if(target.hostname==='oidc.fly.io') {res.setHeader('Content-Type','application/json');res.end(JSON.stringify(target.pathname.endsWith('openid-configuration')?{issuer:'https://oidc.fly.io/fixture',jwks_uri:'https://oidc.fly.io/fixture/jwks'}:{keys:[jwk]}));return;} if(target.pathname==='/app/installations/17/access_tokens') {res.setHeader('Content-Type','application/json');res.end(JSON.stringify({token:'github-private',expires_at:new Date(Date.now()+3600000).toISOString()}));return;} if(target.pathname==='/oauth/token') {res.setHeader('Content-Type','application/json');res.end(JSON.stringify({access_token:target.hostname==='api.linear.app'?'linear-refreshed':'model-oauth-private',refresh_token:'refreshed-private',expires_in:3600}));return;} @@ -113,6 +139,7 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const context=await browser.newContext({ignoreHTTPSErrors:true});await context.addCookies([{name:'factorize_session',value:cookieValue,domain:'localhost',path:'/',httpOnly:true,secure:true}]); await context.route('http://127.0.0.1/callback**',route=>route.fulfill({body:'Done'})); const authorize=async(scopes=[],decision='allow',narrow)=>{ + scopes=[...scopes,'proxy:use']; const verifier=randomBytes(32).toString('base64url'),query=new URLSearchParams({response_type:'code',client_id:clientId,redirect_uri:'http://127.0.0.1/callback',scope:scopes.join(' '),state:randomUUID(),code_challenge:createHash('sha256').update(verifier).digest('base64url'),code_challenge_method:'S256',resource:origin+'/mcp'}); const page=await context.newPage();page.setDefaultTimeout(15000); await page.goto(origin+'/authorize?'+query);await page.getByRole('heading',{name:'Authorize Agent fixture',exact:true}).waitFor(); @@ -130,10 +157,42 @@ test('agent API OAuth, policy, connection isolation, run identity and response l try {messages=[JSON.parse(text)];}catch{messages=text.split('\n').filter(line=>line.startsWith('data: ')).map(line=>JSON.parse(line.slice(6)));} return {status:response.status,headers:response.headers,messages,text,result:messages.find(message=>message.id)?.result?.structuredContent}; }; - const request=(token,integration,path='/',extra={})=>rpc(token,'request_api',{integration:integration.id,method:'GET',path,...extra}); + const proxy=async(token,path,args)=>{ + const response=await json(path,'POST',args,{Authorization:'Bearer '+token.access_token}); + return {...response,result:response.status===200 ? response.body : undefined,text:JSON.stringify(response.body)}; + }; + const read=(token,args)=>proxy(token,'/api/v1/agent/responses/read',args); + const request=(token,integration,path='/',extra={})=>proxy(token,'/api/v1/agent/requests',{integration:integration.id,method:'GET',path,...extra}); const scopes=row=>'integration:'+row.id+':'+row.epoch; const first=await authorize(['jobs:read']),second=await authorize(['jobs:read']); const reflect=await rpc(first,'get_api_reflection');assert.equal(reflect.status,200,reflect.text);assert.equal(reflect.result.integrations.find(row=>row.id===baseline.id).access,'granted');assert.equal(reflect.result.integrations.find(row=>row.id===requestable.id).access,'requestable'); + // A new local agent obtains a single device authorization. Its HTTP client + // reads the private header file; MCP and shell credentials are never copied. + const childProgram = ` + import {readFile} from 'node:fs/promises'; + const origin=process.env.FACTORIZE_ORIGIN; + const response=await fetch(origin+'/mcp',{method:'POST',headers:{ + Authorization:'Bearer '+process.env.FACTORIZE_AGENT_TOKEN,Accept:'application/json, text/event-stream', + 'Content-Type':'application/json','MCP-Protocol-Version':'2025-11-25' + },body:JSON.stringify({jsonrpc:'2.0',id:1,method:'tools/call',params:{name:'get_api_reflection',arguments:{}}})}); + const text=await response.text(); + const payload=text.startsWith('{')?JSON.parse(text):JSON.parse(text.split('\\n').find(line=>line.startsWith('data: ')).slice(6)); + const info=payload.result.structuredContent; + const authorization=(await readFile(process.env.FACTORIZE_AGENT_AUTH_FILE,'utf8')).trim().slice('Authorization: '.length); + const proxy=await fetch(info.proxy.requestUrl,{method:'POST',headers:{authorization,'Content-Type':'application/json'}, + body:JSON.stringify({integration:info.integrations.find(row=>row.access==='granted').id,method:'GET',path:'/device-agent'})}); + if (!proxy.ok || (await proxy.json()).body!=='fixture response') process.exit(1); + `; + const login=exec(process.execPath,['scripts/agent-login.mjs',process.execPath,'--input-type=module','-e',childProgram],{ + env:{...process.env,FACTORIZE_ORIGIN:origin,NODE_EXTRA_CA_CERTS:directory+'/cert.pem'},timeout:30000 + }); + const code=await Promise.race([new Promise(resolve=>login.child.stderr.on('data',data=>{ + const match=String(data).match(/approve code ([A-Z2-9]{4}-[A-Z2-9]{4})/);if(match) resolve(match[1]); + })),login.then(()=>{throw new Error('Device login exited before consent');})]); + const preview=await json('/api/v1/oauth/device/preview','POST',{userCode:code},owner); + assert.equal(preview.status,200); + assert.equal((await json('/api/v1/oauth/device/decision','POST',{userCode:code,signature:preview.body.signature,decision:'allow'},owner)).status,200); + await login; const before=observed.length; const denied=await request(first,requestable,'/must-not-run',{method:'POST',body:'denied'});assert.equal(denied.status,403,denied.text);assert.match(denied.headers.get('WWW-Authenticate'),/error="insufficient_scope"/);assert.ok(denied.headers.get('WWW-Authenticate').includes(scopes(requestable)));assert.ok(denied.headers.get('WWW-Authenticate').includes('resource_metadata='));assert.equal(observed.length,before); const baselineCall=await request(first,baseline,'/items?q=1',{method:'POST',body:'payload',headers:{Authorization:'caller-secret',Cookie:'caller-cookie','X-Forwarded-Host':'hidden','Content-Type':'text/plain'}});assert.equal(baselineCall.result.body,'fixture response');assert.equal(baselineCall.result.status,200);assert.equal(baselineCall.result.headers['set-cookie'],undefined);assert.equal(baselineCall.result.headers.authorization,undefined);assert.equal(observed.at(-1).headers.authorization,'Bearer upstream-private');assert.equal(observed.at(-1).body,'payload');assert.ok(observed.at(-1).target.endsWith('/items?q=1'));assert.equal(observed.at(-1).headers.cookie,undefined);assert.ok(!baselineCall.text.includes('upstream-private')); @@ -143,7 +202,7 @@ test('agent API OAuth, policy, connection isolation, run identity and response l assert.equal((await request(first,baseline)).result.status,200,'ordinary authorization preserves old connection'); const refreshed=await form({grant_type:'refresh_token',client_id:clientId,refresh_token:stepped.refresh_token,resource:origin+'/mcp'});assert.equal((await request(refreshed,requestable)).result.status,200); assert.equal((await rpc(refreshed,'get_api_reflection')).result.identity.id,(await rpc(stepped,'get_api_reflection')).result.identity.id); - const narrowed=await form({grant_type:'refresh_token',client_id:clientId,refresh_token:refreshed.refresh_token,scope:'jobs:read',resource:origin+'/mcp'});assert.equal((await request(narrowed,requestable)).status,403,'presented token narrowing wins over consent props'); + const narrowed=await form({grant_type:'refresh_token',client_id:clientId,refresh_token:refreshed.refresh_token,scope:'jobs:read proxy:use',resource:origin+'/mcp'});assert.equal((await request(narrowed,requestable)).status,403,'presented token narrowing wins over consent props'); const policy=async(row,value)=>{const current=(await db.query('SELECT revision FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2',[tenant,row.id])).rows[0];const result=await json('/api/v1/integration-api-policies/'+row.id,'PUT',{policy:value,expectedRevision:current.revision},owner);assert.equal(result.status,200,JSON.stringify(result.body));return result;}; await policy(requestable,'baseline');assert.equal((await request(first,requestable)).result.status,200);assert.equal((await rpc(first,'get_api_reflection')).result.integrations.find(row=>row.id===requestable.id).access,'granted'); await policy(requestable,'requestable');assert.equal((await request(first,requestable)).status,403);assert.equal((await request(stepped,requestable)).result.status,200); @@ -155,9 +214,9 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const failure=await request(first,baseline,'/failure');assert.equal(failure.result.status,422); const redirectBefore=observed.length;assert.ok((await request(first,baseline,'/redirect')).text.includes('proxy_failed'));assert.equal(observed.length,redirectBefore+1); const large=await request(first,baseline,'/large');assert.equal(large.result.size,1140000,large.text);assert.ok(large.result.handle);assert.equal(large.result.body,undefined); - const chunk=await rpc(first,'read_api_response',{handle:large.result.handle,offset:1040000});assert.equal(Buffer.from(chunk.result.body,'base64').length,65536);assert.ok(Buffer.from(chunk.result.body,'base64').every(value=>value===255)); - assert.ok((await rpc(second,'read_api_response',{handle:large.result.handle,offset:0})).text.includes('not_found')); - const progress=await rpc(first,'request_api',{integration:baseline.id,method:'GET',path:'/'},{progressToken:'fixture-progress'});assert.equal(progress.messages.filter(message=>message.method==='notifications/progress').length,2,progress.text); + const chunk=await read(first,{handle:large.result.handle,offset:1040000});assert.equal(Buffer.from(chunk.result.body,'base64').length,65536);assert.ok(Buffer.from(chunk.result.body,'base64').every(value=>value===255)); + assert.ok((await read(second,{handle:large.result.handle,offset:0})).text.includes('not_found')); + const removed=await rpc(first,'request_api',{integration:baseline.id,method:'GET',path:'/'},{progressToken:'fixture-progress'});assert.ok(!removed.result,'proxy tool removed'); const policies=await json('/api/v1/integration-api-policies','GET',undefined,owner);assert.equal(policies.status,200); const otherTenant=randomUUID();await db.query('INSERT INTO app.tenants(id) VALUES($1)',[otherTenant]); const foreign=randomUUID();await db.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available,policy) VALUES($1,$2,'bearer','foreign','Foreign',true,'baseline')",[otherTenant,foreign]);assert.equal((await request(first,{id:foreign})).status,403); @@ -167,7 +226,7 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const foreignCookie=encodeURIComponent(foreignSession+'.'+createHmac('sha256',secret).update(foreignSession).digest('base64')); await context.addCookies([{name:'factorize_session',value:foreignCookie,domain:'localhost',path:'/',httpOnly:true,secure:true}]); const foreignToken=await authorize(['jobs:read']); - assert.ok((await rpc(foreignToken,'read_api_response',{handle:large.result.handle,offset:0})).text.includes('not_found')); + assert.ok((await read(foreignToken,{handle:large.result.handle,offset:0})).text.includes('not_found')); assert.equal((await json('/api/v1/access/authorizations/'+foreignToken.access_token.split(':')[1],'DELETE',undefined,owner)).status,404); await context.addCookies([{name:'factorize_session',value:cookieValue,domain:'localhost',path:'/',httpOnly:true,secure:true}]); // Cleanup executes inside workerd with actual R2 storage and PostgreSQL receipts. @@ -175,7 +234,7 @@ test('agent API OAuth, policy, connection isolation, run identity and response l const prefixes=(await db.query('SELECT object_key FROM app.agent_proxy_responses WHERE tenant_id=$1 AND id=ANY($2::uuid[])',[tenant,[expired.result.handle,interrupted.result.handle]])).rows.map(row=>row.object_key); await db.query("UPDATE app.agent_proxy_responses SET expires_at=now()-interval '1 second' WHERE tenant_id=$1 AND id=ANY($2::uuid[])",[tenant,[expired.result.handle,interrupted.result.handle]]); await db.query('UPDATE app.agent_proxy_responses SET size=NULL WHERE tenant_id=$1 AND id=$2',[tenant,interrupted.result.handle]); - assert.ok((await rpc(second,'read_api_response',{handle:expired.result.handle,offset:0})).text.includes('not_found')); + assert.ok((await read(second,{handle:expired.result.handle,offset:0})).text.includes('not_found')); const maintenance=(await mf.getBindings()).MAINTENANCE;assert.equal((await maintenance.fetch('https://maintenance/')).status,200); assert.equal((await db.query('SELECT 1 FROM app.agent_proxy_responses WHERE tenant_id=$1 AND id=ANY($2::uuid[])',[tenant,[expired.result.handle,interrupted.result.handle]])).rowCount,0); const bucket=await mf.getR2Bucket('RUN_ARTIFACTS');for(const prefix of prefixes) assert.equal((await bucket.list({prefix})).objects.length,0); @@ -210,6 +269,45 @@ test('agent API OAuth, policy, connection isolation, run identity and response l await policy(row,'disabled'); assert.equal((await request(approved,row,provider.path)).status,403); await policy(row,'requestable'); assert.equal((await request(approved,row,provider.path)).status,403,'disable revokes old consent for '+provider.kind); await policy(row,'baseline'); + if (provider.kind==='exe') { + const delegator=await authorize(['vm:grant']); + const info=(await rpc(delegator,'get_api_reflection')).result; + assert.equal(info.proxy.requestUrl,origin+'/api/v1/agent/requests'); + assert.equal(info.integrations.find(item=>item.id===row.id).vmGrantProvider,'exe.dev'); + const input={providerIntegrationId:row.id,vm:'external-guest',integrationIds:[baseline.id],idempotencyKey:'create-external-guest'}; + assert.ok(!(await rpc(first,'grant_vm',input)).result,'delegation requires its own scope'); + assert.ok(!(await rpc(delegator,'grant_vm',input)).result,'provider failure leaves enrollment retryable'); + const enrolled=await rpc(delegator,'grant_vm',input); + assert.ok(enrolled.result?.grantId,enrolled.text); + const grantId=enrolled.result.grantId; + assert.equal((await rpc(delegator,'grant_vm',input)).result.grantId,grantId); + assert.ok(!(await rpc(delegator,'grant_vm',{...input,vm:'another-guest'})).result); + const guest=(integration,proof=guestProof)=>json('/api/v1/agent/requests','POST',{integration,method:'GET',path:'/guest'},{ + Authorization:'Bearer '+guestJwt,'X-Factorize-VM-Grant':grantId,'X-Factorize-VM-Proof':proof}); + assert.equal((await guest(baseline.id)).body.body,'fixture response'); + assert.equal((await guest(row.id)).status,403,'a baseline provider outside the subset stays unavailable'); + assert.equal((await guest(baseline.id,'0'.repeat(64))).status,401,'a replacement VM lacks the enrollment proof'); + wif.attachments.push('vm:other'); + assert.equal((await guest(baseline.id)).status,401); + wif.attachments.pop(); + assert.ok(!(await rpc(second,'revoke_vm_grant',{grantId})).result); + assert.equal((await rpc(delegator,'revoke_vm_grant',{grantId})).result.revoked,true); + assert.equal((await guest(baseline.id)).status,401,'an unexpired signed token cannot revive a revoked grant'); + assert.equal((await maintenance.fetch('https://maintenance/')).status,200); + assert.equal(wif,undefined); + const expiring=(await rpc(delegator,'grant_vm',{...input,idempotencyKey:'expire'})).result; + await db.query("UPDATE app.vm_grants SET expires_at=now()-interval '1 second' WHERE id=$1",[expiring.grantId]); + const delegatedRequest=id=>json('/api/v1/agent/requests','POST',{integration:baseline.id,method:'GET',path:'/expired'},{ + Authorization:'Bearer '+guestJwt,'X-Factorize-VM-Grant':id,'X-Factorize-VM-Proof':guestProof}); + assert.equal((await delegatedRequest(expiring.grantId)).status,401); + await maintenance.fetch('https://maintenance/'); + const child=(await rpc(delegator,'grant_vm',{...input,idempotencyKey:'parent-revoked'})).result; + assert.equal((await delegatedRequest(child.grantId)).status,200); + assert.equal((await json('/api/v1/access/authorizations/'+delegator.access_token.split(':')[1],'DELETE',undefined,owner)).status,200); + assert.equal((await delegatedRequest(child.grantId)).status,401); + await maintenance.fetch('https://maintenance/'); + assert.equal(wif,undefined); + } if (provider.kind==='amp' || provider.kind==='clickup') { const beforeEscape=observed.length; assert.ok((await request(first,row,'/../outside')).text.includes('credential_unavailable')); @@ -290,10 +388,10 @@ test('agent API OAuth, policy, connection isolation, run identity and response l await db.query("UPDATE app.integration_records SET deleted_at=now(),encrypted_payload=NULL WHERE tenant_id=$1 AND id=$2",[tenant,baseline.credential_id]); await db.query("UPDATE app.integration_records SET deleted_at=NULL,encrypted_payload=$3 WHERE tenant_id=$1 AND id=$2",[tenant,baseline.credential_id,encrypt('factorize-managed-bearer-v1:upstream-private')]); assert.equal((await send('/internal/run-proxy/'+runId+'/integrations/'+baseline.credential_id+'/','GET',undefined,runHeaders)).status,403,'run disconnect revocation survives reconnect'); - assert.equal((await rpc(first,'read_api_response',{handle:large.result.handle,offset:0})).status,403,'retained responses cannot cross a disconnect epoch'); + assert.equal((await read(first,{handle:large.result.handle,offset:0})).status,403,'retained responses cannot cross a disconnect epoch'); await db.query("UPDATE app.job_runs SET state='stopped' WHERE tenant_id=$1 AND id=$2",[tenant,runId]);assert.equal((await send('/internal/run-proxy/'+runId+'/integrations/'+baseline.credential_id+'/','GET',undefined,runHeaders)).status,403); - await policy(baseline,'requestable');assert.equal((await request(first,baseline)).status,403);assert.equal((await rpc(first,'read_api_response',{handle:large.result.handle,offset:0})).status,403,'reads require current grants');await policy(baseline,'baseline'); - const grantId=first.access_token.split(':')[1];assert.equal((await json('/api/v1/access/authorizations/'+grantId,'DELETE',undefined,owner)).status,200);assert.equal((await request(first,baseline)).status,401);assert.equal((await rpc(first,'read_api_response',{handle:large.result.handle,offset:0})).status,401);assert.equal((await request(second,baseline)).result.status,200); + await policy(baseline,'requestable');assert.equal((await request(first,baseline)).status,403);assert.equal((await read(first,{handle:large.result.handle,offset:0})).status,403,'reads require current grants');await policy(baseline,'baseline'); + const grantId=first.access_token.split(':')[1];assert.equal((await json('/api/v1/access/authorizations/'+grantId,'DELETE',undefined,owner)).status,200);assert.equal((await request(first,baseline)).status,401);assert.equal((await read(first,{handle:large.result.handle,offset:0})).status,401);assert.equal((await request(second,baseline)).result.status,200); await context.close(); } finally { releaseStream?.();await browser?.close();if(site) await new Promise(resolve=>site.close(resolve));await mf?.dispose();if(upstream) await new Promise(resolve=>upstream.close(resolve));await db?.end();await admin.query(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`);await admin.end();await rm(directory,{recursive:true,force:true}); diff --git a/scripts/agent-login.mjs b/scripts/agent-login.mjs new file mode 100644 index 00000000..a9d0eb01 --- /dev/null +++ b/scripts/agent-login.mjs @@ -0,0 +1,83 @@ +// Start a process with the same device authorization for HTTP and MCP. +import { mkdtemp, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawn } from "node:child_process"; +import { setTimeout as wait } from "node:timers/promises"; + +const origin = new URL(process.env.FACTORIZE_ORIGIN || "https://app.factorize.sh").origin; +if (!origin.startsWith("https://")) throw new Error("Factorize requires HTTPS"); +const grant = "urn:ietf:params:oauth:grant-type:device_code"; +const post = async (path, body, type) => { + const response = await fetch(origin + path, { + method: "POST", + redirect: "error", + headers: { "Content-Type": type }, + body, + }); + return response.json(); +}; +const [command = "codex", ...args] = process.argv.slice(2); +const client = await post( + "/oauth/register", + JSON.stringify({ + client_name: "Factorize external agent", + grant_types: [grant], + token_endpoint_auth_method: "none", + }), + "application/json", +); +if (!client.client_id) throw new Error("Device client registration failed"); +const form = (path, fields) => post(path, new URLSearchParams(fields), "application/x-www-form-urlencoded"); +const device = await form("/oauth/device_authorization", { + client_id: client.client_id, + scope: ["proxy:use", "vm:grant", process.env.FACTORIZE_SCOPES || ""].join(" ").trim(), +}); +if (!device.device_code) throw new Error("Device authorization failed"); +console.error("Open", device.verification_uri, "and approve code", device.user_code); +const deadline = Date.now() + device.expires_in * 1000; +let interval = device.interval || 5; +let token; +while (Date.now() < deadline) { + await wait(interval * 1000); + const result = await form("/oauth/token", { + client_id: client.client_id, + device_code: device.device_code, + grant_type: grant, + }); + if (result.access_token) { + token = result.access_token; + break; + } + if (result.error === "slow_down") interval += 5; + else if (result.error !== "authorization_pending") + throw new Error("Device authorization failed: " + result.error); +} +if (!token) throw new Error("Device authorization expired"); +const directory = await mkdtemp(join(tmpdir(), "factorize-agent-")); +const authFile = join(directory, "authorization"); +try { + await writeFile(authFile, "Authorization: Bearer " + token + "\n", { mode: 0o600 }); + const config = + command === "codex" + ? [ + "-c", + "mcp_servers.factorize.url=" + JSON.stringify(origin + "/mcp"), + "-c", + 'mcp_servers.factorize.bearer_token_env_var="FACTORIZE_AGENT_TOKEN"', + "-c", + "shell_environment_policy.set.FACTORIZE_AGENT_AUTH_FILE=" + JSON.stringify(authFile), + ] + : []; + const child = spawn(command, [...config, ...args], { + stdio: "inherit", + env: { ...process.env, FACTORIZE_AGENT_TOKEN: token, FACTORIZE_AGENT_AUTH_FILE: authFile }, + }); + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.once(signal, () => child.kill(signal)); + process.exitCode = await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("exit", (code) => resolve(code ?? 1)); + }); +} finally { + await rm(directory, { recursive: true, force: true }); +}