diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index d9c50c31..52c38b6c 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -23,6 +23,8 @@ function harnessCommand(harness: NonNullable): string return [...environment, harness.executable, ...harness.args].map((value, index) => index < environment.length ? value : shellAtom(value)).join(" "); } +export class ExeIntegrationError extends Error {} + export interface ExePermissionTest { ok: boolean; missingPermissions: string[]; tags: string[]; checks: BackendCommandResult[] } export interface ExeAgentValidation { models: string[]; command: BackendCommandResult } @@ -51,6 +53,11 @@ export class ExeVmBackend implements ExecutionBackend { return { body, status: response.status, exitCode, ok: response.ok && (exitCode === null || exitCode === 0), requestBody: command }; } + private validationFailure(message: string, result: BackendCommandResult): ExeIntegrationError { + const detail = safeDiagnosticText(result.body.split(this.connection.apiToken).join("[REDACTED]"), 300); + return new ExeIntegrationError(`${message} (HTTP ${result.status}${result.exitCode === null ? "" : `, exit ${result.exitCode}`}): ${detail}`); + } + async testPermissions(): Promise { const commands = ["ls --json", "integrations list --json", "new --help", "ssh --help", "rm --help"]; const checks = await Promise.all(commands.map(command => this.api(command))); @@ -71,19 +78,20 @@ export class ExeVmBackend implements ExecutionBackend { const vm = vmNameFor(`validate-${crypto.randomUUID()}`); const tags = [...new Set(this.connection.tags)].map(tag => `--tag=${shellAtom(tag)}`).join(" "); const created = await this.api(`new --name=${shellAtom(vm)} --no-email --comment=${shellAtom(`Factorize VM ${vm}`)} ${tags}`.trim()); - if (!created.ok) throw new Error(`Could not create the validation VM (${created.status}): ${created.body.slice(0, 300)}`); + if (!created.ok) throw this.validationFailure("Could not create the validation VM. Check your exe.dev VM capacity and token permissions", created); try { const binary = agentKind; const remote = `command -v ${binary} >/dev/null && curl --fail --silent --show-error https://llm.int.exe.xyz/v1/models | jq -cer '[.data[]?.id | strings] | unique'`; let result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(remote)}`); for (let attempt = 1; !result.ok && attempt < 5; attempt++) result = await this.api(`ssh ${shellAtom(vm)} ${shellAtom(remote)}`); - if (!result.ok) throw new Error(`${binary} or its model integration is unavailable on a VM with these tags (${result.status}): ${result.body.slice(0, 300)}`); - const parsed: unknown = JSON.parse(result.body); - if (!Array.isArray(parsed) || parsed.some(model => typeof model !== "string")) throw new Error("The exe.dev model endpoint returned an invalid response"); + if (!result.ok) throw this.validationFailure(`${binary} or its model integration is unavailable. Check that the agent is installed and the llm integration is attached to VMs with the selected tags`, result); + let parsed: unknown; + try { parsed = JSON.parse(result.body); } catch { throw new ExeIntegrationError("The exe.dev model endpoint returned invalid JSON"); } + if (!Array.isArray(parsed) || parsed.some(model => typeof model !== "string")) throw new ExeIntegrationError("The exe.dev model endpoint returned an invalid response"); return { models: [...new Set(parsed.map(model => model.trim()).filter(Boolean))].sort(), command: result }; } finally { const removed = await this.deleteVm(vm); - if (!removed.ok) throw new Error(`The validation VM could not be deleted (${removed.status}): ${removed.body.slice(0, 300)}`); + if (!removed.ok) throw this.validationFailure(`The validation VM ${vm} could not be deleted. Remove it in exe.dev and check the token rm permission`, removed); } } diff --git a/packages/api/src/postgres/integration-service.ts b/packages/api/src/postgres/integration-service.ts index 487d4c1c..bc02236c 100644 --- a/packages/api/src/postgres/integration-service.ts +++ b/packages/api/src/postgres/integration-service.ts @@ -1,5 +1,5 @@ import { AmpBackend, type AmpConnection } from "../amp-backend"; -import { ExeVmBackend } from "../exe-vm-backend"; +import { ExeIntegrationError, ExeVmBackend } from "../exe-vm-backend"; import type { ExeConnection } from "../exe"; import type { AmpConnectionInput, ExeConnectionInput, TailIntegrationInput } from "../types"; import { signTailDelivery, verifyTailDelivery } from "../cloudflare-tail"; @@ -18,12 +18,17 @@ export class IntegrationService { async saveExe(value: ExeConnectionInput) { const existing = value.connectionId ? await this.connections.get(`exe:${value.connectionId}`) : null; const apiToken = value.apiToken || existing?.apiToken; - if (!apiToken) throw new Error("An exe.dev HTTPS token is required"); + if (!apiToken) throw new ExeIntegrationError("An exe.dev HTTPS token is required"); const tags = Array.isArray(value.tags) ? value.tags.map(String).map(tag => tag.trim()).filter(Boolean) : []; - if (tags.length > 20 || tags.some(tag => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) throw new Error("VM tags are invalid"); + if (tags.length > 20 || tags.some(tag => !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(tag))) throw new ExeIntegrationError("VM tags are invalid"); const candidate: ExeConnection = { apiToken, tags, ...(value.agentKind ? { agentKind: value.agentKind } : {}) }; const backend = new ExeVmBackend(candidate), permissions = await backend.testPermissions(); - if (!permissions.ok) throw new Error(`exe.dev token is missing required permissions: ${permissions.missingPermissions.join(", ")}`); + if (!permissions.ok) { + if (permissions.checks.some(check => check.status === 401)) throw new ExeIntegrationError("exe.dev rejected the account token. Check that it is valid and has not expired."); + if (permissions.missingPermissions.length) throw new ExeIntegrationError(`exe.dev token is missing required permissions: ${permissions.missingPermissions.map(command => command === "integrations" ? "integrations list" : command).join(", ")}`); + const failed = permissions.checks.find(check => !check.ok); + throw new ExeIntegrationError(`exe.dev credential verification failed${failed ? ` for ${failed.requestBody} (HTTP ${failed.status})` : ""}. Try again shortly.`); + } const validation = value.agentKind ? await backend.validateAgentAndModels(value.agentKind) : undefined, connectionId = value.connectionId || crypto.randomUUID(); const saved = { ...candidate, ...(validation ? { models: validation.models, modelsRefreshedAt: timestamp() } : {}) }; await this.connections.put(`exe:${connectionId}`, saved); diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index f2f2496f..a7ec54b7 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -1,3 +1,4 @@ +import { ExeIntegrationError } from "./exe-vm-backend"; import { queryOf } from "./query-params"; import { jobUpdateInput } from "./job-contracts"; import { InvocationError } from "./job-domain"; @@ -13,6 +14,7 @@ import { matchApiOperation } from "./api-contract"; import { normalizeScopes } from "./access-tokens"; function errorResponse(error: unknown): Response { + 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 }); if (error instanceof z.ZodError) return Response.json({ error: { code: "invalid_request", message: "Request validation failed", details: error.issues } }, { status: 400 }); diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index e4fee333..18d5e1f8 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -1,3 +1,4 @@ +import { ExeIntegrationError } from "../src/exe-vm-backend"; import { readFileSync } from "node:fs"; import { afterEach, describe, expect, it, vi } from "vitest"; import { parse } from "yaml"; @@ -359,3 +360,13 @@ describe("Worker OpenAPI request/response boundaries", () => { expect(missing).toHaveBeenCalledWith("missing"); }); }); + + +describe("exe integration validation errors", () => { + it("returns actionable validation failures through the public API", async () => { + vi.spyOn(ApiService.prototype, "saveExeIntegration").mockRejectedValue(new ExeIntegrationError("exe.dev token is missing required permissions: rm")); + const response = await request("PUT", "/api/v1/integrations/exe", { apiToken: "test", agentKind: "codex", tags: [] }); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: { code: "invalid_request", message: "exe.dev token is missing required permissions: rm" } }); + }); +}); diff --git a/packages/api/test/exe-integration.test.ts b/packages/api/test/exe-integration.test.ts new file mode 100644 index 00000000..0b9ee98e --- /dev/null +++ b/packages/api/test/exe-integration.test.ts @@ -0,0 +1,19 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { IntegrationService } from "../src/postgres/integration-service"; +import type { Database } from "../src/postgres/database"; + +afterEach(() => vi.unstubAllGlobals()); + +describe("saving exe integrations", () => { + it.each([ + [401, "exe.dev rejected the account token"], + [403, "integrations list, new, ssh, rm"], + [503, "credential verification failed for ls --json (HTTP 503)"], + ])("explains failed permission checks (HTTP %s) without saving", async (status, message) => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("private upstream output", { status: Number(status) }))); + const service = new IntegrationService({} as Database, "tenant", "key"); + const save = vi.spyOn(service.connections, "put"); + await expect(service.saveExe({ apiToken: "test", agentKind: "codex", tags: [] })).rejects.toThrow(String(message)); + expect(save).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index 8e11795f..d4bd39dc 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -224,3 +224,25 @@ describe("ExecutionBackend contract", () => { expect(await backend.stop(launched.handle)).toEqual({ state: "stopped" }); }); }); + + +describe("exe validation diagnostics", () => { + it("reports VM creation failure without exposing the account token", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("Capacity exhausted secret", { status: 422 }))); + await expect(new ExeVmBackend(connection).validateAgentAndModels("codex")).rejects.toThrow("Capacity exhausted [REDACTED]"); + }); + + it("cleans up the temporary VM when model discovery fails", async () => { + let vm = ""; + const commands: string[] = []; + vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { + const command = String(init.body); commands.push(command); + if (command.startsWith("new ")) { vm = command.match(/--name='([^']+)'/)?.[1] ?? ""; return new Response("created"); } + if (command.startsWith("ssh ")) return new Response("curl: integration unavailable", { status: 422 }); + if (command === "ls --json") return new Response(JSON.stringify({ vms: [{ name: vm, comment: `Factorize VM ${vm}` }] })); + return new Response("removed"); + })); + await expect(new ExeVmBackend(connection).validateAgentAndModels("codex")).rejects.toThrow("llm integration is attached to VMs with the selected tags"); + expect(commands.at(-1)).toBe(`rm '${vm}'`); + }); +});