diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index eca44928..65f0c0a9 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1,5 +1,69 @@ // Generated from packages/docs/openapi.yaml. Do not edit. export interface paths { + "/api/v1/integrations/bearer": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List encrypted bearer integrations + * @description Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed. + * + * Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_integrations_bearer"]; + put?: never; + /** + * Create an encrypted bearer integration + * @description Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_integrations_bearer"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/integrations/bearer/{integrationId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Update an encrypted bearer integration + * @description Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_integrations_bearer_integrationId"]; + post?: never; + /** + * Delete an encrypted bearer integration + * @description Requires an interactive owner browser session and the current collection revision. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_integrations_bearer_integrationId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/auth/connections": { parameters: { query?: never; @@ -2451,6 +2515,185 @@ export interface components { } export type $defs = Record; export interface operations { + get_api_v1_integrations_bearer: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Encrypted bearer integration records */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revision: number; + integrations: { + /** Format: uuid */ + id: string; + name: string; + origin: string; + description: string | null; + revision: number; + encryptedPayload: 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_integrations_bearer: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** Format: uuid */ + id: string; + expectedRevision: number; + /** Format: uuid */ + idempotencyKey: string; + name: string; + /** Format: uri */ + origin: string; + description: string | null; + encryptedPayload: string; + }; + }; + }; + responses: { + /** @description Created integration */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revision: number; + duplicate: 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"]; + }; + }; + put_api_v1_integrations_bearer_integrationId: { + parameters: { + query?: never; + header?: never; + path: { + integrationId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + expectedRevision: number; + /** Format: uuid */ + idempotencyKey: string; + name: string; + /** Format: uri */ + origin: string; + description: string | null; + encryptedPayload: string; + }; + }; + }; + responses: { + /** @description Updated integration */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + revision: number; + duplicate: 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"]; + }; + }; + delete_api_v1_integrations_bearer_integrationId: { + parameters: { + query?: never; + header?: never; + path: { + integrationId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + expectedRevision: number; + /** Format: uuid */ + idempotencyKey: string; + }; + }; + }; + responses: { + /** @description Deleted integration */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + id: string; + /** @constant */ + deleted: true; + revision: number; + duplicate: 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"]; + }; + }; post_api_v1_auth_connections: { parameters: { query?: never; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 3782a6b5..cd92fd90 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -117,6 +117,20 @@ const accessTokenBody = z.object({ scopes: z.array(z.union([scopeSchema, z.enum(["flows:read", "flows:write"])] )).min(1), expiryDays: z.union([z.literal(7), z.literal(30), z.literal(90)]), }); +const bearerIntegrationMetadata = z.object({ + id: z.uuid(), name: z.string(), origin: z.string(), description: z.string().nullable(), + revision: z.number().int().nonnegative(), encryptedPayload: z.string(), +}); +const bearerIntegrationCreate = z.object({ + id: z.uuid(), expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid(), + name: z.string().trim().min(1).max(120), origin: z.string().url().max(2048), + description: z.string().max(500).nullable(), encryptedPayload: z.string().min(1).max(65_536), +}).strict(); +const bearerIntegrationUpdate = bearerIntegrationCreate.omit({ id: true }); +const bearerIntegrationDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict(); +const bearerIntegrationList = z.object({ revision: z.number().int().nonnegative(), integrations: z.array(bearerIntegrationMetadata) }); +const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() }); +const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); function route( method: string, @@ -195,6 +209,26 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st } export const API_ROUTES: RouteContract[] = [ + route("GET", "/api/v1/integrations/bearer", "flows:read", { + summary: "List encrypted bearer integrations", + description: "Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed.", + responses: { "200": { description: "Encrypted bearer integration records", content: { "application/json": { schema: jsonSchema(bearerIntegrationList, "output") } } } }, + }, service => service.listBearerIntegrations(), { ownerSession: true }), + route("POST", "/api/v1/integrations/bearer", "flows:write", { + summary: "Create an encrypted bearer integration", + description: "Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential.", + responses: { "201": { description: "Created integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } }, + }, (service, { body }) => service.createBearerIntegration(body), { body: bearerIntegrationCreate, maxBodyBytes: 70_000, ownerSession: true }), + route("PUT", "/api/v1/integrations/bearer/{integrationId}", "flows:write", { + summary: "Update an encrypted bearer integration", + description: "Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext.", + responses: { "200": { description: "Updated integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } }, + }, (service, { params, body }) => service.updateBearerIntegration(params.integrationId, body), { body: bearerIntegrationUpdate, maxBodyBytes: 70_000, ownerSession: true }), + route("DELETE", "/api/v1/integrations/bearer/{integrationId}", "flows:write", { + summary: "Delete an encrypted bearer integration", + description: "Requires an interactive owner browser session and the current collection revision.", + responses: { "200": { description: "Deleted integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationDeleteResult, "output") } } } }, + }, (service, { params, body }) => service.deleteBearerIntegration(params.integrationId, body), { body: bearerIntegrationDelete, maxBodyBytes: 4096, ownerSession: true }), authRoute("POST", "/api/v1/auth/connections", "connection-start", "Persist an individual validated MCP connection; sets a per-attempt browser cookie", connectionStartSuccess, connectionStartInput), authRoute("POST", "/api/v1/auth/connections/resume", "connection-resume", "Resume verified onboarding in the initiating browser; never grants OAuth access", continuationSuccess, connectionResumeInput), authRoute("GET", "/api/v1/session", "session", "Get current browser session", sessionResponse), diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 9402a3a6..b7be1eec 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -16,6 +16,7 @@ import { jobResponse } from "./job-contracts"; import type { JobPageQuery } from "./job-contracts"; import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository"; import { ConnectionRepository } from "./postgres/connection-repository"; +import { EncryptedIntegrationRepository, IntegrationIdempotencyConflictError, IntegrationValidationError, StaleIntegrationRevisionError } from "./postgres/encrypted-integration-repository"; import { decrypt, encrypt } from "./crypto"; import { InvocationService, type Job, type Trigger } from "./job-domain"; import { RunQueryRepository } from "./postgres/run-query-repository"; @@ -456,6 +457,44 @@ export class ApiService { async testAmpIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().testAmp(input); } async saveTailIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveTail(input); } async testTailIntegration(id: string) { await this.authorize("integrations:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } + private encryptedIntegrations() { return new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload?: string; operation: "upsert" | "delete" }) { + try { return await this.encryptedIntegrations().write({ ...input, kind: "bearer" }); } + catch (error) { + if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `The integration collection changed. Current revision is ${error.currentRevision}.`); + if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different integration change."); + if (error instanceof IntegrationValidationError) throw new ServiceError(400, "invalid_request", error.message); + throw error; + } + } + private validateBearerOrigin(origin: string) { + let parsed: URL; + try { parsed = new URL(origin); } catch { throw new ServiceError(400, "invalid_request", "Integration origin must be an HTTPS origin."); } + if (parsed.protocol !== "https:" || parsed.origin !== origin || parsed.username || parsed.password) throw new ServiceError(400, "invalid_request", "Integration origin must be an HTTPS origin without credentials, path, query, or fragment."); + } + async listBearerIntegrations() { + await this.authorizeOwnerSession("integrations:read"); + const [revision, records] = await Promise.all([this.encryptedIntegrations().revision(), this.encryptedIntegrations().records("bearer")]); + return { revision, integrations: records }; + } + async createBearerIntegration(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload: string }) { + await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin); + if ((await this.encryptedIntegrations().records("bearer")).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "Integration already exists."); + return this.bearerWrite({ ...input, operation: "upsert" }); + } + async updateBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload: string }) { + await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin); + const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id); + if (!existing) throw new ServiceError(404, "not_found", "Integration not found."); + return this.bearerWrite({ ...input, id, operation: "upsert" }); + } + async deleteBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string }) { + await this.authorizeOwnerSession("integrations:write"); + const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id && record.origin !== null); + if (!existing) throw new ServiceError(404, "not_found", "Integration not found."); + const result = await this.bearerWrite({ id, name: existing.name, origin: existing.origin!, description: existing.description, ...input, operation: "delete" }); + return { id, deleted: true as const, ...result }; + } async removeTailIntegration(id: string) { await this.authorize("integrations:write"); if (!await this.connections().delete(`cloudflare-tail:${id}`)) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } async linearProjects() { await this.authorize("integrations:read"); return publicValue(z.array(namedOption), await this.providers().linearProjects()); } async linearOptions() { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().linearOptions()); } diff --git a/packages/api/src/postgres/encrypted-integration-repository.ts b/packages/api/src/postgres/encrypted-integration-repository.ts index aa864fa0..4edea45d 100644 --- a/packages/api/src/postgres/encrypted-integration-repository.ts +++ b/packages/api/src/postgres/encrypted-integration-repository.ts @@ -37,6 +37,17 @@ function safeRevision(value: string | number): number { return number; } +function isUserCiphertext(value: string): boolean { + if (value.length > 65_536) return false; + const [encodedIv, encodedBody, extra] = value.split("."); + if (!encodedIv || !encodedBody || extra !== undefined) return false; + try { + const iv = atob(encodedIv), body = atob(encodedBody); + return iv.length === 12 && body.length >= 16 + && btoa(iv) === encodedIv && btoa(body) === encodedBody; + } catch { return false; } +} + function validate(change: IntegrationWrite): void { if (!Number.isSafeInteger(change.expectedRevision) || change.expectedRevision < 0) throw new IntegrationValidationError("expectedRevision must be a non-negative safe integer"); const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -46,7 +57,7 @@ function validate(change: IntegrationWrite): void { if (change.description !== null && change.description.length > 500) throw new IntegrationValidationError("description must be at most 500 characters"); if (change.kind === "bearer" && (!change.origin || change.origin.length > 2048)) throw new IntegrationValidationError("bearer integrations require an origin of at most 2048 characters"); if (change.kind === "model" && change.origin !== null) throw new IntegrationValidationError("model accounts do not have an origin"); - if (change.operation === "upsert" && (typeof change.encryptedPayload !== "string" || !change.encryptedPayload.length)) throw new IntegrationValidationError("upserts require user-encrypted ciphertext"); + if (change.operation === "upsert" && (typeof change.encryptedPayload !== "string" || !isUserCiphertext(change.encryptedPayload))) throw new IntegrationValidationError("upserts require a valid user-encrypted AES-GCM ciphertext envelope"); if (change.operation === "delete" && change.encryptedPayload !== undefined) throw new IntegrationValidationError("deletions cannot contain ciphertext"); } @@ -103,9 +114,9 @@ export class EncryptedIntegrationRepository { }); } - async records(): Promise> { + async records(kind?: EncryptedIntegrationKind): Promise> { const { rows } = await this.database.pool.query<{ id: string; kind: EncryptedIntegrationKind; name: string; origin: string | null; description: string | null; revision: string | number; encrypted_payload: string }>( - "SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND deleted_at IS NULL ORDER BY revision,id", [this.tenantId]); + `SELECT id,kind,name,origin,description,revision,encrypted_payload FROM app.integration_records WHERE tenant_id=$1 AND deleted_at IS NULL${kind ? " AND kind=$2" : ""} ORDER BY revision,id`, kind ? [this.tenantId, kind] : [this.tenantId]); return Promise.all(rows.map(async row => ({ id: row.id, kind: row.kind, name: row.name, origin: row.origin, description: row.description, revision: safeRevision(row.revision), encryptedPayload: await decrypt(row.encrypted_payload, this.serverEncryptionKey) }))); } diff --git a/packages/api/test/encrypted-integration-api.postgres.test.ts b/packages/api/test/encrypted-integration-api.postgres.test.ts new file mode 100644 index 00000000..e4b59dc2 --- /dev/null +++ b/packages/api/test/encrypted-integration-api.postgres.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from "vitest"; +import worker from "../src/worker"; +import { protectedApiFetch } from "../src/protected-api"; +import { IdentityRepository } from "../src/postgres/identity-repository"; +import { signSession } from "../src/session"; +import { loadingFixture } from "./helpers/loading-fixture"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); +const databaseUrl = process.env.AUTH_TEST_DATABASE_URL; + +async function userEncrypt(plaintext: string): Promise { + const iv = crypto.getRandomValues(new Uint8Array(12)); + const key = await crypto.subtle.importKey("raw", Uint8Array.from(atob(btoa("u".repeat(32))), c => c.charCodeAt(0)), "AES-GCM", false, ["encrypt"]); + const body = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(plaintext)); + const encode = (bytes: Uint8Array) => btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join("")); + return `${encode(iv)}.${encode(new Uint8Array(body))}`; +} + +describe.skipIf(!databaseUrl)("browser-only encrypted bearer integration API (PostgreSQL)", { timeout: 60_000 }, () => { + it("supports safe create, list, update, delete and rejects malformed and stale writes", async () => { + const f = await loadingFixture(databaseUrl!); + try { + const request = (path: string, method = "GET", body?: unknown, cookie = f.cookie) => worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1" + path, { + method, headers: { Cookie: cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }), f.env, { waitUntil() {} } as any); + const id = crypto.randomUUID(), idempotencyKey = crypto.randomUUID(), cipher = await userEncrypt("synthetic upstream bearer credential"); + const created = await request("/integrations/bearer", "POST", { id, expectedRevision: 0, idempotencyKey, name: "Test service", origin: "https://api.example.test", description: "fixture", encryptedPayload: cipher }); + expect(created.status).toBe(201); + expect(await created.json()).toEqual({ revision: 1, duplicate: false }); + + const listed = await request("/integrations/bearer"); + expect(listed.status).toBe(200); + const result = await listed.json() as any; + expect(result).toEqual({ revision: 1, integrations: [{ id, kind: "bearer", name: "Test service", origin: "https://api.example.test", description: "fixture", revision: 1, encryptedPayload: cipher }] }); + expect(JSON.stringify(result)).not.toContain("synthetic upstream bearer credential"); + expect(result.integrations[0]).not.toHaveProperty("unlockKey"); + expect(result.integrations[0]).not.toHaveProperty("token"); + + const updated = await request(`/integrations/bearer/${id}`, "PUT", { expectedRevision: 1, idempotencyKey: crypto.randomUUID(), name: "Renamed service", origin: "https://api.example.test", description: null, encryptedPayload: cipher }); + expect(updated.status).toBe(200); + expect(await updated.json()).toEqual({ revision: 2, duplicate: false }); + + const malformed = await request("/integrations/bearer", "POST", { id: crypto.randomUUID(), expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Malformed", origin: "https://api.example.test", description: null, encryptedPayload: "not-ciphertext" }); + expect(malformed.status).toBe(400); + const plaintext = await request("/integrations/bearer", "POST", { id: crypto.randomUUID(), expectedRevision: 2, idempotencyKey: crypto.randomUUID(), name: "Plaintext", origin: "https://api.example.test", description: null, encryptedPayload: cipher, bearerToken: "must-not-be-accepted" }); + expect(plaintext.status).toBe(400); + const stale = await request(`/integrations/bearer/${id}`, "PUT", { expectedRevision: 1, idempotencyKey: crypto.randomUUID(), name: "Stale", origin: "https://api.example.test", description: null, encryptedPayload: cipher }); + expect(stale.status).toBe(409); + expect((await stale.json() as any).error.code).toBe("stale_revision"); + + const deleted = await request(`/integrations/bearer/${id}`, "DELETE", { expectedRevision: 2, idempotencyKey: crypto.randomUUID() }); + expect(deleted.status).toBe(200); + expect(await deleted.json()).toEqual({ id, deleted: true, revision: 3, duplicate: false }); + expect((await (await request("/integrations/bearer")).json() as any).integrations).toEqual([]); + } finally { await f.cleanup(); } + }); + + it("requires a browser session and isolates records across tenants", async () => { + const f = await loadingFixture(databaseUrl!); + try { + const path = f.env.APP_ORIGIN + "/api/v1/integrations/bearer"; + const anonymous = await worker.fetch(new Request(path), f.env, { waitUntil() {} } as any); + expect(anonymous.status).toBe(401); + const agent = await protectedApiFetch(new Request(path), f.env, { tenantId: f.tenantId, userId: f.userId, sessionVersion: 0, scopes: ["integrations:write"], authMethod: "access_token" } as any, {} as any); + expect(agent.status).toBe(403); + + const id = crypto.randomUUID(), cipher = await userEncrypt("tenant private credential"); + const created = await worker.fetch(new Request(path, { method: "POST", headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ id, expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Private", origin: "https://api.example.test", description: null, encryptedPayload: cipher }) }), f.env, { waitUntil() {} } as any); + expect(created.status).toBe(201); + + const otherUser = crypto.randomUUID(); + await new IdentityRepository(f.db, f.otherTenant).upsertOwner(otherUser, "other-owner@example.test"); + const member = await new IdentityRepository(f.db, f.otherTenant).member(otherUser); + const otherCookie = `factorize_session=${await signSession({ tenantId: f.otherTenant, userId: otherUser, email: "other-owner@example.test", sessionVersion: member!.sessionVersion, exp: Math.floor(Date.now() / 1000) + 600 }, f.env.SESSION_SIGNING_SECRET)}`; + const otherList = await worker.fetch(new Request(path, { headers: { Cookie: otherCookie } }), f.env, { waitUntil() {} } as any); + expect(otherList.status).toBe(200); + expect(await otherList.json()).toEqual({ revision: 0, integrations: [] }); + const otherUpdate = await worker.fetch(new Request(path + `/${id}`, { method: "PUT", headers: { Cookie: otherCookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, body: JSON.stringify({ expectedRevision: 0, idempotencyKey: crypto.randomUUID(), name: "Stolen", origin: "https://api.example.test", description: null, encryptedPayload: cipher }) }), f.env, { waitUntil() {} } as any); + expect(otherUpdate.status).toBe(404); + } finally { await f.cleanup(); } + }); +}); diff --git a/packages/api/test/fly-machines-client.test.ts b/packages/api/test/fly-machines-client.test.ts index 94bb73d2..5ada3866 100644 --- a/packages/api/test/fly-machines-client.test.ts +++ b/packages/api/test/fly-machines-client.test.ts @@ -80,14 +80,22 @@ describe("bounded Fly Machines client", () => { it("bounds a stalled response body and reports a secret-safe timeout", async () => { let count = 0; + let markRequestReceived!: () => void; + const requestReceived = new Promise(resolve => { markRequestReceived = resolve; }); const origin = await fakeFly((_req, res) => { count++; + markRequestReceived(); res.writeHead(200, { "content-type": "application/json" }); res.flushHeaders(); // Deliberately leave the body open until the client deadline aborts it. }); - const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 30, maxRetries: 0 }); - await expect(client.inspectMachine("app", "machine")).rejects.toMatchObject({ kind: "timeout" }); + const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 1_000, maxRetries: 0 }); + const inspection = client.inspectMachine("app", "machine"); + let deadline: ReturnType | undefined; + try { + await Promise.race([requestReceived, new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("Fake Fly server did not receive the bounded request")), 5_000); })]); + } finally { if (deadline) clearTimeout(deadline); } + await expect(inspection).rejects.toMatchObject({ kind: "timeout" }); expect(count).toBe(1); }); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 17ad6941..14652096 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -1787,6 +1787,370 @@ components: schema: $ref: "#/components/schemas/Error" paths: + /api/v1/integrations/bearer: + get: + summary: List encrypted bearer integrations + description: |- + Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed. + + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Encrypted bearer integration records + content: + application/json: + schema: + type: object + properties: + revision: + type: integer + minimum: 0 + maximum: 9007199254740991 + 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 + origin: + type: string + description: + type: + - string + - "null" + revision: + type: integer + minimum: 0 + maximum: 9007199254740991 + encryptedPayload: + type: string + required: + - id + - name + - origin + - description + - revision + - encryptedPayload + additionalProperties: false + required: + - revision + - 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_integrations_bearer + tags: + - integrations + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + post: + summary: Create an encrypted bearer integration + description: |- + Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "201": + description: Created integration + content: + application/json: + schema: + type: object + properties: + revision: + type: integer + minimum: 0 + maximum: 9007199254740991 + duplicate: + type: boolean + required: + - revision + - duplicate + 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_integrations_bearer + tags: + - integrations + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + 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)$ + expectedRevision: + type: integer + minimum: 0 + maximum: 9007199254740991 + idempotencyKey: + 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 + minLength: 1 + maxLength: 120 + origin: + type: string + maxLength: 2048 + format: uri + description: + anyOf: + - type: string + maxLength: 500 + - type: "null" + encryptedPayload: + type: string + minLength: 1 + maxLength: 65536 + required: + - id + - expectedRevision + - idempotencyKey + - name + - origin + - description + - encryptedPayload + additionalProperties: false + /api/v1/integrations/bearer/{integrationId}: + put: + summary: Update an encrypted bearer integration + description: |- + Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Updated integration + content: + application/json: + schema: + type: object + properties: + revision: + type: integer + minimum: 0 + maximum: 9007199254740991 + duplicate: + type: boolean + required: + - revision + - duplicate + 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_integrations_bearer_integrationId + tags: + - integrations + security: + - bearerAuth: [] + - 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: + expectedRevision: + type: integer + minimum: 0 + maximum: 9007199254740991 + idempotencyKey: + 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 + minLength: 1 + maxLength: 120 + origin: + type: string + maxLength: 2048 + format: uri + description: + anyOf: + - type: string + maxLength: 500 + - type: "null" + encryptedPayload: + type: string + minLength: 1 + maxLength: 65536 + required: + - expectedRevision + - idempotencyKey + - name + - origin + - description + - encryptedPayload + additionalProperties: false + delete: + summary: Delete an encrypted bearer integration + description: |- + Requires an interactive owner browser session and the current collection revision. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Deleted integration + content: + application/json: + schema: + 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)$ + deleted: + type: boolean + const: true + revision: + type: integer + minimum: 0 + maximum: 9007199254740991 + duplicate: + type: boolean + required: + - id + - deleted + - revision + - duplicate + 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: delete_api_v1_integrations_bearer_integrationId + tags: + - integrations + security: + - bearerAuth: [] + - 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: + expectedRevision: + type: integer + minimum: 0 + maximum: 9007199254740991 + idempotencyKey: + 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)$ + required: + - expectedRevision + - idempotencyKey + additionalProperties: false /api/v1/auth/connections: post: summary: Persist an individual validated MCP connection; sets a per-attempt browser cookie diff --git a/scripts/validation.mjs b/scripts/validation.mjs index e5f710e7..50aff789 100644 --- a/scripts/validation.mjs +++ b/scripts/validation.mjs @@ -17,7 +17,7 @@ const lanes = { ["application build", "npm", ["run", "build", "--workspace=factorize-app"], 90_000], ["Chromium availability", process.execPath, ["scripts/validation.mjs", "--check-chromium"], 15_000], ["functional browser checks", "npm", ["run", "test:functional", "--workspace=factorize-app"], 90_000], - ["application unit checks", "npm", ["test", "--workspace=factorize-app"], 180_000], + ["application unit checks", "npm", ["test", "--workspace=factorize-app"], 240_000], ], proxy: [ ["portable proxy harness checks", process.execPath, ["--test", "scripts/validation-runner.test.mjs"], 30_000],