diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 3a6e82f7..96c05149 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -544,6 +544,70 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/fly/connection": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read Fly account connection status + * @description Owner browser session only. Returns organization metadata and never returns the provisioning token. + * + * Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_fly_connection"]; + /** + * Save a Fly account connection + * @description Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org `. A read-only org token is insufficient for provisioning. The server validates the connection and encrypts the token with its credential key; the token is never returned. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_fly_connection"]; + post?: never; + /** + * Remove the Fly account connection + * @description Owner browser session only. Deletes the tenant's encrypted provisioning token. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_fly_connection"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/fly/connection/test": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Validate a Fly organization token + * @description Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org `. A read-only org token is insufficient for later provisioning. Validation calls Fly's documented read-only current-token endpoint and launches no resources. + * + * Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_fly_connection_test"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/integrations/exe": { parameters: { query?: never; @@ -3823,6 +3887,153 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_fly_connection: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Connection status */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + connection: { + organizationSlug: string; + organizationName: string; + } | null; + }; + }; + }; + 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_fly_connection: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + token: string; + organizationSlug: string; + }; + }; + }; + responses: { + /** @description Saved connection metadata */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + connection: { + organizationSlug: string; + organizationName: string; + }; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_fly_connection: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deletion result */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + deleted: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_fly_connection_test: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + token: string; + organizationSlug: string; + }; + }; + }; + responses: { + /** @description Validated organization */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @constant */ + valid: true; + connection: { + organizationSlug: string; + organizationName: 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"]; + }; + }; put_api_v1_integrations_exe: { parameters: { query?: never; diff --git a/packages/api/migrations/0034_fly_connections.sql b/packages/api/migrations/0034_fly_connections.sql new file mode 100644 index 00000000..8e94677a --- /dev/null +++ b/packages/api/migrations/0034_fly_connections.sql @@ -0,0 +1,8 @@ +CREATE TABLE app.fly_connections ( + tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE, + organization_slug text NOT NULL CHECK (organization_slug ~ '^[a-z0-9-]{1,63}$'), + organization_name text NOT NULL CHECK (length(organization_name) BETWEEN 1 AND 120), + encrypted_token text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index c2b3c356..42861c26 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -27,6 +27,7 @@ import { traceReplaySchema } from "./trace-replay-schemas"; import document from "./api-document.json"; import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api"; import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput } from "./skills"; +import { flyConnectionInput, flyConnectionMetadata } from "./fly-account-client"; type JsonSchema = Record; export interface RouteContract { @@ -358,6 +359,26 @@ export const API_ROUTES: RouteContract[] = [ }, (service) => service.integrationStatus(), ), + route("GET", "/api/v1/fly/connection", "integrations:read", { + summary: "Read Fly account connection status", + description: "Owner browser session only. Returns organization metadata and never returns the provisioning token.", + responses: { "200": { description: "Connection status", content: { "application/json": { schema: jsonSchema(z.object({ connection: flyConnectionMetadata.nullable() }), "output") } } } }, + }, service => service.getFlyConnection(), { ownerSession: true }), + route("POST", "/api/v1/fly/connection/test", "integrations:write", { + summary: "Validate a Fly organization token", + description: "Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org `. A read-only org token is insufficient for later provisioning. Validation calls Fly's documented read-only current-token endpoint and launches no resources.", + responses: { "200": { description: "Validated organization", content: { "application/json": { schema: jsonSchema(z.object({ valid: z.literal(true), connection: flyConnectionMetadata }), "output") } } } }, + }, (service, { body }) => service.validateFlyConnection(body), { body: flyConnectionInput, ownerSession: true }), + route("PUT", "/api/v1/fly/connection", "integrations:write", { + summary: "Save a Fly account connection", + description: "Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org `. A read-only org token is insufficient for provisioning. The server validates the connection and encrypts the token with its credential key; the token is never returned.", + responses: { "200": { description: "Saved connection metadata", content: { "application/json": { schema: jsonSchema(z.object({ connection: flyConnectionMetadata }), "output") } } } }, + }, (service, { body }) => service.saveFlyConnection(body), { body: flyConnectionInput, ownerSession: true }), + route("DELETE", "/api/v1/fly/connection", "integrations:write", { + summary: "Remove the Fly account connection", + description: "Owner browser session only. Deletes the tenant's encrypted provisioning token.", + responses: { "200": { description: "Deletion result", content: { "application/json": { schema: jsonSchema(z.object({ deleted: z.boolean() }), "output") } } } }, + }, service => service.removeFlyConnection(), { ownerSession: true }), route( "PUT", "/api/v1/integrations/exe", diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 6d9b3e15..c1739a36 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -40,6 +40,8 @@ import { SkillRepository, SkillConflict, SkillReferenced } from "./postgres/skil import { RunRepository } from "./postgres/run-repository"; import { safeDiagnosticText } from "./harness-diagnostics"; import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput, composePrompt } from "./skills"; +import { createFlyAccountClient, FlyAccountError, flyConnectionInput } from "./fly-account-client"; +import { FlyConnectionRepository } from "./postgres/fly-connection-repository"; const PROJECT_GRAPH_LABEL_MAX_CHARS = 24; @@ -65,6 +67,7 @@ export class ApiService { private jobs() { return new PostgresJobRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); } private connections() { return new ConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private flyConnections() { return new FlyConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private projects() { return new ProjectRepository(databaseFor(this.env), this.auth.tenantId); } private skills() { return new SkillRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private async executionConfig(id: string) { @@ -168,6 +171,26 @@ export class ApiService { async listExeConnections() { await this.authorize("integrations:read"); return publicValue(z.array(exeConnection), (await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).status()).exeConnections); } + async getFlyConnection() { await this.authorizeOwnerSession("integrations:read"); return { connection: await this.flyConnections().get() }; } + async validateFlyConnection(input: unknown) { + await this.authorizeOwnerSession("integrations:write"); + const parsed = flyConnectionInput.parse(input); + try { return { valid: true, connection: await createFlyAccountClient().validate(parsed.token, parsed.organizationSlug) }; } + catch (error) { this.throwFlyAccountError(error); } + } + async saveFlyConnection(input: unknown) { + await this.authorizeOwnerSession("integrations:write"); + const parsed = flyConnectionInput.parse(input); + try { + const metadata = await createFlyAccountClient().validate(parsed.token, parsed.organizationSlug); + return { connection: await this.flyConnections().save(metadata, parsed.token) }; + } catch (error) { this.throwFlyAccountError(error); } + } + async removeFlyConnection() { await this.authorizeOwnerSession("integrations:write"); return { deleted: await this.flyConnections().remove() }; } + private throwFlyAccountError(error: unknown): never { + if (error instanceof FlyAccountError) throw new ServiceError(error.kind === "auth" ? 401 : error.kind === "organization" ? 400 : 502, error.kind === "auth" ? "fly_auth_failed" : error.kind === "organization" ? "fly_organization_unavailable" : "fly_validation_failed", error.message); + throw error; + } async listGitHubInstallations() { await this.authorize("integrations:read"); return publicValue(z.array(githubInstallation), JSON.parse(JSON.stringify(await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations()))); } async listTailIntegrations() { await this.authorize("integrations:read"); return publicValue(z.array(tailIntegration), await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails()); } async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return publicValue(runPageResponse, JSON.parse(JSON.stringify(await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query)))); } diff --git a/packages/api/src/fly-account-client.ts b/packages/api/src/fly-account-client.ts new file mode 100644 index 00000000..0059f80f --- /dev/null +++ b/packages/api/src/fly-account-client.ts @@ -0,0 +1,55 @@ +import { z } from "zod"; + +export const flyConnectionInput = z.object({ + token: z.string().trim().min(1).max(4096).meta({ writeOnly: true }), + organizationSlug: z.string().trim().min(1).max(63).regex(/^[a-z0-9-]+$/), +}).strict(); + +export const flyConnectionMetadata = z.object({ + organizationSlug: z.string(), + organizationName: z.string(), +}); + +export class FlyAccountError extends Error { + constructor(readonly kind: "auth" | "organization" | "unavailable" | "invalid_response") { + super(kind === "auth" ? "Fly authentication failed" : kind === "organization" ? "Fly organization is unavailable to this token" : kind === "unavailable" ? "Fly could not validate the account right now" : "Fly returned an invalid account response"); + this.name = "FlyAccountError"; + } +} + +type FlyAccountOptions = { apiOrigin?: string; timeoutMs?: number; fetch?: typeof fetch }; + +/** Validates an org-scoped Fly token using the documented read-only current-token endpoint. */ +export function createFlyAccountClient(options: FlyAccountOptions = {}) { + const origin = (options.apiOrigin ?? "https://api.machines.dev").replace(/\/$/, ""); + const timeoutMs = options.timeoutMs ?? 5_000; + const fetchImpl = options.fetch ?? fetch; + return { + async validate(token: string, organizationSlug: string): Promise<{ organizationSlug: string; organizationName: string }> { + let response: Response; + try { + response = await fetchImpl(`${origin}/v1/tokens/current`, { + headers: { authorization: `Bearer ${token}`, accept: "application/json" }, + signal: AbortSignal.timeout(timeoutMs), + }); + } catch { + throw new FlyAccountError("unavailable"); + } + if (response.status === 401 || response.status === 403) { + await response.body?.cancel().catch(() => undefined); + throw new FlyAccountError("auth"); + } + if (!response.ok) { + await response.body?.cancel().catch(() => undefined); + throw new FlyAccountError("unavailable"); + } + let body: unknown; + try { body = await response.json(); } catch { throw new FlyAccountError("invalid_response"); } + const parsed = z.object({ tokens: z.array(z.object({ org_slug: z.string(), organization: z.string().optional() }).passthrough()) }).safeParse(body); + if (!parsed.success) throw new FlyAccountError("invalid_response"); + const organization = parsed.data.tokens.find(item => item.org_slug.toLowerCase() === organizationSlug.toLowerCase()); + if (!organization) throw new FlyAccountError("organization"); + return { organizationSlug: organization.org_slug, organizationName: organization.organization?.trim() || organization.org_slug }; + }, + }; +} diff --git a/packages/api/src/postgres/fly-connection-repository.ts b/packages/api/src/postgres/fly-connection-repository.ts new file mode 100644 index 00000000..4e09aee6 --- /dev/null +++ b/packages/api/src/postgres/fly-connection-repository.ts @@ -0,0 +1,38 @@ +import { decrypt, encrypt } from "../crypto"; +import type { Database } from "./database"; + +export type FlyConnection = { organizationSlug: string; organizationName: string }; + +/** Stores one org-scoped provisioning token per tenant, encrypted with the server credential key. */ +export class FlyConnectionRepository { + constructor(private database: Database, private tenantId: string, private serverEncryptionKey: string) { + if (!tenantId) throw new Error("tenantId is required"); + } + + async get(): Promise { + const { rows } = await this.database.pool.query<{ organization_slug: string; organization_name: string }>( + "SELECT organization_slug,organization_name FROM app.fly_connections WHERE tenant_id=$1", [this.tenantId]); + return rows[0] ? { organizationSlug: rows[0].organization_slug, organizationName: rows[0].organization_name } : null; + } + + async save(connection: FlyConnection, token: string): Promise { + const encryptedToken = await encrypt(token, this.serverEncryptionKey); + const { rows } = await this.database.pool.query<{ organization_slug: string; organization_name: string }>( + `INSERT INTO app.fly_connections(tenant_id,organization_slug,organization_name,encrypted_token) + VALUES ($1,$2,$3,$4) + ON CONFLICT (tenant_id) DO UPDATE SET organization_slug=excluded.organization_slug,organization_name=excluded.organization_name,encrypted_token=excluded.encrypted_token,updated_at=now() + RETURNING organization_slug,organization_name`, + [this.tenantId, connection.organizationSlug, connection.organizationName, encryptedToken]); + return { organizationSlug: rows[0]!.organization_slug, organizationName: rows[0]!.organization_name }; + } + + async token(): Promise { + const { rows } = await this.database.pool.query<{ encrypted_token: string }>("SELECT encrypted_token FROM app.fly_connections WHERE tenant_id=$1", [this.tenantId]); + return rows[0] ? decrypt(rows[0].encrypted_token, this.serverEncryptionKey) : null; + } + + async remove(): Promise { + const result = await this.database.pool.query("DELETE FROM app.fly_connections WHERE tenant_id=$1", [this.tenantId]); + return (result.rowCount ?? 0) > 0; + } +} diff --git a/packages/api/test/fly-account-connection.postgres.test.ts b/packages/api/test/fly-account-connection.postgres.test.ts new file mode 100644 index 00000000..b8b4dfbc --- /dev/null +++ b/packages/api/test/fly-account-connection.postgres.test.ts @@ -0,0 +1,101 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { decrypt } from "../src/crypto"; +import { createFlyAccountClient } from "../src/fly-account-client"; +import { FlyConnectionRepository } from "../src/postgres/fly-connection-repository"; +import { protectedApiFetch } from "../src/protected-api"; +import { loadingFixture } from "./helpers/loading-fixture"; +import type { OAuthProps } from "../src/types"; + +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)("Fly account connection (PostgreSQL/API)", () => { + let fixture: Awaited>; + beforeAll(async () => { fixture = await loadingFixture(url!); }); + afterAll(async () => { vi.unstubAllGlobals(); await fixture?.cleanup(); }); + + function request(method: string, auth: OAuthProps, body?: unknown, path = "/api/v1/fly/connection") { + return protectedApiFetch(new Request(fixture.env.APP_ORIGIN + path, { + method, + headers: { Origin: fixture.env.APP_ORIGIN, "Content-Type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }), fixture.env, auth, { waitUntil() {} } as any); + } + + it("enforces one connection per tenant, isolates tenants, and keeps credentials secret-free on reads", async () => { + const first = new FlyConnectionRepository(fixture.db, fixture.tenantId, fixture.env.CREDENTIAL_ENCRYPTION_KEY); + const other = new FlyConnectionRepository(fixture.db, fixture.otherTenant, fixture.env.CREDENTIAL_ENCRYPTION_KEY); + const firstToken = "synthetic-fly-token-one"; + await first.save({ organizationSlug: "alpha", organizationName: "Alpha" }, firstToken); + await first.save({ organizationSlug: "beta", organizationName: "Beta" }, "synthetic-fly-token-two"); + expect(await first.get()).toEqual({ organizationSlug: "beta", organizationName: "Beta" }); + expect(await other.get()).toBeNull(); + expect(await other.remove()).toBe(false); + const rows = await fixture.db.pool.query("SELECT tenant_id,organization_slug,encrypted_token FROM app.fly_connections ORDER BY tenant_id"); + expect(rows.rows.filter(row => row.tenant_id === fixture.tenantId)).toHaveLength(1); + expect(rows.rows.find(row => row.tenant_id === fixture.tenantId)!.encrypted_token).not.toContain("synthetic-fly-token-two"); + expect(await first.token()).toBe("synthetic-fly-token-two"); + expect(await decrypt(rows.rows.find(row => row.tenant_id === fixture.tenantId)!.encrypted_token, fixture.env.CREDENTIAL_ENCRYPTION_KEY)).toBe("synthetic-fly-token-two"); + }); + + it("validates and saves in the browser API without returning the token or creating resources", async () => { + const urls: string[] = []; + vi.stubGlobal("fetch", async (input: RequestInfo | URL) => { + const request = new URL(String(input)); urls.push(request.toString()); + return Response.json({ tokens: [{ org_slug: "alpha", organization: "Alpha Org" }] }); + }); + const auth = { ...fixture.auth, scopes: ["integrations:read", "integrations:write"] }; + const token = "synthetic-fly-secret"; + const validated = await request("POST", auth, { token, organizationSlug: "alpha" }, "/api/v1/fly/connection/test"); + expect(validated.status).toBe(200); + expect(await validated.json()).toEqual({ valid: true, connection: { organizationSlug: "alpha", organizationName: "Alpha Org" } }); + const saved = await request("PUT", auth, { token, organizationSlug: "alpha" }); + expect(saved.status).toBe(200); + expect(JSON.stringify(await saved.json())).not.toContain(token); + const read = await request("GET", auth); + expect(await read.json()).toEqual({ connection: { organizationSlug: "alpha", organizationName: "Alpha Org" } }); + expect(urls).toEqual(["https://api.machines.dev/v1/tokens/current", "https://api.machines.dev/v1/tokens/current"]); + expect((await fixture.db.pool.query("SELECT encrypted_token FROM app.fly_connections WHERE tenant_id=$1", [fixture.tenantId])).rows[0].encrypted_token).not.toContain(token); + }); + + it("denies agent credentials even when integrations:write is granted", async () => { + const agent = { ...fixture.auth, authMethod: "run_token", scopes: ["integrations:write"] } as OAuthProps; + const response = await request("PUT", agent, { token: "secret", organizationSlug: "alpha" }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { code: "session_required" } }); + }); + + it("maps fake-provider authentication and organization failures to sanitized API errors", async () => { + const auth = { ...fixture.auth, scopes: ["integrations:write"] }; + for (const [status, payload, expected] of [ + [401, { error: "rejected synthetic-fly-secret" }, { status: 401, code: "fly_auth_failed", message: "Fly authentication failed" }], + [200, { tokens: [{ org_slug: "other", organization: "Other Org" }] }, { status: 400, code: "fly_organization_unavailable", message: "Fly organization is unavailable to this token" }], + ] as const) { + vi.stubGlobal("fetch", async () => new Response(JSON.stringify(payload), { status, headers: { "Content-Type": "application/json" } })); + const response = await request("POST", auth, { token: "synthetic-fly-secret", organizationSlug: "alpha" }, "/api/v1/fly/connection/test"); + expect(response.status).toBe(expected.status); + const body = await response.json() as any; + expect(body.error).toMatchObject({ code: expected.code, message: expected.message }); + expect(JSON.stringify(body)).not.toContain("synthetic-fly-secret"); + expect(JSON.stringify(body)).not.toContain("rejected"); + } + }); +}); + +describe("Fly account validation errors", () => { + const client = (status: number, body: unknown) => createFlyAccountClient({ + apiOrigin: "https://fly.test", + fetch: async (input, init) => { + expect(String(input)).toBe("https://fly.test/v1/tokens/current"); + expect(new Headers(init?.headers).get("authorization")).toBe("Bearer synthetic-token"); + return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); + }, + }); + it("sanitizes provider authentication and organization errors", async () => { + await expect(client(401, { error: "bad synthetic-token" }).validate("synthetic-token", "alpha")) + .rejects.toMatchObject({ name: "FlyAccountError", kind: "auth", message: "Fly authentication failed" }); + await expect(client(200, { tokens: [{ org_slug: "beta", organization: "Beta" }] }).validate("synthetic-token", "alpha")) + .rejects.toMatchObject({ name: "FlyAccountError", kind: "organization", message: "Fly organization is unavailable to this token" }); + }); +}); diff --git a/packages/api/test/fly-machines-client.test.ts b/packages/api/test/fly-machines-client.test.ts index f422cd8e..bc39fe14 100644 --- a/packages/api/test/fly-machines-client.test.ts +++ b/packages/api/test/fly-machines-client.test.ts @@ -116,10 +116,13 @@ describe("bounded Fly Machines client", () => { it("times out a stalled response and reconciles an ambiguous create by operation id", async () => { const machines: FlyMachine[] = []; let createCount = 0; + let markCreateReceived!: () => void; + const createReceived = new Promise(resolve => { markCreateReceived = resolve; }); const origin = await fakeFly(async (req, res) => { if (req.method === "GET") return json(res, 200, machines); if (req.method === "POST") { createCount++; + markCreateReceived(); let raw = ""; for await (const chunk of req) raw += chunk; const body = JSON.parse(raw); const machine = { id: "m-created", config: body.config }; @@ -129,7 +132,15 @@ describe("bounded Fly Machines client", () => { } }); const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 1_000, maxRetries: 0 }); - const created = await client.createMachine("app", { image: "image" }, "op-ambiguous"); + let deadline: ReturnType | undefined; + let created: FlyMachine; + try { + const creation = client.createMachine("app", { image: "image" }, "op-ambiguous"); + await Promise.race([createReceived, new Promise((_, reject) => { + deadline = setTimeout(() => reject(new Error("Fake Fly server did not receive the ambiguous create")), 5_000); + })]); + created = await creation; + } finally { if (deadline) clearTimeout(deadline); } expect(created.id).toBe("m-created"); expect(createCount).toBe(1); }); diff --git a/packages/app/package.json b/packages/app/package.json index 589757a4..82f68b1b 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -7,7 +7,7 @@ "dev": "vite --host 0.0.0.0", "build": "tsc --noEmit && vite build", "check": "npm run build && npm test && npm run test:functional", - "test": "node --test test/*.test.mjs", + "test": "node --test --test-concurrency=2 test/*.test.mjs", "test:functional": "playwright test --config=playwright.functional.config.mjs", "test:visual": "playwright test --config=playwright.visual.config.mjs" }, diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 01ebe83e..b6d5c57d 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -4117,6 +4117,267 @@ paths: - cookieAuth: [] x-required-scope: integrations:read x-owner-session-required: false + /api/v1/fly/connection: + get: + summary: Read Fly account connection status + description: |- + Owner browser session only. Returns organization metadata and never returns the provisioning token. + + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Connection status + content: + application/json: + schema: + type: object + properties: + connection: + anyOf: + - type: object + properties: + organizationSlug: + type: string + organizationName: + type: string + required: + - organizationSlug + - organizationName + additionalProperties: false + - type: "null" + required: + - connection + 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_fly_connection + tags: + - fly + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + put: + summary: Save a Fly account connection + description: |- + Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org `. A read-only org token is insufficient for provisioning. The server validates the connection and encrypts the token with its credential key; the token is never returned. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Saved connection metadata + content: + application/json: + schema: + type: object + properties: + connection: + type: object + properties: + organizationSlug: + type: string + organizationName: + type: string + required: + - organizationSlug + - organizationName + additionalProperties: false + required: + - connection + 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_fly_connection + tags: + - fly + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + token: + type: string + minLength: 1 + maxLength: 4096 + writeOnly: true + organizationSlug: + type: string + minLength: 1 + maxLength: 63 + pattern: ^[a-z0-9-]+$ + required: + - token + - organizationSlug + additionalProperties: false + delete: + summary: Remove the Fly account connection + description: |- + Owner browser session only. Deletes the tenant's encrypted provisioning token. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Deletion result + content: + application/json: + schema: + type: object + properties: + deleted: + type: boolean + required: + - deleted + 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_fly_connection + tags: + - fly + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + /api/v1/fly/connection/test: + post: + summary: Validate a Fly organization token + description: |- + Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org `. A read-only org token is insufficient for later provisioning. Validation calls Fly's documented read-only current-token endpoint and launches no resources. + + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + responses: + "200": + description: Validated organization + content: + application/json: + schema: + type: object + properties: + valid: + type: boolean + const: true + connection: + type: object + properties: + organizationSlug: + type: string + organizationName: + type: string + required: + - organizationSlug + - organizationName + additionalProperties: false + required: + - valid + - connection + 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_fly_connection_test + tags: + - fly + security: + - bearerAuth: [] + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + token: + type: string + minLength: 1 + maxLength: 4096 + writeOnly: true + organizationSlug: + type: string + minLength: 1 + maxLength: 63 + pattern: ^[a-z0-9-]+$ + required: + - token + - organizationSlug + additionalProperties: false /api/v1/integrations/exe: put: summary: Create an exe.dev integration diff --git a/scripts/validation.mjs b/scripts/validation.mjs index 43c6f466..ddc3df8a 100644 --- a/scripts/validation.mjs +++ b/scripts/validation.mjs @@ -10,7 +10,7 @@ const lanes = { ["generated contracts", "npm", ["run", "generate"], 90_000], ["generated contract drift", "git", ["diff", "--exit-code", "--", "packages/docs/openapi.yaml", "packages/api-client/src/schema.d.ts"], 15_000], ["application build", "npm", ["run", "build", "--workspace=factorize-app"], 90_000], - ["backend checks", "npm", ["run", "check:backend"], 270_000], + ["backend checks", "npm", ["run", "check:backend"], 300_000], ["compiled app/API/PostgreSQL integration", "npm", ["run", "test:static-slice", "--workspace=factorize"], 90_000], ], browser: [