From 70a5c4a74844be40fc49dde0b0818431f5d2f4e5 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 19:36:19 +0000 Subject: [PATCH] Unify OAuth and run integration grants with agent API proxy --- package.json | 2 +- packages/api-client/src/schema.d.ts | 434 ++++++++++++ .../api/migrations/0054_agent_api_grants.sql | 92 +++ packages/api/src/access-tokens.ts | 3 +- packages/api/src/agent-api-contracts.ts | 18 + packages/api/src/agent-api.ts | 215 ++++++ packages/api/src/agent-credentials.ts | 52 ++ packages/api/src/api-contract.ts | 13 +- packages/api/src/auth-api.ts | 3 +- packages/api/src/consent-api.ts | 17 +- packages/api/src/device-oauth.ts | 5 +- packages/api/src/flow-service.ts | 36 +- packages/api/src/postgres/run-scheduler.ts | 2 + packages/api/src/postgres/schema.ts | 13 +- packages/api/src/protected-api.ts | 71 +- packages/api/src/run-outbound-forwarder.ts | 2 +- packages/api/src/run-outbound-proxy.ts | 76 +-- packages/api/src/types.ts | 2 + packages/api/test/agent-api.postgres.test.ts | 60 ++ packages/api/test/api-boundary.test.ts | 17 +- .../test/fixtures/agent-api-runtime-worker.ts | 21 + .../test/report-run-error-boundary.test.ts | 2 +- .../api/test/run-outbound-forwarder.test.ts | 13 + packages/app/src/features/auth/consent.tsx | 2 +- packages/app/src/features/auth/device.tsx | 2 +- .../src/features/settings/api-policies.tsx | 21 + .../features/settings/authorized-clients.tsx | 4 +- .../src/features/settings/integrations.tsx | 3 +- packages/docs/integrations/oauth.mdx | 68 ++ packages/docs/llms-full.txt | 71 ++ packages/docs/mcp/tools.mdx | 3 + packages/docs/openapi.yaml | 636 ++++++++++++++++++ scripts/agent-api-runtime.test.mjs | 216 ++++++ 33 files changed, 2085 insertions(+), 110 deletions(-) create mode 100644 packages/api/migrations/0054_agent_api_grants.sql create mode 100644 packages/api/src/agent-api-contracts.ts create mode 100644 packages/api/src/agent-api.ts create mode 100644 packages/api/src/agent-credentials.ts create mode 100644 packages/api/test/agent-api.postgres.test.ts create mode 100644 packages/api/test/fixtures/agent-api-runtime-worker.ts create mode 100644 packages/app/src/features/settings/api-policies.tsx create mode 100644 scripts/agent-api-runtime.test.mjs diff --git a/package.json b/package.json index d0c88eef..11dc8bcc 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ "build": "npm run build:app", "check:hosting": "node --test scripts/hosting-invariants.test.mjs scripts/deployment-gate.test.mjs scripts/trusted-app-release.test.mjs && python3 scripts/test-retain-app-assets.py", "test:hosting-runtime": "node --test scripts/hosting-runtime.test.mjs scripts/vendor-identity-runtime.test.mjs", - "test:oauth-runtime": "node --test scripts/oauth-runtime.test.mjs", + "test:oauth-runtime": "node --test scripts/oauth-runtime.test.mjs scripts/agent-api-runtime.test.mjs", "test:rollback-runtime": "node --test scripts/rollback-runtime.test.mjs", "test:conditions-runtime": "node --test scripts/webhook-conditions-runtime.test.mjs", "test:docker": "node scripts/docker-execution-e2e.mjs" diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 88813973..f8760e95 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1048,6 +1048,30 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/access/authorizations/{grantId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Revoke one isolated OAuth connection + * @description Other connections, including copies of the same client, retain their approvals. + * + * Requires the jobs:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_access_authorizations_grantId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/access/authorized-clients/{clientId}": { parameters: { query?: never; @@ -1654,6 +1678,118 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/agent/reflection": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * 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. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + get: operations["get_api_v1_agent_reflection"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/agent/requests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + 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. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_agent_requests"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/agent/responses/read": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + 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. + * + * Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + */ + post: operations["post_api_v1_agent_responses_read"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/integration-api-policies": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List tenant MCP API access policies + * @description Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_integration_api_policies"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/integration-api-policies/{integrationId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * 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. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_integration_api_policies_integrationId"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/runtime-context": { parameters: { query?: never; @@ -3869,6 +4005,11 @@ export interface operations { scopes: string[]; expiresAt: string; signature: string; + integrationLabels?: { + scope: string; + name: string; + description: string | null; + }[]; }; }; }; @@ -3951,6 +4092,11 @@ export interface operations { request: string; signature: string; expiresAt: string; + integrationLabels?: { + scope: string; + name: string; + description: string | null; + }[]; }; }; }; @@ -5224,6 +5370,38 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + delete_api_v1_access_authorizations_grantId: { + parameters: { + query?: never; + header?: never; + path: { + grantId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Authorization revoked */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revoked: number; + }; + }; + }; + 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"]; + }; + }; delete_api_v1_access_authorized_clients_clientId: { parameters: { query?: never; @@ -7074,6 +7252,262 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_agent_reflection: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Agent reflection */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + identity: { + /** Format: uuid */ + id: string; + /** @enum {string} */ + kind: "oauth" | "run"; + }; + scopes: string[]; + integrations: { + /** Format: uuid */ + id: string; + name: string; + description: string | null; + /** @enum {string} */ + kind: "bearer" | "github" | "linear" | "model"; + /** @enum {string} */ + policy: "baseline" | "requestable" | "disabled"; + available: boolean; + revision: number; + requiredScope: string; + /** @enum {string} */ + access: "granted" | "requestable" | "unavailable"; + instructions: string; + }[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_agent_requests: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + integration: string; + /** @enum {string} */ + method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS"; + path: string; + /** @default {} */ + headers?: { + [key: string]: string; + }; + body?: string; + /** + * @default utf8 + * @enum {string} + */ + encoding?: "utf8" | "base64"; + }; + }; + }; + responses: { + /** @description Upstream response or retained response handle */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + status: number; + headers: { + [key: string]: string; + }; + size: number; + /** @enum {string} */ + encoding: "utf8" | "base64"; + body?: string; + /** Format: uuid */ + handle?: string; + expiresAt?: 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"]; + }; + }; + post_api_v1_agent_responses_read: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + handle: string; + /** @default 0 */ + offset?: number; + }; + }; + }; + responses: { + /** @description Response chunk */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + handle: string; + offset: number; + nextOffset: number; + size: number; + /** @constant */ + encoding: "base64"; + body: string; + done: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + get_api_v1_integration_api_policies: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Policies */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + integrations: { + /** Format: uuid */ + id: string; + name: string; + description: string | null; + /** @enum {string} */ + kind: "bearer" | "github" | "linear" | "model"; + /** @enum {string} */ + policy: "baseline" | "requestable" | "disabled"; + available: boolean; + revision: number; + requiredScope: string; + }[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_integration_api_policies_integrationId: { + parameters: { + query?: never; + header?: never; + path: { + integrationId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** @enum {string} */ + policy: "baseline" | "requestable" | "disabled"; + expectedRevision: number; + }; + }; + }; + responses: { + /** @description Updated policies */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + integrations: { + /** Format: uuid */ + id: string; + name: string; + description: string | null; + /** @enum {string} */ + kind: "bearer" | "github" | "linear" | "model"; + /** @enum {string} */ + policy: "baseline" | "requestable" | "disabled"; + available: boolean; + revision: number; + requiredScope: string; + }[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_runtime_context: { parameters: { query?: never; diff --git a/packages/api/migrations/0054_agent_api_grants.sql b/packages/api/migrations/0054_agent_api_grants.sql new file mode 100644 index 00000000..35fc5e63 --- /dev/null +++ b/packages/api/migrations/0054_agent_api_grants.sql @@ -0,0 +1,92 @@ +-- Stable references survive disconnects. Epoch scopes cannot revive after a +-- disconnect or disable; credential rotation deliberately retains the epoch. +CREATE TABLE app.agent_integrations ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + id uuid NOT NULL DEFAULT gen_random_uuid(), + kind text NOT NULL CHECK(kind IN ('bearer','github','linear','model')), + credential_id text NOT NULL, + name text NOT NULL, + description text, + available boolean NOT NULL, + policy text NOT NULL DEFAULT 'requestable' CHECK(policy IN ('baseline','requestable','disabled')), + epoch integer NOT NULL DEFAULT 1 CHECK(epoch>0), + revision integer NOT NULL DEFAULT 1, + PRIMARY KEY(tenant_id,id), UNIQUE(tenant_id,kind,credential_id) +); +CREATE FUNCTION app.sync_agent_integration(t uuid,k text,c text,n text,d text,a boolean) RETURNS void LANGUAGE sql AS $$ + INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) VALUES(t,k,c,n,d,a) + ON CONFLICT(tenant_id,kind,credential_id) DO UPDATE SET name=excluded.name,description=excluded.description,available=excluded.available, + epoch=app.agent_integrations.epoch+CASE WHEN app.agent_integrations.available AND NOT excluded.available THEN 1 ELSE 0 END, + revision=app.agent_integrations.revision+1; +$$; +CREATE FUNCTION app.agent_integration_changed() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF TG_TABLE_NAME='integration_records' THEN + IF TG_OP='DELETE' THEN + PERFORM app.sync_agent_integration(OLD.tenant_id,OLD.kind,OLD.id::text,OLD.name,OLD.description,false); + ELSE + PERFORM app.sync_agent_integration(NEW.tenant_id,NEW.kind,NEW.id::text,NEW.name,NEW.description,NEW.deleted_at IS NULL); + END IF; + ELSIF TG_TABLE_NAME='github_installations' THEN + IF TG_OP='DELETE' THEN + PERFORM app.sync_agent_integration(OLD.tenant_id,'github',OLD.installation_id::text,'GitHub · '||OLD.account_login,'GitHub installation API',false); + ELSE + PERFORM app.sync_agent_integration(NEW.tenant_id,'github',NEW.installation_id::text,'GitHub · '||NEW.account_login,'GitHub installation API',NEW.state='active'); + END IF; + ELSE + IF TG_OP='DELETE' THEN + IF OLD.kind='linear' THEN PERFORM app.sync_agent_integration(OLD.tenant_id,'linear','linear','Linear','Linear GraphQL API',false); END IF; + ELSE + IF NEW.kind='linear' THEN PERFORM app.sync_agent_integration(NEW.tenant_id,'linear','linear','Linear','Linear GraphQL API',true); END IF; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER agent_integration_sync AFTER INSERT OR UPDATE OR DELETE ON app.integration_records FOR EACH ROW EXECUTE FUNCTION app.agent_integration_changed(); +CREATE TRIGGER agent_github_sync AFTER INSERT OR UPDATE OR DELETE ON app.github_installations FOR EACH ROW EXECUTE FUNCTION app.agent_integration_changed(); +CREATE TRIGGER agent_linear_sync AFTER INSERT OR UPDATE OR DELETE ON app.connections FOR EACH ROW EXECUTE FUNCTION app.agent_integration_changed(); +INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) + SELECT tenant_id,kind,id::text,name,description,deleted_at IS NULL FROM app.integration_records; +INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) + SELECT tenant_id,'github',installation_id::text,'GitHub · '||account_login,'GitHub installation API',state='active' FROM app.github_installations; +INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available) + SELECT tenant_id,'linear','linear','Linear','Linear GraphQL API',true FROM app.connections WHERE kind='linear'; +CREATE FUNCTION app.invalidate_agent_policy() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.policy<>NEW.policy THEN + NEW.revision=OLD.revision+1; + IF NEW.policy='disabled' THEN NEW.epoch=OLD.epoch+1; END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER agent_policy_revocation BEFORE UPDATE OF policy ON app.agent_integrations FOR EACH ROW EXECUTE FUNCTION app.invalidate_agent_policy(); +CREATE TABLE app.agent_identities ( + tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, + id uuid NOT NULL DEFAULT gen_random_uuid(), + kind text NOT NULL CHECK(kind IN ('oauth','run')), + subject text NOT NULL, + user_id uuid NOT NULL, + session_version integer NOT NULL, + revoked_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY(tenant_id,id), UNIQUE(tenant_id,kind,subject) +); +-- Reserve a cleanup receipt before uploading. Failed uploads and interrupted +-- calls leave expiring receipts, so no R2 object can become an orphan. +CREATE TABLE app.agent_proxy_responses ( + tenant_id uuid NOT NULL, + id uuid NOT NULL, + identity_id uuid NOT NULL, + integration_id uuid NOT NULL, + integration_epoch integer NOT NULL, + object_key text NOT NULL UNIQUE, + size integer, + expires_at timestamptz NOT NULL, + PRIMARY KEY(tenant_id,id), + FOREIGN KEY(tenant_id,identity_id) REFERENCES app.agent_identities(tenant_id,id), + FOREIGN KEY(tenant_id,integration_id) REFERENCES app.agent_integrations(tenant_id,id) +); +CREATE INDEX agent_proxy_response_expiry ON app.agent_proxy_responses(expires_at); +INSERT INTO app.schema_migrations(version) VALUES ('0054_agent_api_grants') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/access-tokens.ts b/packages/api/src/access-tokens.ts index ca549c7d..39c8cb27 100644 --- a/packages/api/src/access-tokens.ts +++ b/packages/api/src/access-tokens.ts @@ -1,3 +1,4 @@ +import { isIntegrationScope } from "./agent-api-contracts"; import type { Env, OAuthProps } from "./types"; import { databaseFor } from "./postgres/database"; import { AccessTokenRepository } from "./postgres/access-token-repository"; @@ -13,7 +14,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)) result.add(scope); + else if (ACCESS_SCOPES.includes(scope as AccessScope) || 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 new file mode 100644 index 00000000..4d19a01a --- /dev/null +++ b/packages/api/src/agent-api-contracts.ts @@ -0,0 +1,18 @@ +import { z } from "zod"; +export const integrationScopePattern = /^integration:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}):([1-9][0-9]{0,9})$/; +export const isIntegrationScope = (scope: string) => integrationScopePattern.test(scope); +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, name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model"]), 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 requestApiInput = z.object({ + integration: integrationRef, + method: z.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]), + path: z.string().min(1).max(8192).refine(path => path.startsWith("/") && !path.startsWith("//") && !/[\\\r\n\0#]/.test(path), "Supply a relative path/query starting with one slash"), + headers: z.record(z.string().regex(/^[!#$%&'*+.^_\x60|~0-9A-Za-z-]+$/), z.string().max(8192).refine(value => !/[\r\n\0]/.test(value))).default({}).refine(headers => Object.keys(headers).length <= 64), + body: z.string().max(44_739_244).optional(), encoding: z.enum(["utf8", "base64"]).default("utf8"), +}).strict().refine(input => !input.body || input.method !== "GET" && input.method !== "HEAD", "GET/HEAD cannot have a body"); +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() }); diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts new file mode 100644 index 00000000..95d1b97f --- /dev/null +++ b/packages/api/src/agent-api.ts @@ -0,0 +1,215 @@ +import { Buffer } from "node:buffer"; +import type { Env, OAuthProps } from "./types"; +import { databaseFor } from "./postgres/database"; +import { IdentityRepository } from "./postgres/identity-repository"; +import { normalizeScopes } from "./access-tokens"; +import { integrationScopePattern, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; +import { resolveAgentCredential } from "./agent-credentials"; +import { forwardRunOutbound } from "./run-outbound-forwarder"; +import type { z } from "zod"; + +export class AgentApiError extends Error { + constructor(readonly status: number, readonly code: string, message: string, readonly scope?: string) { super(message); } +} +export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number}; +export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`; +const STORAGE_BLOCK_BYTES = 1024 * 1024; +const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized."); +const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active."); +const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, name: row.name, description: row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) }); + +/** These are structural checks only: reflection never refreshes/decrypts secrets. */ +export async function integrationConsentLabels(env: Env, tenantId: string, scopes: string[]) { + const labels: Array<{scope: string; name: string; description: string | null}> = []; + for (const scope of scopes) { + const match = integrationScopePattern.exec(scope); + if (!match) { if (scope.startsWith("integration:")) throw forbidden(); continue; } + const row = (await databaseFor(env).pool.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2", [tenantId, match[1]])).rows[0]; + if (!row || !row.available || row.policy === "disabled" || requiredIntegrationScope(row) !== scope) throw forbidden(); + labels.push({scope, name: row.name, description: row.description}); + } + return labels; +} + +export class AgentApiService { + constructor(private env: Env, private auth: OAuthProps) {} + private get database() { return databaseFor(this.env); } + async identity() { + 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; + 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 + JOIN app.job_runs j ON j.tenant_id=r.tenant_id AND j.id=r.id + JOIN app.vendor_run_identity_bindings b ON b.tenant_id=j.tenant_id AND b.run_id=j.id + JOIN app.run_authorizations a ON a.tenant_id=j.tenant_id AND a.run_id=j.id + WHERE r.tenant_id=$1 AND r.id=$2 AND b.provider=$3 AND b.revoked_at IS NULL + AND a.user_id=$4 AND a.session_version=$5 + 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 === "oauth" && auth.oauthGrantId && auth.oauthClientId && auth.oauthExpiresAt && auth.oauthExpiresAt > Date.now()/1000) { + kind = "oauth"; subject = auth.oauthGrantId; + } else throw invalidIdentity(); + const row = (await this.database.pool.query<{id: string; user_id: string; session_version: number; revoked_at: Date | null}>(`INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version) + VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET subject=excluded.subject + RETURNING id,user_id,session_version,revoked_at`, [auth.tenantId, kind, subject, auth.userId, auth.sessionVersion])).rows[0]!; + if (row.revoked_at || row.user_id !== auth.userId || row.session_version !== auth.sessionVersion) throw invalidIdentity(); + return {id: row.id, kind, config}; + } + private selected(row: AgentIntegration, config: Record) { + switch(row.kind) { + case "bearer": return Array.isArray(config.portableIntegrationIds) && config.portableIntegrationIds.includes(row.credential_id); + case "github": return Array.isArray(config.githubInstallationIds) && config.githubInstallationIds.includes(Number(row.credential_id)); + case "linear": return config.linearConnectionId === "linear"; + case "model": return config.modelAccess === "portable" && config.modelAccountId === row.credential_id; + } + } + async authorize(integration: string) { + 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 (!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(); + } else { + if (row.policy === "disabled" || !row.available) throw forbidden(); + if (row.policy !== "baseline" && !this.auth.scopes.includes(requiredIntegrationScope(row))) throw new AgentApiError(403, "insufficient_scope", "Approve this integration before making the request.", requiredIntegrationScope(row)); + } + return {identity, integration: row}; + } + async reflection() { + const identity = await this.identity(); + const rows = (await this.database.pool.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 ORDER BY name,id", [this.auth.tenantId])).rows; + const result = []; + for (const row of rows) { + if (identity.kind === "run" ? !this.selected(row, identity.config!) : row.policy === "disabled") continue; + let access: "granted" | "requestable" | "unavailable" = "granted"; + try { await this.authorize(row.id); } catch (error) { + if (!(error instanceof AgentApiError) || error.status === 401) throw error; + access = error.code === "insufficient_scope" ? "requestable" : "unavailable"; + } + result.push({...publicIntegration(row), access, instructions: row.kind === "linear" ? "Use request_api with path /graphql and a JSON GraphQL body." : 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."}); + } + return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), integrations: result}; + } + async forward(integration: string, path: string, request: Request) { + const grant = await this.authorize(integration); + let credential; + try { credential = await resolveAgentCredential(this.env, this.auth.tenantId, grant.integration.kind, grant.integration.credential_id, path); } + catch { throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved."); } + if (!credential) throw new AgentApiError(502, "credential_unavailable", "The upstream credential is unavailable; ask the owner to repair it."); + // Refresh may await a remote provider. Recheck policy, run state and revocations. + const current = await this.authorize(integration); + if (current.integration.epoch !== grant.integration.epoch) throw forbidden(); + try { return await forwardRunOutbound(request, credential); } + catch { throw new AgentApiError(502, "proxy_failed", "The upstream request failed."); } + } + async request(input: z.infer, signal?: AbortSignal) { + const parsed = requestApiInput.parse(input); + // Decode and size-check before any upstream operation. + let bytes: Uint8Array | undefined; + try { bytes = parsed.body === undefined ? undefined : parsed.encoding === "base64" ? decodeBase64(parsed.body) : new TextEncoder().encode(parsed.body); } + catch { throw new AgentApiError(400, "invalid_request", "Invalid base64 request body."); } + if (bytes && bytes.byteLength > 32*1024*1024) throw new AgentApiError(413, "request_too_large", "Request body exceeds the proxy limit."); + const response = await this.forward(parsed.integration, parsed.path, new Request(`${this.env.APP_ORIGIN}/mcp`, {method: parsed.method, headers: parsed.headers, body: bytes as Uint8Array | undefined, signal})); + const headers: Record = {}; response.headers.forEach((value,key) => {headers[key]=value;}); + const reader = response.body?.getReader(), chunks: Uint8Array[] = []; + let size = 0, buffered = 0, block = 0; + let handle: string | undefined, expiresAt: string | undefined, key: string | undefined; + // R2 accepts known-length byte buffers. Store bounded 1 MiB blocks while + // consuming upstream, rather than buffering the complete response in memory. + const pending = new Uint8Array(STORAGE_BLOCK_BYTES); let pendingSize = 0; + const write = async (value: Uint8Array) => { + for (let offset=0;offset 64*1024*1024) throw new Error("Proxy response exceeds limit"); + if (!key && size > 32768) { + if (!this.env.RUN_ARTIFACTS) throw new Error("Response storage unavailable"); + const grant = await this.authorize(parsed.integration); + handle = crypto.randomUUID(); expiresAt = new Date(Date.now()+86400_000).toISOString(); + key = `agent-responses/${this.auth.tenantId}/${grant.identity.id}/${handle}`; + await this.database.pool.query(`INSERT INTO app.agent_proxy_responses(tenant_id,id,identity_id,integration_id,integration_epoch,object_key,expires_at) VALUES($1,$2,$3,$4,$5,$6,$7)`, [this.auth.tenantId,handle,grant.identity.id,parsed.integration,grant.integration.epoch,key,expiresAt]); + // Start the maintenance heartbeat even on otherwise idle tenants. + if(this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake",{method:"POST"}); + for (const chunk of chunks) await write(chunk); + chunks.length = 0; + } + if (key) await write(value); else { chunks.push(value); buffered += value.byteLength; } + } + if (key) { + if(pendingSize) await this.env.RUN_ARTIFACTS!.put(`${key}/${block++}`,pending.slice(0,pendingSize).buffer); + await this.authorize(parsed.integration); + await this.database.pool.query("UPDATE app.agent_proxy_responses SET size=$3 WHERE tenant_id=$1 AND id=$2", [this.auth.tenantId,handle,size]); + return {status: response.status,headers,size,encoding: "base64" as const,handle,expiresAt}; + } + const body = new Uint8Array(buffered); let offset = 0; for (const chunk of chunks) {body.set(chunk,offset);offset+=chunk.byteLength;} + await this.authorize(parsed.integration); + try { return {status: response.status,headers,size,encoding: "utf8" as const,body: new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(body)}; } + catch { return {status: response.status,headers,size,encoding: "base64" as const,body: encodeBase64(body)}; } + } catch (error) { + await reader?.cancel().catch(() => {}); + if (error instanceof AgentApiError) throw error; + throw new AgentApiError(502,"proxy_failed","The upstream response could not be retained."); + } + } + async authorizeRead(input: z.infer) { + const {handle,offset} = readApiResponseInput.parse(input), identity = await this.identity(); + const row = (await this.database.pool.query<{object_key: string; size: number; integration_id: string; integration_epoch: number}>("SELECT object_key,size,integration_id,integration_epoch FROM app.agent_proxy_responses WHERE tenant_id=$1 AND id=$2 AND identity_id=$3 AND expires_at>clock_timestamp() AND size IS NOT NULL", [this.auth.tenantId,handle,identity.id])).rows[0]; + if (!row) throw new AgentApiError(404,"not_found","Response handle not found or expired."); + const grant = await this.authorize(row.integration_id); + if (grant.integration.epoch !== row.integration_epoch) throw forbidden(); + if (offset > row.size) throw new AgentApiError(400,"invalid_request","Offset exceeds response size."); + return row; + } + async read(input: z.infer) { + const {handle,offset} = readApiResponseInput.parse(input), row = await this.authorizeRead(input); + const length = Math.min(65536,row.size-offset), body = new Uint8Array(length); + let copied=0; + while(copied=row.size}; + } +} +export async function listAgentPolicies(env: Env, tenantId: string) { + return {integrations:(await databaseFor(env).pool.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 ORDER BY name,id",[tenantId])).rows.map(publicIntegration)}; +} +export async function cleanupAgentResponses(env: Env) { + if (!env.RUN_ARTIFACTS) return; + const database = databaseFor(env); + const rows = (await database.pool.query<{tenant_id:string;id:string;object_key:string}>("SELECT tenant_id,id,object_key FROM app.agent_proxy_responses WHERE expires_atobject.key)); + cursor = page.truncated ? page.cursor : undefined; + } while(cursor); + await database.pool.query("DELETE FROM app.agent_proxy_responses WHERE tenant_id=$1 AND id=$2 AND expires_at { + if (body.length%4 || /[^A-Za-z0-9+/=]/.test(body) || !/^[A-Za-z0-9+/]*={0,2}$/.test(body)) throw new Error(); + const alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if(body.endsWith("==") ? (alphabet.indexOf(body.at(-3)!) & 15)!==0 : body.endsWith("=") && (alphabet.indexOf(body.at(-2)!) & 3)!==0) throw new Error(); + return Buffer.from(body,"base64"); +} diff --git a/packages/api/src/agent-credentials.ts b/packages/api/src/agent-credentials.ts new file mode 100644 index 00000000..7ed7d5c6 --- /dev/null +++ b/packages/api/src/agent-credentials.ts @@ -0,0 +1,52 @@ +import type { Env } from "./types"; +import { databaseFor } from "./postgres/database"; +import { CredentialRepository } from "./postgres/credential-repository"; +import { resolveRunProviderCredentials } from "./provider-credentials"; +import type { OutboundCredential } from "./run-outbound-forwarder"; +import { resolveManagedModelCredential } from "./managed-model-credentials"; +import { isPublicHttpsOrigin } from "./public-address"; + +/** Only call after shared identity/grant authorization. No caller origin or secret. */ +export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string): Promise { + const database = databaseFor(env); + const modelAccountId = credentialId; + const prefix = kind === "bearer" ? `/integrations/${credentialId}` : kind === "github" ? `/providers/github/${credentialId}` : kind === "linear" ? "/providers/linear" : "/providers/model/v1"; + const separator = relativePath.indexOf("?"); + const path = prefix + (separator < 0 ? relativePath : relativePath.slice(0, separator)); + const url = {search: separator < 0 ? "" : relativePath.slice(separator)}; + const bearer = /^\/integrations\/([0-9a-f-]{36})(\/.*)?$/.exec(path); + const github = /^\/providers\/github\/([1-9][0-9]*)(\/.*)?$/.exec(path); + const linear = /^\/providers\/linear(\/.*)?$/.exec(path); + const model = /^\/providers\/model\/v1(\/.*)?$/.exec(path); + let selected: OutboundCredential | null = null; + if (bearer) { + const credential = await new CredentialRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(bearer[1]!, "bearer"); + if (!credential?.origin || !isPublicHttpsOrigin(credential.origin, env.APP_ORIGIN)) return null; + selected = {origin: credential.origin, path: `${bearer[2] ?? "/"}${url.search}`, credential: credential.payload}; + } else if (github) { + const installationId = Number(github[1]); + if (!Number.isSafeInteger(installationId)) return null; + const resolved = await resolveRunProviderCredentials({database, env, tenantId: tenantId, githubInstallationIds: [installationId], linearSelected: false}); + const credential = resolved.githubInstallations[0]; + if (!credential?.available || !credential.accessToken) return null; + let suffix = github[2] ?? "/", origin = "https://api.github.com"; + const smart = /\/(?:info\/refs|git-upload-pack|git-receive-pack)$/.test(suffix); + if (smart) origin = "https://github.com"; + else if (suffix.startsWith("/raw/")) { origin = "https://raw.githubusercontent.com"; suffix = suffix.slice(4); } + else if (suffix.startsWith("/archive/")) { origin = "https://codeload.github.com"; suffix = suffix.slice(8); } + selected = {origin, path: `${suffix}${url.search}`, credential: credential.accessToken, authorization: smart ? "github-git-basic" : "bearer"}; + } else if (linear) { + const resolved = await resolveRunProviderCredentials({database, env, tenantId: tenantId, githubInstallationIds: [], linearSelected: true}); + if (!resolved.linearConnection?.available || !resolved.linearConnection.accessToken) return null; + selected = {origin: "https://api.linear.app", path: `${linear[1] ?? "/graphql"}${url.search}`, credential: resolved.linearConnection.accessToken}; + } else if (model) { + const credential = await resolveManagedModelCredential({database, env, tenantId: tenantId, accountId: modelAccountId}); + if (!credential) return null; + const suffix = model[1] ?? "/"; + const target = new URL(`${credential.origin}${credential.prefix}${suffix}`); + if (!target.pathname.startsWith(`${credential.prefix}/`)) return null; + selected = {origin: credential.origin, path: `${target.pathname}${url.search}`, credential: credential.accessToken, + ...(credential.accountId ? {headers: {"chatgpt-account-id": credential.accountId}} : {})}; + } + return selected; +} diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 32e21172..aa40c7ae 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,3 +1,4 @@ +import { 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"; @@ -48,7 +49,7 @@ export interface RouteContract { documentation: Record; execute: ( service: ApiService, - input: { params: Record; body: any; query: any; url: URL }, + input: { params: Record; body: any; query: any; url: URL; signal?: AbortSignal }, ) => Promise; } @@ -152,7 +153,7 @@ function route( documentation: RouteContract["documentation"], execute: RouteContract["execute"], options: Partial< - Pick + Pick > = {}, ): RouteContract { const keys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]); @@ -271,7 +272,7 @@ export const API_ROUTES: RouteContract[] = [ authRoute("POST", "/api/v1/auth/password", "password", "Change password and invalidate sessions", authSuccess, authInputs.change), authRoute("POST", "/api/v1/auth/logout", "logout", "Revoke current session and clear browser cookie", authSuccess), - route("POST", "/api/v1/oauth/device/preview", "flows:read", { summary: "Inspect a device authorization code", responses: { "200": { description: "Pending device request", content: { "application/json": { schema: jsonSchema(z.object({ userCode: z.string(), clientName: z.string(), scopes: z.array(z.string()), expiresAt: z.string(), signature: z.string() }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32) }).strict(), authOperation: "device-preview", ownerSession: true }), + route("POST", "/api/v1/oauth/device/preview", "flows:read", { summary: "Inspect a device authorization code", responses: { "200": { description: "Pending device request", content: { "application/json": { schema: jsonSchema(z.object({ userCode: z.string(), clientName: z.string(), scopes: z.array(z.string()), expiresAt: z.string(), signature: z.string(), integrationLabels: z.array(z.object({scope:z.string(),name:z.string(),description:z.string().nullable()})).optional() }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32) }).strict(), authOperation: "device-preview", ownerSession: true }), route("POST", "/api/v1/oauth/device/decision", "flows:write", { summary: "Approve or deny a device authorization code", responses: { "200": { description: "Device decision", content: { "application/json": { schema: jsonSchema(z.object({ status: z.enum(["approved", "denied"]) }), "output") } } } } }, async () => undefined, { body: z.object({ userCode: z.string().min(1).max(32), signature: z.string().min(1).max(256), decision: z.enum(["allow", "deny"]) }).strict(), authOperation: "device-decision", ownerSession: true }), route("POST", "/api/v1/oauth/consent/preview", "flows:read", { summary: "Inspect an OAuth consent request", responses: { "200": { description: "Owner-bound expiring consent", content: { "application/json": { schema: jsonSchema(consentPreviewResponse, "output") } } } } }, async () => undefined, { body: consentPreviewInput, authOperation: "consent-preview", ownerSession: true }), route("POST", "/api/v1/oauth/consent/decision", "flows:write", { summary: "Decide an OAuth consent request", responses: { "200": { description: "Validated protocol destination", content: { "application/json": { schema: jsonSchema(consentDecisionResponse, "output") } } } } }, async () => undefined, { body: consentDecisionInput, authOperation: "consent-decision", ownerSession: true }), @@ -616,6 +617,7 @@ export const API_ROUTES: RouteContract[] = [ (service, { params }) => service.revokeAccessToken(params.tokenId), { ownerSession: true }, ), + route("DELETE", "/api/v1/access/authorizations/{grantId}", "jobs:write", {summary:"Revoke one isolated OAuth connection", description:"Other connections, including copies of the same client, retain their approvals.",responses:{"200":{description:"Authorization revoked",content:{"application/json":{schema:jsonSchema(z.object({revoked:z.number().int()}),"output")}}}}}, (service,{params})=>service.revokeOAuthAuthorization(params.grantId), {ownerSession:true}), route( "DELETE", "/api/v1/access/authorized-clients/{clientId}", @@ -853,6 +855,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("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("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", { summary: "Inspect the current runtime identity and scopes", description: "Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments.", diff --git a/packages/api/src/auth-api.ts b/packages/api/src/auth-api.ts index e1093c2d..1ec38bc7 100644 --- a/packages/api/src/auth-api.ts +++ b/packages/api/src/auth-api.ts @@ -1,3 +1,4 @@ +import { integrationConsentLabels } from "./agent-api"; import { ACCESS_SCOPES } from "./access-tokens"; import { connectionFor, originalBrowser, startConnection, connectionDestination } from "./oauth-continuation"; import { inspectDevice, decideDevice, deviceConsentSignature, safeEqual } from "./device-oauth"; @@ -117,7 +118,7 @@ export async function executeAuth(action: AuthAction, request: Request, env: Env const preview = await inspectDevice(env, String(input.userCode)); if (!preview) return failure(400, "This device request is invalid, expired, or already completed. Start a new connection in your client."); const signature = await deviceConsentSignature(env, session, preview); - if (action === "device-preview") return authJson({ ...preview, signature }); + if (action === "device-preview") return authJson({ ...preview, signature, integrationLabels: await integrationConsentLabels(env, session.tenantId, preview.scopes) }); if (!safeEqual(String(input.signature), signature)) return failure(403, "Invalid device consent. Review the device request before approving it."); const result = await decideDevice(env, env.OAUTH_PROVIDER, session, preview.userCode, input.decision as "allow" | "deny"); return result ? authJson(result) : failure(400, "This device request has expired or already completed. Start a new connection in your client."); diff --git a/packages/api/src/consent-api.ts b/packages/api/src/consent-api.ts index b3f7fbc9..09ea9cb0 100644 --- a/packages/api/src/consent-api.ts +++ b/packages/api/src/consent-api.ts @@ -1,3 +1,5 @@ +import { integrationConsentLabels } from "./agent-api"; +import { isIntegrationScope } from "./agent-api-contracts"; import { databaseFor } from "./postgres/database"; import { connectionFor, originalBrowser } from "./oauth-continuation"; import { z } from "zod"; @@ -8,7 +10,7 @@ import type { Session } from "./session"; import { ACCESS_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() }); +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 encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value)))); @@ -34,8 +36,10 @@ export async function consentPreview(env: Env, session: Session, input: z.infer< const nonce = crypto.randomUUID(); await databaseFor(env).pool.query("INSERT INTO app.oauth_consent_previews(id,expires_at) VALUES ($1,$2)", [nonce, new Date(expiresAt * 1000)]); const request = encode({ parsed, expiresAt, nonce, connection: connectionId }); - const requestedScopes = parsed.scope.filter(scope => supported.includes(scope)); - return { clientName: client.clientName ?? "this client", scopes: requestedScopes.some(scope => scope.startsWith("flows:") || scope === "runs:write") ? requestedScopes : normalizeScopes(requestedScopes), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; + if (parsed.scope.some(scope => !supported.includes(scope) && !isIntegrationScope(scope))) return null; + const requestedScopes = parsed.scope; + const integrationLabels = await integrationConsentLabels(env, session.tenantId, requestedScopes); + return { integrationLabels, clientName: client.clientName ?? "this client", scopes: requestedScopes.some(scope => scope.startsWith("flows:") || scope === "runs:write") ? requestedScopes : normalizeScopes(requestedScopes), request, signature: await hmac(binding(request, session), env.SESSION_SIGNING_SECRET), expiresAt: new Date(expiresAt * 1000).toISOString() }; } export async function consentDecision(env: Env, session: Session, input: z.infer) { if (!env.OAUTH_PROVIDER || !equal(input.signature, await hmac(binding(input.request, session), env.SESSION_SIGNING_SECRET))) return null; @@ -46,11 +50,11 @@ export async function consentDecision(env: Env, session: Session, input: z.infer // Revalidate client registration and redirect URI before grant issuance. const client = await env.OAUTH_PROVIDER.lookupClient(parsed.clientId); if (!client || !client.redirectUris.includes(parsed.redirectUri)) return null; - const allowed = new Set(normalizeScopes(parsed.scope.filter(scope => supported.includes(scope)))); + const allowed = new Set(normalizeScopes(parsed.scope.filter(scope => supported.includes(scope) || isIntegrationScope(scope)))); 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]))) return null; + 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; 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; @@ -59,8 +63,9 @@ export async function consentDecision(env: Env, session: Session, input: z.infer if (!consumed.rows.length) return null; } if (input.decision === "deny") { const redirect = new URL(parsed.redirectUri); redirect.searchParams.set("error", "access_denied"); redirect.searchParams.set("state", parsed.state); if (parsed.issuer) redirect.searchParams.set("iss", parsed.issuer); return { redirectTo: redirect.toString() }; } + await integrationConsentLabels(env, session.tenantId, issuedScopes); const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: issuedScopes, authMethod: "oauth" }; - const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: issuedScopes, props }); + const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: issuedScopes, props, revokeExistingGrants: false }); return { redirectTo }; }); } diff --git a/packages/api/src/device-oauth.ts b/packages/api/src/device-oauth.ts index ca862732..bbadc6e8 100644 --- a/packages/api/src/device-oauth.ts +++ b/packages/api/src/device-oauth.ts @@ -1,3 +1,5 @@ +import { integrationConsentLabels } from "./agent-api"; +import { isIntegrationScope } from "./agent-api-contracts"; import { staticApp } from "./static-app"; import type { AuthRequest } from "@cloudflare/workers-oauth-provider"; import { hmac } from "./crypto"; @@ -113,7 +115,7 @@ export async function deviceAuthorization(request: Request, env: Env, oauth: OAu if (!await authenticateDeviceClient(request, env, form, client)) return oauthError("invalid_client", "Client authentication failed.", 401); if (!client.redirectUris.length) return oauthError("unauthorized_client", "The client must have a registered redirect URI."); const requested = String(form.get("scope") ?? "").split(/\s+/).filter(Boolean); - const invalidScope = requested.find(value => !supportedScopes.includes(value)); + const invalidScope = requested.find(value => !supportedScopes.includes(value) && !isIntegrationScope(value)); if (invalidScope) return oauthError("invalid_scope", `Unsupported scope: ${invalidScope}`); const resource = String(form.get("resource") ?? `${env.APP_ORIGIN}/mcp`); if (resource !== `${env.APP_ORIGIN}/mcp`) return oauthError("invalid_target", "The resource must be the Factorize MCP endpoint."); @@ -225,6 +227,7 @@ export async function decideDevice(env: Env, oauth: OAuthHelpers, session: { ten const authorize = async (record: DeviceRecord | null, write: (record: DeviceRecord) => Promise) => { if (!record || record.status !== "pending" || record.expiresAt <= Math.floor(Date.now() / 1000)) return null; if (decision === "deny") { record.status = "denied"; await write(record); return { status: "denied" as const }; } + await integrationConsentLabels(env, session.tenantId, record.scope); const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: record.scope, authMethod: "oauth" }; const authRequest: AuthRequest = { responseType: "code", clientId: record.clientId, redirectUri: record.redirectUri, scope: record.scope, state: "", codeChallenge: record.codeChallenge, codeChallengeMethod: "S256", resource: record.resource, issuer: env.APP_ORIGIN }; const result = await oauth.completeAuthorization({ request: authRequest, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: record.scope, props, revokeExistingGrants: false }); diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 3e53c44a..7caf2a5b 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,3 +1,5 @@ +import { AgentApiService, listAgentPolicies } from "./agent-api"; +import { apiPolicyInput, integrationRef, requestApiInput, readApiResponseInput } from "./agent-api-contracts"; import { DEFAULT_RUN_SCOPES } from "./run-scopes"; import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; @@ -206,6 +208,19 @@ 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); } + 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)); } + async listApiPolicies() { await this.authorizeOwnerSession("integrations:read"); return listAgentPolicies(this.env, this.auth.tenantId); } + async updateApiPolicy(id: string, input: unknown) { + await this.authorizeOwnerSession("integrations:write"); + integrationRef.parse(id); const parsed = apiPolicyInput.parse(input); + const updated = await databaseFor(this.env).pool.query("UPDATE app.agent_integrations SET policy=$3 WHERE tenant_id=$1 AND id=$2 AND revision=$4 RETURNING id", [this.auth.tenantId,id,parsed.policy,parsed.expectedRevision]); + if (!updated.rowCount) throw new ServiceError(409,"stale_policy","Integration policy changed or is unavailable. Reload before updating."); + return this.listApiPolicies(); + } + async getRuntimeIntegrations() { await this.authorizeIdentity(); if (this.auth.authMethod !== "vendor_identity" || !this.auth.runId) throw new ServiceError(403, "forbidden", "A vendor-verified run identity is required."); @@ -705,12 +720,29 @@ export class ApiService { await this.authorizeOwnerSession("jobs:read"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); const grants: any[] = []; let cursor: string | undefined; - do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => !grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000))); cursor = page.cursor; } while (cursor); + do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => (grant.metadata as any)?.tenantId === this.auth.tenantId && (!grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000)))); cursor = page.cursor; } while (cursor); const clients = await Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await this.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const)); const byId = new Map(clients); return publicValue(z.array(authorizedClient), grants.map(grant => ({ grantId: grant.id, clientId: grant.clientId, clientName: byId.get(grant.clientId)?.clientName ?? grant.clientId, scopes: normalizeScopes(grant.scope), authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }))); } - async revokeAuthorizedClient(clientId: string) { await this.authorizeOwnerSession("jobs:write"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); const grants: any[] = []; let cursor: string | undefined; do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => grant.clientId === clientId)); cursor = page.cursor; } while (cursor); await Promise.all(grants.map(grant => this.env.OAUTH_PROVIDER!.revokeGrant(grant.id, this.auth.userId))); return { revoked: grants.length }; } + async revokeOAuthAuthorization(grantId: string) { + await this.authorizeOwnerSession("jobs:write"); + if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503,"operation_failed","OAuth management unavailable"); + let cursor: string | undefined, found = false; + do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId,{limit:100,cursor}); found ||= page.items.some(grant=>grant.id===grantId && (grant.metadata as any)?.tenantId===this.auth.tenantId); cursor=page.cursor; } while(cursor && !found); + if(!found) throw new ServiceError(404,"not_found","Authorization not found"); + await databaseFor(this.env).pool.query("INSERT INTO app.agent_identities(tenant_id,kind,subject,user_id,session_version,revoked_at) VALUES($1,'oauth',$2,$3,$4,now()) ON CONFLICT(tenant_id,kind,subject) DO UPDATE SET revoked_at=now()",[this.auth.tenantId,grantId,this.auth.userId,this.auth.sessionVersion]); + await this.env.OAUTH_PROVIDER.revokeGrant(grantId,this.auth.userId); + return {revoked:1}; + } + async revokeAuthorizedClient(clientId: string) { + await this.authorizeOwnerSession("jobs:write"); + if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503,"operation_failed","OAuth management unavailable"); + const grants: any[]=[]; let cursor: string | undefined; + do { const page=await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId,{limit:100,cursor});grants.push(...page.items.filter(grant=>grant.clientId===clientId && (grant.metadata as any)?.tenantId===this.auth.tenantId));cursor=page.cursor; } while(cursor); + for (const grant of grants) await this.revokeOAuthAuthorization(grant.id); + return {revoked:grants.length}; + } async listAccessTokens() { await this.authorizeOwnerSession("jobs:read"); return publicValue(z.array(accessToken), (await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).list()).map(token => ({ ...token, created_at: new Date(token.created_at).toISOString(), expires_at: new Date(token.expires_at).toISOString(), last_used_at: token.last_used_at ? new Date(token.last_used_at).toISOString() : null, revoked_at: token.revoked_at ? new Date(token.revoked_at).toISOString() : null, scopes: normalizeScopes(token.scopes) }))); } async createAccessToken(input: any) { await this.authorizeOwnerSession("jobs:write"); const name = typeof input?.name === "string" ? input.name.trim() : "", requested: string[] = Array.isArray(input?.scopes) ? [...new Set(input.scopes.filter((scope: unknown): scope is string => typeof scope === "string"))] : [], legacy = new Set(["flows:read", "flows:write"]), scopes = normalizeScopes(requested), expiryDays = Number(input?.expiryDays); if (!name || name.length > 100 || !requested.length || requested.some(scope => !ACCESS_SCOPES.includes(scope as any) && !legacy.has(scope)) || !scopes.length || ![7, 30, 90].includes(expiryDays)) throw new ServiceError(400, "invalid_request", "A name, supported scopes, and expiryDays of 7, 30, or 90 are required."); const token = issueAccessToken(this.auth.tenantId), expiresAt = new Date(Date.now() + expiryDays * 86_400_000).toISOString(); const metadata = await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).create({ name, scopes, expiresAt, digest: await accessTokenDigest(token), userId: this.auth.userId, sessionVersion: this.auth.sessionVersion }); if (!metadata) throw new ServiceError(401, "invalid_token", "The owner session is no longer active."); return publicValue(createdAccessToken, JSON.parse(JSON.stringify({ ...metadata, token }))); } async revokeAccessToken(id: string) { await this.authorizeOwnerSession("jobs:write"); if (!await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).revoke(id)) throw new ServiceError(404, "not_found", "Access token not found"); return { revoked: true }; } diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index 655ce287..37bd2468 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -1,3 +1,4 @@ +import { cleanupAgentResponses } from "../agent-api"; import { validateTraceSources, type TraceSource, type TraceSources } from "../trace-source"; import { AmpBackend, type AmpConnection } from "../amp-backend"; import { issueArtifactUploadGrant } from "../artifact-upload"; @@ -52,6 +53,7 @@ export class RunScheduler { const retention = new RunRetentionRepository(this.database); await this.reconcileProviderCleanup(); await this.runRetentionMaintenance(retention); + await cleanupAgentResponses(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 a66e0a6c..8e1f2cf6 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -47,6 +47,17 @@ export const integrationCollections = app.table("integration_collections", { export const integrationRecords = app.table("integration_records", { tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), id: uuid("id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), revision: bigint("revision", { mode: "number" }).notNull(), encryptedPayload: text("encrypted_payload"), deletedAt: timestamp("deleted_at", { withTimezone: true, mode: "date" }), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), uniqueIndex("integration_records_active_name").on(t.tenantId, t.kind, sql`lower(${t.name})`).where(sql`${t.deletedAt} is null`), index("integration_records_collection_order").on(t.tenantId, t.revision, t.id), check("integration_records_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_records_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_records_payload_check", sql`(${t.deletedAt} IS NULL AND ${t.encryptedPayload} IS NOT NULL) OR (${t.deletedAt} IS NOT NULL AND ${t.encryptedPayload} IS NULL)`)]); +export const agentIntegrations = app.table("agent_integrations", { + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, {onDelete:"cascade"}), id: uuid("id").notNull().defaultRandom(), + kind: text("kind").$type<"bearer"|"github"|"linear"|"model">().notNull(), credentialId: text("credential_id").notNull(), name:text("name").notNull(), description:text("description"), available:boolean("available").notNull(), + 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(), +},t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.subject)]); +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)]); export const integrationChanges = app.table("integration_changes", { tenantId: uuid("tenant_id").notNull().references(() => integrationCollections.tenantId, { onDelete: "cascade" }), revision: bigint("revision", { mode: "number" }).notNull(), id: uuid("id").notNull(), idempotencyKey: uuid("idempotency_key").notNull(), operation: text("operation").$type<"upsert" | "delete">().notNull(), recordId: uuid("record_id").notNull(), kind: text("kind").$type<"bearer" | "model">().notNull(), name: text("name").notNull(), origin: text("origin"), description: text("description"), encryptedPayload: text("encrypted_payload"), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.revision] }), unique().on(t.tenantId, t.idempotencyKey), index("integration_changes_page").on(t.tenantId, t.revision), check("integration_changes_operation_check", sql`${t.operation} IN ('upsert','delete')`), check("integration_changes_kind_check", sql`${t.kind} IN ('bearer','model')`), check("integration_changes_origin_check", sql`(${t.kind} = 'bearer' AND ${t.origin} IS NOT NULL) OR (${t.kind} = 'model' AND ${t.origin} IS NULL)`), check("integration_changes_payload_check", sql`(${t.operation} = 'upsert' AND ${t.encryptedPayload} IS NOT NULL) OR (${t.operation} = 'delete' AND ${t.encryptedPayload} IS NULL)`)]); @@ -155,7 +166,7 @@ export const runRelations = relations(runs, ({ one, many }) => ({ export const databaseSchema = { schemaMigrations, tenants, oauthConnections, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, accessTokens, - connections, integrationCollections, integrationRecords, integrationChanges, modelDeviceAuthorizations, linearWorkspaces, githubInstallations, githubSetupStates, projects, jobs, vmImageVerifications, skills, jobSkills, triggers, webhookConditionsCutover, invocations, manualInvocationPermissions, jobRuns, runAuthorizations, runs, runArtifacts, runRetentionCleanup, + 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, 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 bd949042..4fa682f0 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,9 +1,12 @@ +import { Hono } from "hono"; +import { AgentApiError } from "./agent-api"; +import { requestApiInput, readApiResponseInput } 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 } from "@modelcontextprotocol/server"; +import { createMcpHandler, McpServer, type ServerContext } from "@modelcontextprotocol/server"; import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; import { ApiService, ServiceError } from "./flow-service"; @@ -13,7 +16,8 @@ import { executeAuth, validBrowserOrigin } from "./auth-api"; import { matchApiOperation } from "./api-contract"; import { normalizeScopes } from "./access-tokens"; -function errorResponse(error: unknown): Response { +function errorResponse(error: unknown, origin?: string): Response { + if (error instanceof AgentApiError) return Response.json({error: {code: error.code, message: error.message}}, {status: error.status, headers: error.code === "insufficient_scope" ? {"WWW-Authenticate": `Bearer error="insufficient_scope", scope="${error.scope}", resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`} : undefined}); if (error instanceof ExeIntegrationError) return Response.json({ error: { code: "invalid_request", message: error.message } }, { status: 400 }); if (error instanceof URIError) return Response.json({ error: { code: "invalid_request", message: "Invalid path encoding" } }, { status: 400 }); if (error instanceof InvocationError && error.code === "queue_full") return Response.json({ error: { code: error.code, message: error.message } }, { status: 409 }); @@ -59,7 +63,24 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP const url = new URL(request.url), path = url.pathname; if (path === "/mcp") { if (!auth) throw new ServiceError(401, "invalid_token", "Unauthorized"); - return mcp(request, new ApiService(env, auth), env, ctx); + 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({ + transform(chunk,controller) { mcpBytes+=chunk.byteLength; if(mcpBytes>45_000_000) throw new ServiceError(413,"request_too_large","MCP request exceeds the proxy limit."); controller.enqueue(chunk); } + })); + 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); } const matched = matchApiOperation(request.method, path); if (!matched) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); @@ -94,19 +115,32 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (route.authOperation) return timed(await executeAuth(route.authOperation, request, env, body as Record)); service = new ApiService(env, auth!, ctx); const query = route.query?.parse(queryInput(url)); - const result = await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url }); + const result = await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url, signal: request.signal }); return timed(result instanceof Response ? result : Response.json(result, { status: route.status })); - } catch (error) { return timed(errorResponse(error)); } + } catch (error) { return timed(errorResponse(error, env.APP_ORIGIN)); } } const mcpServices = new WeakMap(); +const mcpBodies = 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) => Promise) => server.registerTool(name, { description, inputSchema: schema }, async (input: T) => { - try { return structured(await action(input)); } + 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); + } 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("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()); @@ -158,12 +192,15 @@ const mcpHandler = createMcpHandler(({ requestInfo }) => { return createMcpServer(service); }); -const mcpApps = new Map>(); +const mcpApps = new Map(); function mcpAppFor(hostname: string) { let app = mcpApps.get(hostname); if (!app) { - app = createMcpHonoApp({ host: hostname, allowedHosts: [hostname], allowedOrigins: [hostname] }); - app.all("/mcp", c => mcpHandler.fetch(c.req.raw, { parsedBody: (c as any).get("parsedBody") })); + const protocol = createMcpHonoApp({ host: hostname, allowedHosts: [hostname], allowedOrigins: [hostname] }); + protocol.all("/mcp", c => mcpHandler.fetch(c.req.raw, { parsedBody: (c as any).get("parsedBody") })); + app = new Hono(); + app.use("*",async(c,next)=> { if(mcpBodies.has(c.req.raw)) (c as any).set("parsedBody",mcpBodies.get(c.req.raw)); await next(); }); + app.route("/",protocol); mcpApps.set(hostname, app); } return app; @@ -177,16 +214,12 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi export class ProtectedApiHandler extends WorkerEntrypoint { async fetch(request: Request): Promise { let auth = this.ctx.props; - const isReportRequest = new URL(request.url).pathname.endsWith("/report-error") - || new URL(request.url).pathname === "/mcp" && await request.clone().json().then(body => (body as any)?.params?.name === "report_run_error").catch(() => false); - if (isReportRequest && auth.authMethod === "oauth" && (!auth.oauthGrantId || !auth.oauthClientId)) { + if (auth.authMethod === "oauth" || auth.authMethod === undefined) { const authorization = request.headers.get("Authorization"), credential = authorization?.startsWith("Bearer ") ? authorization.slice(7) : ""; - if (credential && this.env.OAUTH_PROVIDER) { - // The SDK validates the bearer before dispatch. Unwrap only for stable grant/client IDs; - // the credential itself is never logged, returned, or persisted. - const token = await this.env.OAUTH_PROVIDER.unwrapToken(credential); - if (token?.userId === auth.userId && token.grant?.clientId) auth = { ...auth, oauthGrantId: token.grantId, oauthClientId: token.grant.clientId }; - } + const token = credential && this.env.OAUTH_PROVIDER ? await this.env.OAUTH_PROVIDER.unwrapToken(credential) : null; + if (!token || token.userId !== auth.userId || !token.grant?.clientId) return Response.json({error:{code:"invalid_token",message:"Invalid OAuth authorization"}}, {status:401}); + // Props describe original consent. The presented token may be narrowed. + auth = {...auth, authMethod: "oauth", scopes: normalizeScopes(token.scope).filter(scope => normalizeScopes(auth.scopes).includes(scope)), oauthGrantId: token.grantId, oauthClientId: token.grant.clientId, oauthExpiresAt: token.expiresAt}; } return protectedApiFetch(request, this.env, auth, this.ctx); } diff --git a/packages/api/src/run-outbound-forwarder.ts b/packages/api/src/run-outbound-forwarder.ts index 655c042b..4ee0101f 100644 --- a/packages/api/src/run-outbound-forwarder.ts +++ b/packages/api/src/run-outbound-forwarder.ts @@ -14,7 +14,7 @@ function filteredHeaders(input: Headers, request: boolean): Headers { const connectionTokens = new Set((input.get("connection") ?? "").toLowerCase().split(",").map(s => s.trim())); input.forEach((value, key) => { const name = key.toLowerCase(); - if (hop.has(name) || connectionTokens.has(name) || (request && (privateHeaders.has(name) || name.startsWith("x-forwarded-") || name.startsWith("sec-") || name.startsWith("cf-") || name === "origin" || name === "referer")) || (!request && name === "set-cookie")) return; + if (hop.has(name) || connectionTokens.has(name) || (request && (privateHeaders.has(name) || name.startsWith("x-forwarded-") || name.startsWith("sec-") || name.startsWith("cf-") || name === "origin" || name === "referer")) || (!request && (name === "set-cookie" || name === "authorization" || name === "proxy-authorization"))) return; result.set(key, value); }); return result; diff --git a/packages/api/src/run-outbound-proxy.ts b/packages/api/src/run-outbound-proxy.ts index 532839dd..d103df9b 100644 --- a/packages/api/src/run-outbound-proxy.ts +++ b/packages/api/src/run-outbound-proxy.ts @@ -1,73 +1,37 @@ import type { Env } from "./types"; import { databaseFor } from "./postgres/database"; -import { CredentialRepository } from "./postgres/credential-repository"; -import { resolveRunProviderCredentials } from "./provider-credentials"; import { authenticateVendorRunRequest, RUN_IDENTITY_HEADER } from "./vendor-run-auth"; -import { forwardRunOutbound, type OutboundCredential } from "./run-outbound-forwarder"; -import { resolveManagedModelCredential } from "./managed-model-credentials"; -import { isPublicHttpsOrigin } from "./public-address"; +import { AgentApiService } from "./agent-api"; const unavailable = () => new Response("Run credential unavailable", {status: 403, headers: {"Cache-Control": "no-store"}}); -/** Raw outbound protocol boundary. The guest supplies a path, never an origin, - * upstream token, tenant, or credential outside its immutable run selection. */ +/** Preserve raw VM URLs and true streaming. Authentication never falls back to + * OAuth. Both transports reach the same identity/grant and forwarding service. */ export async function runOutboundProxyFetch(request: Request, env: Env): Promise { const url = new URL(request.url); const route = /^\/internal\/run-proxy\/([0-9a-f-]{36})(\/.*)$/.exec(url.pathname); if (!route || route[1] !== request.headers.get(RUN_IDENTITY_HEADER)) return unavailable(); const auth = await authenticateVendorRunRequest(request, env); if (!auth?.runId || auth.authMethod !== "vendor_identity") return unavailable(); - const database = databaseFor(env); - const active = async () => (await database.pool.query<{ execution_config: Record }>(`SELECT r.execution_config FROM app.runs r JOIN app.job_runs j ON j.tenant_id=r.tenant_id AND j.id=r.id - JOIN app.vendor_run_identity_bindings b ON b.tenant_id=j.tenant_id AND b.run_id=j.id - WHERE r.tenant_id=$1 AND r.id=$2 AND b.provider=$3 AND b.revoked_at IS NULL - AND r.state IN ('starting','running','blocked') AND j.state IN ('starting','running','blocked')`, [auth.tenantId, auth.runId, auth.runIdentityProvider])).rows[0]; - const revoked = async (kind: string, id: string) => Boolean((await 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", [auth.tenantId, auth.runId, kind, id])).rowCount); - const run = await active(); - if (!run) return unavailable(); - const config = run.execution_config, path = route[2]!; - let selected: OutboundCredential | null = null; + const path = route[2]!; + const bearer = /^\/integrations\/([0-9a-f-]{36})(\/.*)?$/.exec(path); + const github = /^\/providers\/github\/([1-9][0-9]*)(\/.*)?$/.exec(path); + const linear = /^\/providers\/linear(\/.*)?$/.exec(path); + const model = /^\/providers\/model\/v1(\/.*)?$/.exec(path); + const kind = bearer ? "bearer" : github ? "github" : linear ? "linear" : model ? "model" : null; + if (!kind) return unavailable(); try { - const bearer = /^\/integrations\/([0-9a-f-]{36})(\/.*)?$/.exec(path); - const github = /^\/providers\/github\/([1-9][0-9]*)(\/.*)?$/.exec(path); - const linear = /^\/providers\/linear(\/.*)?$/.exec(path); - const model = /^\/providers\/model\/v1(\/.*)?$/.exec(path); - if (bearer) { - if (!Array.isArray(config.portableIntegrationIds) || !config.portableIntegrationIds.includes(bearer[1]) || await revoked("bearer", bearer[1]!)) return unavailable(); - const credential = await new CredentialRepository(database, auth.tenantId, env.CREDENTIAL_ENCRYPTION_KEY).managedCredential(bearer[1]!, "bearer"); - if (!credential?.origin || !isPublicHttpsOrigin(credential.origin, env.APP_ORIGIN)) return unavailable(); - selected = {origin: credential.origin, path: `${bearer[2] ?? "/"}${url.search}`, credential: credential.payload}; - } else if (github) { - const installationId = Number(github[1]); - if (!Number.isSafeInteger(installationId) || !Array.isArray(config.githubInstallationIds) || !config.githubInstallationIds.includes(installationId) || await revoked("github", github[1]!)) return unavailable(); - const resolved = await resolveRunProviderCredentials({database, env, tenantId: auth.tenantId, githubInstallationIds: [installationId], linearSelected: false}); - const credential = resolved.githubInstallations[0]; - if (!credential?.available || !credential.accessToken) return unavailable(); - let suffix = github[2] ?? "/", origin = "https://api.github.com"; - const smart = /\/(?:info\/refs|git-upload-pack|git-receive-pack)$/.test(suffix); - if (smart) origin = "https://github.com"; - else if (suffix.startsWith("/raw/")) { origin = "https://raw.githubusercontent.com"; suffix = suffix.slice(4); } - else if (suffix.startsWith("/archive/")) { origin = "https://codeload.github.com"; suffix = suffix.slice(8); } - selected = {origin, path: `${suffix}${url.search}`, credential: credential.accessToken, authorization: smart ? "github-git-basic" : "bearer"}; - } else if (linear) { - if (config.linearConnectionId !== "linear" || await revoked("linear", "linear")) return unavailable(); - const resolved = await resolveRunProviderCredentials({database, env, tenantId: auth.tenantId, githubInstallationIds: [], linearSelected: true}); - if (!resolved.linearConnection?.available || !resolved.linearConnection.accessToken) return unavailable(); - selected = {origin: "https://api.linear.app", path: `${linear[1] ?? "/graphql"}${url.search}`, credential: resolved.linearConnection.accessToken}; - } else if (model) { - if (config.modelAccess !== "portable" || typeof config.modelAccountId !== "string" || await revoked("model", config.modelAccountId)) return unavailable(); - const credential = await resolveManagedModelCredential({database, env, tenantId: auth.tenantId, accountId: config.modelAccountId}); - if (!credential) return unavailable(); - const suffix = model[1] ?? "/"; - const target = new URL(`${credential.origin}${credential.prefix}${suffix}`); - if (!target.pathname.startsWith(`${credential.prefix}/`)) return unavailable(); - selected = {origin: credential.origin, path: `${target.pathname}${url.search}`, credential: credential.accessToken, - ...(credential.accountId ? {headers: {"chatgpt-account-id": credential.accountId}} : {})}; + let id = bearer?.[1] ?? github?.[1] ?? "linear"; + if (model) { + const row = (await databaseFor(env).pool.query<{execution_config: {modelAccountId?: string}}>("SELECT execution_config FROM app.runs WHERE tenant_id=$1 AND id=$2", [auth.tenantId,auth.runId])).rows[0]; + id = row?.execution_config.modelAccountId ?? ""; } - if (!selected || !await active()) return unavailable(); - return await forwardRunOutbound(request, selected); - } catch { + const row = (await databaseFor(env).pool.query<{id: string}>("SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND kind=$2 AND credential_id=$3", [auth.tenantId,kind,id])).rows[0]; + if (!row) return unavailable(); + const suffix = bearer?.[2] ?? github?.[2] ?? linear?.[1] ?? model?.[1] ?? (linear ? "/graphql" : "/"); + return await new AgentApiService(env,auth).forward(row.id, suffix+url.search, request); + } catch (error) { + if (error && typeof error === "object" && "status" in error && (error.status === 401 || error.status === 403)) return unavailable(); return new Response("Run outbound request unavailable", {status: 502, headers: {"Cache-Control": "no-store"}}); } } diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 2bec0dd7..c9e90c30 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -53,6 +53,8 @@ export type OAuthProps = { /** Stable identifier for the OAuth authorization grant; never a bearer token. */ oauthGrantId?: string; oauthClientId?: string; + /** Expiry of the presented, verified OAuth access token. */ + oauthExpiresAt?: number; authMethod?: "session" | "oauth" | "access_token" | "vendor_identity"; }; diff --git a/packages/api/test/agent-api.postgres.test.ts b/packages/api/test/agent-api.postgres.test.ts new file mode 100644 index 00000000..58401797 --- /dev/null +++ b/packages/api/test/agent-api.postgres.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { CredentialRepository } from "../src/postgres/credential-repository"; +import { AgentApiService, cleanupAgentResponses, integrationConsentLabels } from "../src/agent-api"; +import { normalizeScopes } from "../src/access-tokens"; +import { requestApiInput } from "../src/agent-api-contracts"; +vi.mock("cloudflare:workers",()=>({WorkerEntrypoint:class {},DurableObject:class {}})); +vi.mock("@cloudflare/workers-oauth-provider",()=>({OAuthProvider:class {},AuthorizationError:class extends Error {},getOAuthApi:vi.fn()})); +const url=process.env.AUTH_TEST_DATABASE_URL; +describe.skipIf(!url)("persisted agent grants and cleanup",()=>{ + it("retains a stable reference across rotation, but disconnect and disable never revive approvals",async()=>{ + const f=await loadingFixture(url!); + try { + const repository=new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY),id=crypto.randomUUID(); + const write=(operation:"upsert"|"delete",revision:number)=>repository.write({id,kind:"bearer",name:"API",description:"Use this API",origin:"https://api.example.com",expectedRevision:revision,idempotencyKey:crypto.randomUUID(),operation,...(operation==="upsert"?{managedSecret:"private"}:{})}); + await write("upsert",0); + const row=(await f.db.pool.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND credential_id=$2",[f.tenantId,id])).rows[0]; + const scope=`integration:${row.id}:${row.epoch}`; + const auth={...f.auth,authMethod:"oauth" as const,oauthGrantId:"grant",oauthClientId:"client",oauthExpiresAt:Date.now()/1000+3600,scopes:[scope]}; + const service=new AgentApiService(f.env,auth); + expect((await service.authorize(row.id)).identity.kind).toBe("oauth"); + await write("upsert",1);expect((await service.authorize(row.id)).integration.epoch).toBe(row.epoch); + await write("delete",2);await expect(service.authorize(row.id)).rejects.toMatchObject({status:403}); + await write("upsert",3);await expect(service.authorize(row.id)).rejects.toMatchObject({code:"insufficient_scope"}); + await expect(integrationConsentLabels(f.env,f.tenantId,[scope])).rejects.toMatchObject({status:403}); + await f.db.pool.query("UPDATE app.agent_integrations SET policy='baseline' WHERE tenant_id=$1 AND id=$2",[f.tenantId,row.id]); + await service.authorize(row.id); + await f.db.pool.query("UPDATE app.agent_integrations SET policy='disabled' WHERE tenant_id=$1 AND id=$2",[f.tenantId,row.id]); + await expect(service.authorize(row.id)).rejects.toMatchObject({status:403}); + await f.db.pool.query("UPDATE app.agent_integrations SET policy='requestable' WHERE tenant_id=$1 AND id=$2",[f.tenantId,row.id]); + await expect(service.authorize(row.id)).rejects.toMatchObject({code:"insufficient_scope"}); + await f.db.pool.query("UPDATE app.agent_identities SET revoked_at=now() WHERE tenant_id=$1",[f.tenantId]); + await expect(service.reflection()).rejects.toMatchObject({status:401}); + } finally {await f.cleanup();} + }); + it("cleans expired receipts including interrupted uploads, and retries failed object deletion",async()=>{ + const f=await loadingFixture(url!); + try { + const identity=await new AgentApiService(f.env,{...f.auth,authMethod:"oauth",oauthGrantId:"grant",oauthClientId:"client",oauthExpiresAt:Date.now()/1000+3600}).identity(); + const integration=crypto.randomUUID(); + await f.db.pool.query("INSERT INTO app.agent_integrations(tenant_id,id,kind,credential_id,name,available) VALUES($1,$2,'linear','linear','Linear',true)",[f.tenantId,integration]); + const expired=crypto.randomUUID(),pending=crypto.randomUUID(),live=crypto.randomUUID(); + for(const [id,age,size] of [[expired,-1,10],[pending,-1,null],[live,1,10]]) await f.db.pool.query("INSERT INTO app.agent_proxy_responses(tenant_id,id,identity_id,integration_id,integration_epoch,object_key,size,expires_at) VALUES($1,$2,$3,$4,1,$2::uuid::text,$5,now()+$6*interval '1 day')",[f.tenantId,id,identity.id,integration,size,age]); + const deleted:string[]=[];let failed=true; + f.env.RUN_ARTIFACTS={list:vi.fn(async({prefix}:{prefix:string})=>({objects:[{key:prefix+'0'}],truncated:false})),delete:vi.fn(async(keys:string[])=>{if(failed)throw new Error("storage unavailable");deleted.push(...keys);})} as any; + await expect(cleanupAgentResponses(f.env)).rejects.toThrow("storage unavailable"); + expect((await f.db.pool.query("SELECT * FROM app.agent_proxy_responses")).rowCount).toBe(3); + failed=false;await cleanupAgentResponses(f.env); + expect(deleted.sort()).toEqual([expired+'/0',pending+'/0'].sort()); + expect((await f.db.pool.query("SELECT id FROM app.agent_proxy_responses")).rows).toEqual([{id:live}]); + } finally {await f.cleanup();} + }); +}); +it("only normalizes well-formed epoch integration scopes and rejects caller origins and invalid requests",()=>{ + const id=crypto.randomUUID(),scope=`integration:${id}:1`; + expect(normalizeScopes([scope,scope,`integration:${id}:0`,`integration:${id}:01`,`integration:${id}:1 x`,`integration:foreign:1`])).toEqual([scope]); + for(const path of ['https://evil.com','//evil.com','/a\\b','/a\n','/a#fragment']) expect(requestApiInput.safeParse({integration:id,method:"GET",path}).success).toBe(false); + expect(requestApiInput.safeParse({integration:id,method:"CONNECT",path:"/"}).success).toBe(false); + expect(requestApiInput.safeParse({integration:id,method:"GET",path:"/",headers:{x:"x\r\ninjected:true"}}).success).toBe(false); +}); diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index f77019fd..01beb9a4 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -35,23 +35,16 @@ function request( body?: unknown, options: { raw?: string; mediaType?: string; auth?: OAuthProps } = {}, ) { + const identity=options.auth ?? auth; const worker = new ProtectedApiHandler( - { props: options.auth ?? auth } as ExecutionContext, - { APP_ORIGIN: "https://example.com" } as Env, + { props: identity } as ExecutionContext, + { APP_ORIGIN: "https://example.com", ...(identity.authMethod === "oauth" ? {OAUTH_PROVIDER:{unwrapToken:async()=>({userId:identity.userId,grantId:"boundary-grant",scope:identity.scopes,expiresAt:Math.floor(Date.now()/1000)+3600,grant:{clientId:"boundary-client"}})}} : {}) } as unknown as Env, ); return worker.fetch( new Request("https://example.com" + path, { method, - headers: { Origin: "https://example.com" }, - ...(body !== undefined || options.raw !== undefined - ? { - body: options.raw ?? JSON.stringify(body), - headers: { - Origin: "https://example.com", - "Content-Type": options.mediaType ?? "application/json", - }, - } - : {}), + headers: { Origin: "https://example.com", ...(identity.authMethod === "oauth" ? {Authorization:"Bearer validated-boundary-fixture"} : {}), ...(body !== undefined || options.raw !== undefined ? {"Content-Type":options.mediaType ?? "application/json"} : {}) }, + ...(body !== undefined || options.raw !== undefined ? {body: options.raw ?? JSON.stringify(body)} : {}), }), ); } diff --git a/packages/api/test/fixtures/agent-api-runtime-worker.ts b/packages/api/test/fixtures/agent-api-runtime-worker.ts new file mode 100644 index 00000000..21b14ee5 --- /dev/null +++ b/packages/api/test/fixtures/agent-api-runtime-worker.ts @@ -0,0 +1,21 @@ +import { WorkerEntrypoint } from "cloudflare:workers"; +import worker from "../../src/worker"; +import { cleanupAgentResponses } from "../../src/agent-api"; +import type { Env } from "../../src/types"; +export { AlarmCoordinator } from "../../src/worker"; + +// Miniflare's Node fetch bridge replaces Host with its private listener address. +// The HTTPS fixture verifies the external host; restore it before the production +// Hono boundary. This wrapper is bundled only by agent-api-runtime.test.mjs. +export default { + fetch(request: Request, env: Env, ctx: ExecutionContext) { + const headers = new Headers(request.headers); + headers.set("Host",new URL(env.APP_ORIGIN).host); + return worker.fetch(new Request(request,{headers}),env,ctx); + }, +}; +// 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"); } +} diff --git a/packages/api/test/report-run-error-boundary.test.ts b/packages/api/test/report-run-error-boundary.test.ts index b3f41418..6bf78f55 100644 --- a/packages/api/test/report-run-error-boundary.test.ts +++ b/packages/api/test/report-run-error-boundary.test.ts @@ -108,7 +108,7 @@ describe("report authenticated provenance and sanitization", () => { }); it("uses the validated OAuth token summary for legacy grant reporter identity", async () => { - const credential = "never-persist-this-token-value", unwrapToken = vi.fn().mockResolvedValue({ userId: "owner", grantId: "real-grant-id", grant: { clientId: "real-client-id" } }); + const credential = "never-persist-this-token-value", unwrapToken = vi.fn().mockResolvedValue({ userId: "owner", grantId: "real-grant-id", scope: ["runs:write"], expiresAt: Math.floor(Date.now()/1000)+3600, grant: { clientId: "real-client-id" } }); const report = vi.spyOn(ApiService.prototype, "reportRunError").mockImplementation(async function(this: any) { expect(this.auth).toMatchObject({ oauthGrantId: "real-grant-id", oauthClientId: "real-client-id" }); return { reported: true, reason: "safe", retry: false }; diff --git a/packages/api/test/run-outbound-forwarder.test.ts b/packages/api/test/run-outbound-forwarder.test.ts index 93893120..09acefe9 100644 --- a/packages/api/test/run-outbound-forwarder.test.ts +++ b/packages/api/test/run-outbound-forwarder.test.ts @@ -52,6 +52,19 @@ describe("backend streaming outbound protocol", () => { await expect(forwardRunOutbound(new Request("https://factorize.test/", {method: "POST", body: "oversized"}), credential, {requestBytes: 2, fetcher: async (_input, init) => new Response(await new Response(init!.body).text())})).rejects.toThrow("limit"); }); + it("propagates request cancellation and enforces the upstream deadline", async () => { + const selected={origin:"https://api.example.com",path:"/",credential:"secret"}; + const fetcher: typeof fetch = async (_input,init) => new Promise((_resolve,reject)=> { + const signal=init!.signal!; + if(signal.aborted) reject(signal.reason); + else signal.addEventListener("abort",()=>reject(signal.reason),{once:true}); + }); + await expect(forwardRunOutbound(new Request("https://factorize.test/"),selected,{fetcher,timeoutMs:5})).rejects.toMatchObject({name:"TimeoutError"}); + const abort=new AbortController(); + const pending=forwardRunOutbound(new Request("https://factorize.test/",{signal:abort.signal}),selected,{fetcher,timeoutMs:1000}); + abort.abort();await expect(pending).rejects.toMatchObject({name:"AbortError"}); + }); + it.each(["127.0.0.1", "10.1.2.3", "169.254.169.254", "192.168.0.1", "100.64.0.1", "::1", "::ffff:127.0.0.1", "fc00::1", "2001:db8::1"])("rejects non-public address %s", address => { expect(isPublicAddress(address)).toBe(false); }); diff --git a/packages/app/src/features/auth/consent.tsx b/packages/app/src/features/auth/consent.tsx index 5b0e945d..f33341c7 100644 --- a/packages/app/src/features/auth/consent.tsx +++ b/packages/app/src/features/auth/consent.tsx @@ -9,6 +9,6 @@ export function ConsentScreen() { const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Load the authorization request first."); const { data, error } = await api.POST("/api/v1/oauth/consent/decision", { body: { request: preview.data.request, signature: preview.data.signature, decision: value, scopes: selected ?? preview.data.scopes } }); if (!data || error) throw new Error(messageOf(error)); location.assign(data.redirectTo); } }); const scopes = selected ?? preview.data?.scopes ?? []; return

Authorize {preview.data?.clientName ?? "a client"}

{preview.isPending &&

Validating authorization request…

}{preview.error &&

{preview.error.message}

} - {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Job writes may cause future schedule/webhook/lifecycle execution, and deleting a job may remove run history and artifacts. Request expires {preview.data.expiresAt}.

Permissions{preview.data.scopes.map(scope => )}
}{decision.error &&

{decision.error.message}

} + {preview.data && <>

This client requests workspace access. Permissions are independent; write does not imply read. Job writes may cause future schedule/webhook/lifecycle execution, and deleting a job may remove run history and artifacts. Request expires {preview.data.expiresAt}.

Permissions{preview.data.scopes.map(scope => )}
}{decision.error &&

{decision.error.message}

}
; } diff --git a/packages/app/src/features/auth/device.tsx b/packages/app/src/features/auth/device.tsx index cfdb2073..f884a127 100644 --- a/packages/app/src/features/auth/device.tsx +++ b/packages/app/src/features/auth/device.tsx @@ -10,7 +10,7 @@ export function DeviceScreen() { const decision = useMutation({ retry: false, mutationFn: async (value: "allow" | "deny") => { if (!preview.data) throw new Error("Review the device request first."); const { data, error } = await api.POST("/api/v1/oauth/device/decision", { body: { userCode: search.user_code, signature: preview.data!.signature, decision: value } }); if (!data || error) throw new Error(messageOf(error)); return data; } }); return

Connect a device

Enter the code displayed by your MCP client. Only approve a request you started. If it expires, request a new code in that client.

{decision.data ?

{decision.data.status === "approved" ? "Device connected" : "Authorization denied"}. You can close this window.

: <>
{ e.preventDefault(); decision.reset(); void navigate({ to: "/device", search: { user_code: code, connection: undefined } }); }}>
- {preview.isFetching &&

Validating device code…

}{preview.data && <>

Authorize {preview.data.clientName}

Permissions: {preview.data.scopes.join(", ")} · Expires {preview.data.expiresAt}

} + {preview.isFetching &&

Validating device code…

}{preview.data && <>

Authorize {preview.data.clientName}

Permissions: {preview.data.scopes.map(scope => { const label = preview.data.integrationLabels?.find(label=>label.scope===scope); return label ? `${label.name}${label.description ? ` — ${label.description}` : ""}` : scope; }).join(", ")} · Expires {preview.data.expiresAt}

} {[preview.error, decision.error].filter(Boolean).map((error, i) =>

{error?.message}

)}}
; } diff --git a/packages/app/src/features/settings/api-policies.tsx b/packages/app/src/features/settings/api-policies.tsx new file mode 100644 index 00000000..5ff9a841 --- /dev/null +++ b/packages/app/src/features/settings/api-policies.tsx @@ -0,0 +1,21 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Card, Label } from "../../shared/ui"; +import { messageOf } from "../auth/session"; + +export function ApiPolicies() { + const cache = useQueryClient(); + const policies = useQuery({queryKey:["settings","api-policies"],queryFn:async ({signal}) => { + const {data,error} = await api.GET("/api/v1/integration-api-policies",{signal}); + if (!data || error) throw new Error(messageOf(error)); return data; + }}); + const change = useMutation({retry:false,mutationFn:async (input:{id:string;revision:number;policy:"baseline"|"requestable"|"disabled"}) => { + const {data,error} = await api.PUT("/api/v1/integration-api-policies/{integrationId}",{params:{path:{integrationId:input.id}},body:{policy:input.policy,expectedRevision:input.revision}}); + if (!data || error) throw new Error(messageOf(error)); return data; + },onSuccess:data=>cache.setQueryData(["settings","api-policies"],data),onSettled:()=>cache.invalidateQueries({queryKey:["settings","api-policies"]})}); + return

MCP API access

Baseline APIs are available immediately to every connected MCP client. Requestable APIs require separate approval for each connection. Disabling access or disconnecting an integration invalidates its approvals; re-enabling requires fresh consent. Runs keep their own selected connections.

+ {policies.isPending &&

Loading API policies…

} + {[policies.error,change.error].filter(Boolean).map((error,i)=>

{error?.message}

)} + {policies.data?.integrations.map(row=>{row.description &&

{row.description}

}
)} +
; +} diff --git a/packages/app/src/features/settings/authorized-clients.tsx b/packages/app/src/features/settings/authorized-clients.tsx index 1fee1cc6..8cb9ff9b 100644 --- a/packages/app/src/features/settings/authorized-clients.tsx +++ b/packages/app/src/features/settings/authorized-clients.tsx @@ -6,8 +6,8 @@ import { SettingsLayout } from "./navigation"; import { messageOf } from "../auth/session"; export function AuthorizedClients() { const cache = useQueryClient(), clients = useQuery(clientsQuery); - const revoke = useMutation({ retry: false, mutationFn: async (clientId: string) => { const { error } = await api.DELETE("/api/v1/access/authorized-clients/{clientId}", { params: { path: { clientId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); + const revoke = useMutation({ retry: false, mutationFn: async (grantId: string) => { const { error } = await api.DELETE("/api/v1/access/authorizations/{grantId}", { params: { path: { grantId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: () => cache.invalidateQueries({ queryKey: clientsQuery.queryKey }) }); return {clients.isPending &&

Loading clients…

}{clients.error &&

{clients.error.message}

}{revoke.error &&

{revoke.error.message}

}{clients.data?.length === 0 &&

No authorized clients.

} -
    {clients.data?.map(client =>
  • {client.clientName}

    {client.scopes.join(", ")} · Authorized {client.authorizationDate} · Expires {client.expiresAt ?? "No expiry"}

  • )}
+
    {clients.data?.map(client =>
  • {client.clientName}

    {client.scopes.join(", ")} · Authorized {client.authorizationDate} · Expires {client.expiresAt ?? "No expiry"}

  • )}
; } diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index 692c388a..cca5401c 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -1,3 +1,4 @@ +import { ApiPolicies } from "./api-policies"; import { useState, type ReactNode } from "react"; import { IntegrationIcon } from "./icon"; import { Disclosure, Summary, Button, Card, Badge } from "../../shared/ui"; @@ -54,7 +55,7 @@ export function Integrations() { {status.data?.cloudflareTail.installations.map(c =>

Cloudflare Tail · {c.name}

Referenced by {c.referencedJobCount} {c.referencedJobCount === 1 ? "job" : "jobs"}

Connected{buttons("cloudflareTail", c.integrationId)}
{manage(`tail:${c.integrationId}`, )}
)} } - +

Available integrations

Connect a provider to add it to your workspace. Connected providers remain available for additional connections.

setOpenSetup(open ? "linear-new" : null)}>{status.data?.linear ? "Add another Linear account" : "Connect Linear"} setOpenSetup(open ? "clickup-new" : null)}>{status.data?.clickup ? "Add another ClickUp workspace" : "Connect ClickUp"} diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index b512553b..964e5b8d 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -41,3 +41,71 @@ exe.dev and Fly guests use a localhost helper that authenticates to Factorize with fresh vendor signatures bound to that exact VM/run. Selected upstream credentials stay in the backend. Canceling or terminating a run removes its API and outbound access, independently of external VM deletion retries. + +## MCP API proxy access + +External MCP clients continue to authenticate with OAuth; execution VMs continue +to use vendor OIDC. These identities have separate grants. Run selections never +inherit an external client's approvals. + +In Settings → Integrations → MCP API access, choose a policy for each custom +bearer integration, GitHub installation, Linear connection, and model account: + +* **Baseline:** immediately available to all active MCP authorizations. Removing + baseline access immediately removes access derived from that policy. +* **Requestable:** visible in reflection, but each separately authorized + connection must obtain consent before use. +* **Disabled:** unavailable for requests and consent. Disabling or disconnecting + permanently invalidates existing integration approvals. Re-enabling as + requestable requires fresh consent. Replacing a credential without deleting + its integration preserves approvals. + +Start OAuth with only the Factorize resource scopes your client needs; do not +request the complete integration catalog. `get_api_reflection` returns the +current agent identity, effective Factorize scopes, integration references, +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 +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, +bounded by the credential's upstream permissions. Redirects are rejected. + +Missing requestable access produces an HTTP 403 response with a +`WWW-Authenticate: Bearer` challenge containing `error="insufficient_scope"`, +`scope`, and `resource_metadata`. Reauthorize with the union of your currently +needed scopes and the challenged scope, approve the named integration in the +browser, exchange the new code, then retry. The new authorization is independent +of other connections, including copies of the same client. Refresh retains the +authorization identity; a narrowed token uses only its presented scopes. +Integration scopes have the form `integration:{reference UUID}:{revocation epoch}`; +use the value returned by reflection rather than constructing or caching it. + +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. + +Call `read_api_response` 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 +clients settings revoke individual connections; the existing client-wide revoke +endpoint remains available for compatibility. + +The scheduler maintenance heartbeat removes expired response objects and their +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`. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index d0793e3f..a7bfe2a3 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -384,6 +384,74 @@ with fresh vendor signatures bound to that exact VM/run. Selected upstream credentials stay in the backend. Canceling or terminating a run removes its API and outbound access, independently of external VM deletion retries. +## MCP API proxy access + +External MCP clients continue to authenticate with OAuth; execution VMs continue +to use vendor OIDC. These identities have separate grants. Run selections never +inherit an external client's approvals. + +In Settings → Integrations → MCP API access, choose a policy for each custom +bearer integration, GitHub installation, Linear connection, and model account: + +* **Baseline:** immediately available to all active MCP authorizations. Removing + baseline access immediately removes access derived from that policy. +* **Requestable:** visible in reflection, but each separately authorized + connection must obtain consent before use. +* **Disabled:** unavailable for requests and consent. Disabling or disconnecting + permanently invalidates existing integration approvals. Re-enabling as + requestable requires fresh consent. Replacing a credential without deleting + its integration preserves approvals. + +Start OAuth with only the Factorize resource scopes your client needs; do not +request the complete integration catalog. `get_api_reflection` returns the +current agent identity, effective Factorize scopes, integration references, +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 +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, +bounded by the credential's upstream permissions. Redirects are rejected. + +Missing requestable access produces an HTTP 403 response with a +`WWW-Authenticate: Bearer` challenge containing `error="insufficient_scope"`, +`scope`, and `resource_metadata`. Reauthorize with the union of your currently +needed scopes and the challenged scope, approve the named integration in the +browser, exchange the new code, then retry. The new authorization is independent +of other connections, including copies of the same client. Refresh retains the +authorization identity; a narrowed token uses only its presented scopes. +Integration scopes have the form `integration:{reference UUID}:{revocation epoch}`; +use the value returned by reflection rather than constructing or caching it. + +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. + +Call `read_api_response` 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 +clients settings revoke individual connections; the existing client-wide revoke +endpoint remains available for compatibility. + +The scheduler maintenance heartbeat removes expired response objects and their +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`. + ## Trigger configuration Source: https://docs.factorize.sh/integrations/triggers @@ -534,6 +602,9 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `get_run_diagnostics` | runs:read | Required string `runId` | | `report_run_error` | runs:write | Required `runId` and `reason`; records an error without stopping execution | | `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `get_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. | | `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 | diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 9a5188f7..e4e29e01 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -34,6 +34,9 @@ The required scope inventory below is authoritative. Legacy `flows:*` and `runs: | `get_run_diagnostics` | runs:read | Required string `runId` | | `report_run_error` | runs:write | Required `runId` and `reason`; records an error without stopping execution | | `invoke_job` | runs:invoke | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `get_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. | | `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 | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 7fb18306..61e68c27 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -3674,6 +3674,24 @@ paths: type: string signature: type: string + integrationLabels: + type: array + items: + type: object + properties: + scope: + type: string + name: + type: string + description: + type: + - string + - "null" + required: + - scope + - name + - description + additionalProperties: false required: - userCode - clientName @@ -3814,6 +3832,24 @@ paths: type: string expiresAt: type: string + integrationLabels: + type: array + items: + type: object + properties: + scope: + type: string + name: + type: string + description: + type: + - string + - "null" + required: + - scope + - name + - description + additionalProperties: false required: - clientName - scopes @@ -6296,6 +6332,60 @@ paths: schema: type: string minLength: 1 + /api/v1/access/authorizations/{grantId}: + delete: + summary: Revoke one isolated OAuth connection + description: |- + Other connections, including copies of the same client, retain their approvals. + + Requires the jobs:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Authorization revoked + content: + application/json: + schema: + type: object + properties: + revoked: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + required: + - 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_access_authorizations_grantId + tags: + - access + security: + - cookieAuth: [] + x-required-scope: jobs:write + x-owner-session-required: true + parameters: + - name: grantId + in: path + required: true + schema: + type: string + minLength: 1 /api/v1/access/authorized-clients/{clientId}: delete: summary: Revoke an authorized OAuth client @@ -10581,6 +10671,552 @@ paths: runIdentityHeader: [] x-required-scope: [] x-owner-session-required: false + /api/v1/agent/reflection: + get: + 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. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + responses: + "200": + description: Agent reflection + content: + application/json: + schema: + type: object + properties: + identity: + type: object + properties: + id: + 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)$ + kind: + type: string + enum: + - oauth + - run + required: + - id + - kind + additionalProperties: false + scopes: + type: array + items: + type: string + integrations: + type: array + items: + type: object + properties: + id: + 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)$ + name: + type: string + description: + type: + - string + - "null" + kind: + type: string + enum: + - bearer + - github + - linear + - model + policy: + type: string + enum: + - baseline + - requestable + - disabled + available: + type: boolean + revision: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + requiredScope: + type: string + access: + type: string + enum: + - granted + - requestable + - unavailable + instructions: + type: string + required: + - id + - name + - description + - kind + - policy + - available + - revision + - requiredScope + - access + - instructions + additionalProperties: false + required: + - identity + - scopes + - integrations + 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: get_api_v1_agent_reflection + tags: + - agent + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: [] + x-owner-session-required: false + /api/v1/agent/requests: + 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. + + Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session. + responses: + "200": + description: Upstream response or retained response handle + content: + application/json: + schema: + type: object + properties: + status: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + headers: + type: object + propertyNames: + type: string + additionalProperties: + type: string + size: + type: integer + minimum: 0 + maximum: 9007199254740991 + encoding: + type: string + enum: + - utf8 + - base64 + body: + type: string + handle: + 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 + required: + - status + - headers + - size + - encoding + 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_requests + tags: + - agent + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: [] + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + integration: + 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)$ + method: + type: string + enum: + - GET + - HEAD + - POST + - PUT + - PATCH + - DELETE + - OPTIONS + path: + type: string + minLength: 1 + maxLength: 8192 + headers: + default: {} + type: object + propertyNames: + type: string + pattern: ^[!#$%&'*+.^_\x60|~0-9A-Za-z-]+$ + additionalProperties: + type: string + maxLength: 8192 + body: + type: string + maxLength: 44739244 + encoding: + default: utf8 + type: string + enum: + - utf8 + - base64 + required: + - integration + - method + - path + additionalProperties: false + /api/v1/agent/responses/read: + 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 a scoped bearer token, vendor-verified run identity, or interactive owner session. + responses: + "200": + description: Response chunk + content: + application/json: + schema: + type: object + properties: + handle: + 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)$ + offset: + type: integer + minimum: 0 + maximum: 9007199254740991 + nextOffset: + type: integer + minimum: 0 + maximum: 9007199254740991 + size: + type: integer + minimum: 0 + maximum: 9007199254740991 + encoding: + type: string + const: base64 + body: + type: string + done: + type: boolean + required: + - handle + - offset + - nextOffset + - size + - encoding + - body + - done + 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_responses_read + tags: + - agent + security: + - bearerAuth: [] + - vendorRunIdentity: [] + runIdentityHeader: [] + - cookieAuth: [] + x-required-scope: [] + x-owner-session-required: false + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + handle: + 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)$ + offset: + default: 0 + type: integer + minimum: 0 + maximum: 9007199254740991 + required: + - handle + additionalProperties: false + /api/v1/integration-api-policies: + get: + summary: List tenant MCP API access policies + responses: + "200": + description: Policies + content: + application/json: + schema: + type: object + properties: + integrations: + type: array + items: + type: object + properties: + id: + 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)$ + name: + type: string + description: + type: + - string + - "null" + kind: + type: string + enum: + - bearer + - github + - linear + - model + policy: + type: string + enum: + - baseline + - requestable + - disabled + available: + type: boolean + revision: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + requiredScope: + type: string + required: + - id + - name + - description + - kind + - policy + - available + - revision + - requiredScope + additionalProperties: false + required: + - integrations + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: get_api_v1_integration_api_policies + tags: + - integration-api-policies + security: + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + /api/v1/integration-api-policies/{integrationId}: + put: + 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. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Updated policies + content: + application/json: + schema: + type: object + properties: + integrations: + type: array + items: + type: object + properties: + id: + 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)$ + name: + type: string + description: + type: + - string + - "null" + kind: + type: string + enum: + - bearer + - github + - linear + - model + policy: + type: string + enum: + - baseline + - requestable + - disabled + available: + type: boolean + revision: + type: integer + minimum: -9007199254740991 + maximum: 9007199254740991 + requiredScope: + type: string + required: + - id + - name + - description + - kind + - policy + - available + - revision + - requiredScope + additionalProperties: false + required: + - integrations + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: put_api_v1_integration_api_policies_integrationId + tags: + - integration-api-policies + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: integrationId + in: path + required: true + schema: + type: string + minLength: 1 + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + policy: + type: string + enum: + - baseline + - requestable + - disabled + expectedRevision: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + required: + - policy + - expectedRevision + additionalProperties: false /api/v1/runtime-context: get: summary: Inspect the current runtime identity and scopes diff --git a/scripts/agent-api-runtime.test.mjs b/scripts/agent-api-runtime.test.mjs new file mode 100644 index 00000000..cb67c41e --- /dev/null +++ b/scripts/agent-api-runtime.test.mjs @@ -0,0 +1,216 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { createServer as createHttpsServer } from 'node:https'; +import { randomUUID, randomBytes, createHmac, createHash, createCipheriv, generateKeyPairSync, sign } from 'node:crypto'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { resolve } from 'node:path'; +import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; +import { chromium } from 'playwright'; +import pg from 'pg'; +const exec = promisify(execFile); + +// Real workerd/OAuth issuance, compiled browser consent, PostgreSQL and R2. +// The harness replaces only the network destination: every upstream HTTP +// request goes to a local deterministic fixture, never live service credentials. +test('agent API OAuth, policy, connection isolation, run identity and response lifecycle', {skip:!process.env.AUTH_TEST_DATABASE_URL,timeout:180000}, async () => { + const address = new URL(process.env.AUTH_TEST_DATABASE_URL); + assert.ok(['localhost','127.0.0.1'].includes(address.hostname)); + const admin=new pg.Client({connectionString:address.href});await admin.connect(); + const name='agent_api_'+randomUUID().replaceAll('-',''),directory=await mkdtemp(tmpdir()+'/agent-api-'); + let db,mf,browser,upstream,site,worker; + const tenant=randomUUID(),user=randomUUID(),key=randomBytes(32),secret=randomBytes(32).toString('hex'); + let origin; + const encrypt=value=>{const iv=randomBytes(12),cipher=createCipheriv('aes-256-gcm',key,iv);return iv.toString('base64')+'.'+Buffer.concat([cipher.update(value,'utf8'),cipher.final(),cipher.getAuthTag()]).toString('base64');}; + 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');}; + const observed=[];let releaseStream; + try { + await admin.query(`CREATE DATABASE "${name}"`);address.pathname='/'+name;db=new pg.Client({connectionString:address.href});await db.connect(); + for(const file of (await readdir('packages/api/migrations')).filter(file=>/^\d+.*\.sql$/.test(file)).sort()) await db.query(await readFile('packages/api/migrations/'+file,'utf8')); + await db.query('INSERT INTO app.tenants(id,name) VALUES($1,$2)',[tenant,'Agent fixture']); + await db.query('INSERT INTO app.auth_users(id,email,email_verified) VALUES($1,$2,true)',[user,'agent@example.test']); + await db.query("INSERT INTO app.members(tenant_id,user_id,email,role) VALUES($1,$2,$3,'owner')",[tenant,user,'agent@example.test']); + await db.query('INSERT INTO app.integration_collections(tenant_id) VALUES($1)',[tenant]); + const createIntegration=async (name,kind='bearer',payload='upstream-private')=>{ + const id=randomUUID();await db.query("INSERT INTO app.integration_records(tenant_id,id,kind,name,origin,description,revision,encrypted_payload) VALUES($1,$2,$3,$4,$5,'Fixture usage',1,$6)",[tenant,id,kind,name,kind==='bearer'?'https://fixture.upstream.com':null,encrypt((kind==='bearer'?'factorize-managed-bearer-v1:':'factorize-managed-model-cache-v1:')+payload)]); + return (await db.query('SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND credential_id=$2',[tenant,id])).rows[0]; + }; + const baseline=await createIntegration('Baseline API'),requestable=await createIntegration('Requestable API'); + await db.query("UPDATE app.agent_integrations SET policy='baseline' WHERE tenant_id=$1 AND id=$2",[tenant,baseline.id]); + upstream=createServer(async(req,res)=>{ + 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==='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;} + if(target.pathname==='/large') {res.setHeader('Content-Type','application/octet-stream');res.end(Buffer.alloc(1140000,0xff));return;} + if(target.pathname==='/bom') {res.end(Buffer.from([0xef,0xbb,0xbf,0x61]));return;} + if(target.pathname==='/binary') {res.end(Buffer.from([0,255,254,1]));return;} + if(target.pathname==='/redirect') {res.writeHead(302,{Location:'https://evil.invalid/'});res.end();return;} + if(target.pathname==='/stream') {res.setHeader('Content-Type','text/event-stream');res.write('first\n');releaseStream=()=>res.end('last\n');return;} + if(target.pathname==='/failure') res.statusCode=422; + res.setHeader('Set-Cookie','private=hidden');res.setHeader('Authorization','Bearer should-not-escape');res.end('fixture response'); + }); + await new Promise(resolve=>upstream.listen(0,'127.0.0.1',resolve)); + const config=JSON.parse(await readFile('packages/api/wrangler.jsonc','utf8')); + config.main=resolve('packages/api/test/fixtures/agent-api-runtime-worker.ts');config.assets.directory=resolve('packages/app/dist'); + await writeFile(directory+'/wrangler.json',JSON.stringify(config)); + await exec(process.execPath,[resolve('node_modules/wrangler/bin/wrangler.js'),'deploy','--dry-run','--config',directory+'/wrangler.json','--outdir',directory],{maxBuffer:2*1024*1024}); + await exec('openssl',['req','-x509','-newkey','rsa:2048','-nodes','-keyout',directory+'/key.pem','-out',directory+'/cert.pem','-days','1','-subj','/CN=localhost']); + site=createHttpsServer({key:await readFile(directory+'/key.pem'),cert:await readFile(directory+'/cert.pem')},async(req,res)=>{ + try { + const parts=[];for await(const part of req) parts.push(part); + const response=await worker.fetch(origin+req.url,{redirect:'manual',method:req.method,headers:req.headers,...(parts.length?{body:Buffer.concat(parts)}:{})}); + res.statusCode=response.status;response.headers.forEach((value,name)=>{if(name!=='set-cookie') res.setHeader(name,value);}); + res.setHeader('Set-Cookie',response.headers.getSetCookie()); + if(response.body) for await(const part of response.body) res.write(part);res.end(); + }catch(error){res.statusCode=500;res.end(String(error));} + }); + await new Promise(resolve=>site.listen(0,'127.0.0.1',resolve));origin='https://localhost:'+site.address().port; + mf=new Miniflare(convertV4MiniflareOptions({name:"factorize",modules:true,modulesRoot:directory,scriptPath:directory+'/agent-api-runtime-worker.js',compatibilityDate:'2026-09-10',compatibilityFlags:['nodejs_compat','global_fetch_strictly_public'], + bindings:{LINEAR_CLIENT_ID:'fixture-client',LINEAR_CLIENT_SECRET:'fixture-secret',APP_ORIGIN:origin,SESSION_SIGNING_SECRET:secret,CREDENTIAL_ENCRYPTION_KEY:key.toString('base64'),GITHUB_APP_ID:'1',GITHUB_APP_PRIVATE_KEY:privateKey.export({format:'pem',type:'pkcs8'}).toString()}, + kvNamespaces:['OAUTH_KV'],r2Buckets:['RUN_ARTIFACTS'],hyperdrives:{HYPERDRIVE:address.href}, + serviceBindings:{MAINTENANCE:{name:"factorize",entrypoint:"AgentApiMaintenance"},ASSETS:async request=>{ + const path=new URL(request.url).pathname; + try {const data=await readFile(resolve('packages/app/dist','.'+path));return new Response(data,{headers:{'Content-Type':path.endsWith('.js')?'application/javascript':path.endsWith('.css')?'text/css':'text/html'}});}catch{return new Response('Not found',{status:404});} + }}, + outboundService:async request=>{ + const target=new URL(request.url);assert.ok(['fixture.upstream.com','api.github.com','github.com','raw.githubusercontent.com','codeload.github.com','api.linear.app','api.openai.com','oidc.fly.io','auth.openai.com','chatgpt.com'].includes(target.hostname),'Unexpected upstream '+target.hostname); + const headers=new Headers(request.headers);headers.set('x-fixture-target',target.href); + const response=await fetch('http://127.0.0.1:'+upstream.address().port+target.pathname+target.search,{method:request.method,headers,body:request.method==='GET'||request.method==='HEAD'?undefined:await request.arrayBuffer(),redirect:'manual'}); + return new Response(response.body,{status:response.status,headers:response.headers}); + }})); + await mf.ready; + worker = await mf.getWorker("factorize"); + const session=Buffer.from(JSON.stringify({tenantId:tenant,userId:user,email:'agent@example.test',exp:Math.floor(Date.now()/1000)+3600,sessionVersion:1})).toString('base64url'); + const cookieValue=encodeURIComponent(session+'.'+createHmac('sha256',secret).update(session).digest('base64')); + const owner={Cookie:'factorize_session='+cookieValue,Origin:origin}; + const send=(path,method='GET',body,headers={})=>worker.fetch(origin+path,{redirect:"manual",method,headers:{Host:new URL(origin).host,...headers},...(body===undefined?{}:{body:typeof body==='string'?body:JSON.stringify(body)})}); + const json=async(path,method,body,headers)=>{const response=await send(path,method,body,{'Content-Type':'application/json',...headers});return {status:response.status,headers:response.headers,body:await response.json()};}; + const form=async(body)=>{const response=await send('/oauth/token','POST',new URLSearchParams(body).toString(),{'Content-Type':'application/x-www-form-urlencoded'});const result=await response.json();assert.equal(response.status,200,JSON.stringify(result));return result;}; + const registration=await json('/oauth/register','POST',{client_name:'Agent fixture',redirect_uris:['http://127.0.0.1/callback'],token_endpoint_auth_method:'none',grant_types:['authorization_code','refresh_token'],response_types:['code']});assert.equal(registration.status,201); + const clientId=registration.body.client_id; + browser=await chromium.launch({headless:true}); + 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)=>{ + 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(); + if(scopes.some(scope=>scope.startsWith('integration:'))) assert.ok(await page.getByText('Requestable API',{exact:false}).count()); + if(narrow) await page.getByLabel(narrow,{exact:true}).uncheck(); + await page.getByRole('button',{name:decision==='allow'?'Allow':'Deny',exact:true}).click();await page.waitForURL('http://127.0.0.1/callback?**'); + const destination=new URL(page.url());await page.close(); + if(decision==='deny') {assert.equal(destination.searchParams.get('error'),'access_denied');return null;} + return form({grant_type:'authorization_code',client_id:clientId,code:destination.searchParams.get('code'),redirect_uri:'http://127.0.0.1/callback',code_verifier:verifier,resource:origin+'/mcp'}); + }; + let id=1; + const rpc=async(token,name,args={},meta)=>{ + const response=await send('/mcp','POST',{jsonrpc:'2.0',id:id++,method:'tools/call',params:{name,arguments:args,...(meta?{_meta:meta}:{})}},{'Content-Type':'application/json',Accept:'application/json, text/event-stream','MCP-Protocol-Version':'2025-11-25',Authorization:'Bearer '+token.access_token}); + const text=await response.text();let messages; + 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 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'); + 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')); + await authorize(['jobs:read',scopes(requestable)],'deny');assert.equal((await request(first,requestable)).status,403); + const unapproved=await authorize(['jobs:read',scopes(requestable)],'allow',scopes(requestable));assert.equal((await request(unapproved,requestable)).status,403); + const stepped=await authorize(['jobs:read',scopes(requestable)]);assert.equal((await request(stepped,requestable)).result.status,200);assert.equal((await rpc(stepped,'list_jobs')).status,200);assert.equal((await request(second,requestable)).status,403); + 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 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); + await policy(requestable,'disabled');assert.equal((await request(stepped,requestable)).status,403);await policy(requestable,'requestable');assert.equal((await request(stepped,requestable)).status,403,'disable revokes approvals permanently'); + requestable.epoch=(await db.query('SELECT epoch FROM app.agent_integrations WHERE id=$1',[requestable.id])).rows[0].epoch; + const fresh=await authorize(['jobs:read',scopes(requestable)]);assert.equal((await request(fresh,requestable)).result.status,200); + const bom=await request(first,baseline,'/bom');assert.equal(bom.result.body,'\ufeffa');assert.equal(bom.result.size,4); + const binary=await request(first,baseline,'/binary');assert.equal(binary.result.encoding,'base64');assert.deepEqual(Buffer.from(binary.result.body,'base64'),Buffer.from([0,255,254,1])); + 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 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); + for(const path of ['https://evil.invalid/','//evil.invalid/','/\\evil','/x#fragment']) assert.equal((await request(first,baseline,path)).status,400); + await db.query("INSERT INTO app.members(tenant_id,user_id,email,role) VALUES($1,$2,'agent@example.test','owner')",[otherTenant,user]); + const foreignSession=Buffer.from(JSON.stringify({tenantId:otherTenant,userId:user,email:'agent@example.test',exp:Math.floor(Date.now()/1000)+3600,sessionVersion:1})).toString('base64url'); + 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.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. + const expired=await request(second,baseline,'/large'),interrupted=await request(second,baseline,'/large'); + 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')); + 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); + // All provider adapters use the same grants and forwarding boundary. + await db.query("INSERT INTO app.github_installations(installation_id,tenant_id,account_login,account_type,state) VALUES(17,$1,'fixture','Organization','active')",[tenant]); + await db.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,'linear',$2)",[tenant,encrypt(JSON.stringify({accessToken:'linear-private',refreshToken:'linear-refresh',accessTokenExpiresAt:new Date(Date.now()-3600000).toISOString()}))]); + const model=await createIntegration('Model API','model',JSON.stringify({OPENAI_API_KEY:'model-private'})); + for(const [kind,path,expected,auth] of [['github','/repos/fixture/repo','https://api.github.com/repos/fixture/repo','github-private'],['linear','/graphql','https://api.linear.app/graphql','linear-refreshed'],['model','/responses','https://api.openai.com/v1/responses','model-private']]) { + const row=(await db.query('SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind=$2',[tenant,kind])).rows[0];await policy(row,'baseline'); + const result=await request(first,row,path);assert.equal(result.result.status,200,result.text);assert.equal(observed.at(-1).target,expected);assert.equal(observed.at(-1).headers.authorization,'Bearer '+auth); + } + const github=(await db.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind='github'",[tenant])).rows[0]; + for(const [path,target] of [['/owner/repo.git/info/refs','https://github.com/owner/repo.git/info/refs'],['/raw/owner/repo/main/file','https://raw.githubusercontent.com/owner/repo/main/file'],['/archive/owner/repo/zip/main','https://codeload.github.com/owner/repo/zip/main']]) { + assert.equal((await request(first,github,path)).result.status,200);assert.equal(observed.at(-1).target,target); + if(path.includes('info/refs')) assert.equal(observed.at(-1).headers.authorization,'Basic '+Buffer.from('x-access-token:github-private').toString('base64')); + } + const oauthModel=await createIntegration('OAuth Model','model',JSON.stringify({tokens:{access_token:'expired-model',refresh_token:'model-refresh'},last_refresh:'2000-01-01T00:00:00Z'})); + await policy(oauthModel,'baseline');assert.equal((await request(first,oauthModel,'/responses')).result.status,200);assert.equal(observed.at(-1).target,'https://chatgpt.com/backend-api/codex/responses');assert.equal(observed.at(-1).headers.authorization,'Bearer model-oauth-private'); + assert.ok(observed.some(row=>row.target==='https://auth.openai.com/oauth/token'));assert.ok(observed.some(row=>row.target==='https://api.linear.app/oauth/token')); + // Verified Fly OIDC reaches the same service using an immutable run snapshot. + const runId=randomUUID(),jobId=randomUUID(),invocationId=randomUUID(),now=Math.floor(Date.now()/1000); + await db.query("INSERT INTO app.projects(tenant_id,id,name) VALUES($1,md5(($1::uuid)::text || ':default')::uuid,'Default')",[tenant]); + await db.query("INSERT INTO app.jobs(tenant_id,id,project_id,name,slug,encrypted_prompt_template,execution_config,concurrency_limit) VALUES($1,$2,md5(($1::uuid)::text || ':default')::uuid,'Fixture','fixture','cipher','{}',1)",[tenant,jobId]); + await db.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES($1,gen_random_uuid(),$2,'manual','manual')",[tenant,jobId]); + await db.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,context,trigger_id) VALUES($1,$2,$3,'manual','fixture','{}',(SELECT id FROM app.triggers WHERE tenant_id=$1 AND job_id=$3))",[tenant,invocationId,jobId]); + await db.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES($1,$2,$3,$4,'running','cipher')",[tenant,runId,jobId,invocationId]); + await db.query("INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,agent_name,state,execution_config,execution_handle) VALUES($1,$2,$3,$4,'manual','fixture','codex','running',$5,$6)",[tenant,runId,jobId,invocationId,{portableIntegrationIds:[baseline.credential_id]},{id:'fixture-app/machine'}]); + await db.query("INSERT INTO app.fly_connections(tenant_id,organization_slug,organization_name,encrypted_token) VALUES($1,'fixture','Fixture','cipher')",[tenant]); + await db.query("INSERT INTO app.run_authorizations(tenant_id,run_id,user_id,session_version,scopes) VALUES($1,$2,$3,1,'[]')",[tenant,runId,user]); + const subject='fixture:fixture-app:machine'; + await db.query("INSERT INTO app.vendor_run_identity_bindings(tenant_id,run_id,provider,vm_id,issuer,subject,audience,issued_at,expires_at) VALUES($1,$2,'fly.io','machine','https://oidc.fly.io/fixture',$3,$4,now(),now()+interval '1 hour')",[tenant,runId,subject,origin]); + const runHeaders={'X-Factorize-Run-Id':runId,Authorization:'Bearer '+jwt({machine_id:'machine',iss:'https://oidc.fly.io/fixture',sub:subject,aud:origin,iat:now,exp:now+300})}; + const runResponse=await send('/api/v1/agent/reflection','GET',undefined,runHeaders);assert.equal(runResponse.status,200,await runResponse.clone().text());assert.equal((await runResponse.json()).integrations.length,1); + const stream=await send('/internal/run-proxy/'+runId+'/integrations/'+baseline.credential_id+'/stream','GET',undefined,runHeaders);assert.equal(stream.status,200); + const streamReader=stream.body.getReader();assert.match(new TextDecoder().decode((await streamReader.read()).value),/first/);releaseStream();assert.match(new TextDecoder().decode((await streamReader.read()).value),/last/); + assert.equal((await send('/internal/run-proxy/'+runId+'/integrations/'+requestable.credential_id+'/','GET',undefined,runHeaders)).status,403); + assert.equal((await send('/api/v1/agent/reflection','GET',undefined,{...runHeaders,Authorization:'Bearer '+first.access_token})).status,401,'invalid vendor identity cannot fall back to OAuth'); + await db.query("UPDATE app.jobs SET execution_config=$3 WHERE tenant_id=$1 AND id=$2",[tenant,jobId,{portableIntegrationIds:[baseline.credential_id,requestable.credential_id]}]); + assert.equal((await send('/internal/run-proxy/'+runId+'/integrations/'+requestable.credential_id+'/','GET',undefined,runHeaders)).status,403,'job edits cannot expand the run snapshot'); + 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'); + 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 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}); + } +});