From 9949453ed42d586470ca7293e33a39c62593369f Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Fri, 27 Nov 2026 13:32:46 -0700 Subject: [PATCH 1/2] Expose the native Hetzner Cloud API through the standard proxy --- packages/api-client/src/schema.d.ts | 8 +- .../application/access-control-service.ts | 2 +- packages/api/src/api-service.ts | 4 +- .../application/agent-credentials.ts | 23 ++- .../storage/hetzner-connection-repository.ts | 6 +- .../src/integrations/api/hetzner-contracts.ts | 12 +- packages/api/src/integrations/api/mcp.ts | 5 +- packages/api/src/integrations/api/rest.ts | 2 +- .../integrations/application/diagnostics.ts | 2 +- .../application/hetzner-client-key.ts | 43 +++++ .../application/hetzner-inventory.ts | 8 +- .../application/hetzner-provision.ts | 87 ---------- .../integrations/application/hetzner-ssh.ts | 7 - .../integrations/providers/hetzner-cloud.ts | 38 +--- .../storage/hetzner-server-requests.ts | 40 +---- .../api/src/proxy/application/agent-api.ts | 25 ++- .../src/proxy/application/proxy-operations.ts | 1 + .../transport/credential-backed-egress.ts | 8 +- .../api/src/transport/mcp/mcp-oauth-scopes.ts | 1 + .../test/hetzner-inventory.postgres.test.ts | 12 +- .../test/hetzner-provision.postgres.test.ts | 116 ------------- .../api/test/hetzner-proxy.postgres.test.ts | 163 ++++++++++++++++++ .../hetzner-ssh-enrollment.postgres.test.ts | 4 +- .../src/features/integrations/hetzner-ssh.tsx | 4 +- .../app/src/features/integrations/hetzner.tsx | 18 +- packages/app/test/functional/hetzner.spec.mjs | 14 +- packages/docs/integrations/oauth.mdx | 86 ++++----- packages/docs/llms-full.txt | 96 +++++------ packages/docs/mcp/tools.mdx | 2 - packages/docs/openapi.yaml | 8 +- 30 files changed, 387 insertions(+), 458 deletions(-) create mode 100644 packages/api/src/integrations/application/hetzner-client-key.ts delete mode 100644 packages/api/src/integrations/application/hetzner-provision.ts delete mode 100644 packages/api/test/hetzner-provision.postgres.test.ts create mode 100644 packages/api/test/hetzner-proxy.postgres.test.ts diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 12a0e4c8..0f9e736a 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1730,7 +1730,7 @@ export interface paths { get: operations["get_api_v1_hetzner_connection"]; /** * Save a Hetzner Cloud project connection - * @description Owner browser session only. Supply a project API token with Read permission, or Read & Write only when enabling server provisioning. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources. + * @description Owner browser session only. Supply a project API token with Read permission, or Read & Write only when explicitly enabling native API writes through the proxy. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources. * * Requires the integrations:write scope. * @@ -6940,7 +6940,7 @@ export interface operations { "application/json": { connection: { name: string; - provisioningEnabled?: boolean; + nativeWritesEnabled?: boolean; } | null; }; }; @@ -6966,7 +6966,7 @@ export interface operations { content: { "application/json": { name: string; - provisioningEnabled?: boolean; + nativeWritesEnabled?: boolean; token: string; }; }; @@ -6981,7 +6981,7 @@ export interface operations { "application/json": { connection: { name: string; - provisioningEnabled?: boolean; + nativeWritesEnabled?: boolean; }; }; }; diff --git a/packages/api/src/access-control/application/access-control-service.ts b/packages/api/src/access-control/application/access-control-service.ts index f9bfd817..e24772d2 100644 --- a/packages/api/src/access-control/application/access-control-service.ts +++ b/packages/api/src/access-control/application/access-control-service.ts @@ -141,7 +141,7 @@ export class AccessControlService { const globallyAvailable = [...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)]; const liveScopes = new Set(integrations.filter(row => row.kind === "hetzner" && row.available && row.policy !== "disabled").map(row => row.requiredScope)); const scopeLabels = Object.fromEntries(integrations.map(row => [row.requiredScope, - row.kind === "hetzner" ? "Hetzner Cloud (inventory, enrolled SSH, and provisioning if enabled)" : `${row.name} integration access`])); + row.kind === "hetzner" ? "Hetzner Cloud (native API and enrolled SSH)" : `${row.name} integration access`])); return publicValue(z.array(authorizedClient), rows.map(row => { const appName = byId.get(row.client_id)?.clientName ?? row.client_id; const inactive = (row.active_expires_at !== null && row.active_expires_at.getTime() <= Date.now()) || row.active_session_version !== this.auth.sessionVersion; diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 79a56f1a..66d6a8ac 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,4 +1,4 @@ -import { HetznerProvisionService } from "./integrations/application/hetzner-provision"; +import { HetznerClientKeyService } from "./integrations/application/hetzner-client-key"; import { AwsIntegrationService } from "./integrations/application/aws-service"; import { HetznerSshService } from "./integrations/application/hetzner-ssh"; import { ProxyService } from "./proxy/application/proxy-service"; @@ -47,7 +47,7 @@ export class ApiService { get integrations() { return new IntegrationsService(this.env, this.auth, scope => this.authorize(scope), scope => this.authorizeOwnerSession(scope)); } - get hetznerProvision() { return new HetznerProvisionService(this.env, this.auth); } + get hetznerKeys() { return new HetznerClientKeyService(this.env, this.auth); } get hetznerSsh() { return new HetznerSshService(this.env, this.auth, scope => this.authorizeOwnerSession(scope)); } diff --git a/packages/api/src/credentials/application/agent-credentials.ts b/packages/api/src/credentials/application/agent-credentials.ts index 805d234e..10c86298 100644 --- a/packages/api/src/credentials/application/agent-credentials.ts +++ b/packages/api/src/credentials/application/agent-credentials.ts @@ -1,3 +1,5 @@ +import { HetznerConnectionRepository } from "../storage/hetzner-connection-repository"; +import { AgentApiError } from "../../proxy/api/agent-api-error"; import { appConfig, signingConfig } from "../../config/runtime"; import { cloudflareCredential } from "../../integrations/providers/cloudflare-oauth"; import type { Env } from "../../types"; @@ -11,9 +13,28 @@ import { FlyConnectionRepository } from "../storage/fly-connection-repository"; import { isPublicHttpsOrigin } from "../../proxy/transport/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 { +export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string, method: string): Promise { if (kind === "cloudflare") return cloudflareCredential(env, tenantId, credentialId, relativePath); const database = databaseFor(env); + if (kind === "hetzner") { + if (credentialId !== "hetzner") return null; + const origin = "https://api.hetzner.cloud"; + const rawPath = relativePath.split("?", 1)[0]!; + if (!rawPath.startsWith("/") || rawPath.startsWith("//") || /%2f|%5c|%25/i.test(rawPath) || /[\\\s\0#]/.test(relativePath)) { + throw new AgentApiError(400, "invalid_request", "Use a relative Hetzner Cloud /v1/ API path."); + } + const target = new URL(relativePath, origin); + if (target.origin !== origin || !target.pathname.startsWith("/v1/")) { + throw new AgentApiError(400, "invalid_request", "Use a relative Hetzner Cloud /v1/ API path."); + } + const project = await new HetznerConnectionRepository(database, tenantId, signingConfig(env).credentialKey).get(); + if (!project) return null; + if (method !== "GET" && method !== "HEAD" && project.nativeWritesEnabled !== true) { + throw new AgentApiError(403, "hetzner_native_writes_disabled", "The owner has not enabled native Hetzner Cloud API writes."); + } + return { origin, path: target.pathname + target.search, credential: project.token, + requestHeaders: ["accept", "content-type", "if-match", "if-none-match"] }; + } if (kind === "fly") { if (credentialId !== "fly") return null; const token = await new FlyConnectionRepository(database, tenantId, signingConfig(env).credentialKey).token(); diff --git a/packages/api/src/credentials/storage/hetzner-connection-repository.ts b/packages/api/src/credentials/storage/hetzner-connection-repository.ts index 790c6a62..fac9ff87 100644 --- a/packages/api/src/credentials/storage/hetzner-connection-repository.ts +++ b/packages/api/src/credentials/storage/hetzner-connection-repository.ts @@ -2,7 +2,7 @@ import { decrypt, encrypt } from "../../crypto"; import { lockIntegrationTopology } from "../../integrations/storage/integration-removal-topology"; import type { Database, DatabaseClient } from "../../postgres/database"; -export type HetznerProject = { name: string; token: string; revision: string; provisioningEnabled?: boolean }; +export type HetznerProject = { name: string; token: string; revision: string; nativeWritesEnabled?: boolean }; export class HetznerConnectionRepository { constructor(private database: Database, private tenantId: string, private encryptionKey: string) { @@ -16,8 +16,8 @@ export class HetznerConnectionRepository { return rows[0] ? JSON.parse(await decrypt(rows[0].encrypted_value, this.encryptionKey)) as HetznerProject : null; } - async save(name: string, token: string, provisioningEnabled = false) { - const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID(), provisioningEnabled }), this.encryptionKey); + async save(name: string, token: string, nativeWritesEnabled = false) { + const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID(), nativeWritesEnabled }), this.encryptionKey); await this.database.transaction(async client => { await lockIntegrationTopology(client, this.tenantId); const hadProject = Boolean(await this.get(client)); diff --git a/packages/api/src/integrations/api/hetzner-contracts.ts b/packages/api/src/integrations/api/hetzner-contracts.ts index fe659211..2580b463 100644 --- a/packages/api/src/integrations/api/hetzner-contracts.ts +++ b/packages/api/src/integrations/api/hetzner-contracts.ts @@ -2,10 +2,10 @@ import { z } from "zod"; export const hetznerConnectionInput = z.strictObject({ name: z.string().trim().min(1).max(120), - provisioningEnabled: z.boolean().optional(), + nativeWritesEnabled: z.boolean().optional(), token: z.string().trim().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/).meta({ writeOnly: true }), }); -export const hetznerConnectionMetadata = z.object({ name: z.string(), provisioningEnabled: z.boolean().optional() }); +export const hetznerConnectionMetadata = z.object({ name: z.string(), nativeWritesEnabled: z.boolean().optional() }); export const hetznerServer = z.object({ id: z.number().int().positive(), name: z.string().min(1).max(255), @@ -13,11 +13,3 @@ export const hetznerServer = z.object({ location: z.string().min(1).max(64).nullable(), }); export const hetznerInventory = z.object({ servers: z.array(hetznerServer).max(100), truncated: z.boolean() }); - -export const hetznerCreateInput = z.strictObject({ - requestId: z.uuid(), - name: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,46}[a-z0-9])?$/), - serverType: z.enum(["cx23", "cpx22", "cax11"]), - location: z.enum(["fsn1", "nbg1", "hel1", "ash", "hil", "sin"]), -}); -export type HetznerCreateInput = z.infer; diff --git a/packages/api/src/integrations/api/mcp.ts b/packages/api/src/integrations/api/mcp.ts index 63c365c1..a9e25001 100644 --- a/packages/api/src/integrations/api/mcp.ts +++ b/packages/api/src/integrations/api/mcp.ts @@ -1,4 +1,3 @@ -import { hetznerCreateInput, type HetznerCreateInput } from "./hetzner-contracts"; import { awsCodeInput } from "./aws-contracts"; import { hetznerSshToolInput } from "./hetzner-ssh-contracts"; import { z } from "zod"; @@ -19,9 +18,7 @@ export const tailTools = [ export const hetznerTools = [ - mcpTool(null, "list_hetzner_servers", "List server inventory for a connected Hetzner project whose access is granted to this client.", z.strictObject({}), service => () => service.hetznerSsh.inventoryAsClient()), - mcpTool(null, "get_hetzner_ssh_public_key", "Get this authorized OAuth installation’s public SSH key. The owner must install it on existing servers; the private key is never returned.", z.strictObject({}), service => () => service.hetznerProvision.publicKey()), - mcpTool(null, "create_hetzner_server", "Create one small Hetzner Cloud server only when the owner enabled provisioning. This can incur charges. Provide an intentionally chosen name and a stable requestId. Retrying the same request only checks its outcome. Requires an owner-verified host fingerprint before SSH.", hetznerCreateInput, service => input => service.hetznerProvision.create(input)), + mcpTool(null, "get_hetzner_ssh_public_key", "Get this authorized OAuth installation’s public SSH key. The owner must install it on existing servers; the private key is never returned.", z.strictObject({}), service => () => service.hetznerKeys.publicKey()), mcpTool(null, "check_hetzner_ssh", "Check SSH access for one owner-enrolled Hetzner Cloud server. Uses the pinned host identity and a Factorize-held credential. Proves fresh key authentication; no SSH channel, commands or remote output.", hetznerSshToolInput, service => (input: {serverId: number}) => service.hetznerSsh.checkAsClient(input.serverId)), ]; diff --git a/packages/api/src/integrations/api/rest.ts b/packages/api/src/integrations/api/rest.ts index 06b4f702..cb5e7122 100644 --- a/packages/api/src/integrations/api/rest.ts +++ b/packages/api/src/integrations/api/rest.ts @@ -213,7 +213,7 @@ export const integrationRoutes = [ }, service => service.integrations.getHetznerConnection(), { ownerSession: true }), route("PUT", "/api/v1/hetzner/connection", "integrations:write", { summary: "Save a Hetzner Cloud project connection", - description: "Owner browser session only. Supply a project API token with Read permission, or Read & Write only when enabling server provisioning. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources.", + description: "Owner browser session only. Supply a project API token with Read permission, or Read & Write only when explicitly enabling native API writes through the proxy. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources.", responses: { "200": { description: "Saved connection metadata", content: { "application/json": { schema: jsonSchema(z.object({ connection: hetznerConnectionMetadata }), "output") } } } }, }, (service, { body }) => service.integrations.saveHetznerConnection(body), { body: hetznerConnectionInput, ownerSession: true, maxBodyBytes: 4096 }), route("DELETE", "/api/v1/hetzner/connection", "integrations:write", { diff --git a/packages/api/src/integrations/application/diagnostics.ts b/packages/api/src/integrations/application/diagnostics.ts index 999cb4c1..0f70ba03 100644 --- a/packages/api/src/integrations/application/diagnostics.ts +++ b/packages/api/src/integrations/application/diagnostics.ts @@ -1,7 +1,7 @@ import type { HetznerFailure } from "../providers/hetzner-cloud"; type Diagnostic = - | { provider: "hetzner"; operation: "validate_token" | "list_servers" | "lookup_server" | "provision_server"; + | { provider: "hetzner"; operation: "validate_token" | "list_servers" | "lookup_server"; reason: HetznerFailure; upstreamStatus?: number } | { provider: "aws"; operation: "list_connections" | "prepare_connection" | "download_template" | "verify_role"; diff --git a/packages/api/src/integrations/application/hetzner-client-key.ts b/packages/api/src/integrations/application/hetzner-client-key.ts new file mode 100644 index 00000000..571939c3 --- /dev/null +++ b/packages/api/src/integrations/application/hetzner-client-key.ts @@ -0,0 +1,43 @@ +import { signingConfig } from "../../config/runtime"; +import { HetznerClientKeyRepository } from "../../credentials/storage/hetzner-client-key-repository"; +import { HetznerConnectionRepository } from "../../credentials/storage/hetzner-connection-repository"; +import { databaseFor, type DatabaseClient } from "../../postgres/database"; +import { ServiceError } from "../../service-contract"; +import type { Env, OAuthProps } from "../../types"; +import { generateHetznerSshKey } from "../providers/hetzner-ssh-transport"; +import { lockIntegrationTopology } from "../storage/integration-removal-topology"; +import { activeHetznerScope } from "./hetzner-access"; + +export class HetznerClientKeyService { + constructor(private env: Env, private auth: OAuthProps) {} + private get database() { return databaseFor(this.env); } + private get projects() { return new HetznerConnectionRepository(this.database, this.auth.tenantId, signingConfig(this.env).credentialKey); } + private get keys() { return new HetznerClientKeyRepository(this.auth.tenantId, signingConfig(this.env).credentialKey); } + + private async authority(sql: DatabaseClient) { + const { authMethod, oauthInstallationId, oauthGrantId, oauthExpiresAt, tenantId, userId, sessionVersion } = this.auth; + const forbidden = new ServiceError(403, "hetzner_not_authorized", "This client does not have Hetzner access."); + if (authMethod !== "oauth" || !oauthInstallationId || !oauthGrantId || !Number.isFinite(oauthExpiresAt)) throw forbidden; + const current = await activeHetznerScope(sql, { tenantId, userId, sessionVersion, installationId: oauthInstallationId, grantId: oauthGrantId, expiresAt: oauthExpiresAt! }); + if (!current) throw forbidden; + const { rowCount } = await sql.query( + `SELECT 1 FROM app.members m JOIN app.auth_users u ON u.id=m.user_id + WHERE m.tenant_id=$1 AND m.user_id=$2 AND m.role='owner' AND m.session_version=$3 AND u.email_verified`, + [tenantId, userId, sessionVersion], + ); + if (!rowCount) throw forbidden; + return oauthInstallationId; + } + + async publicKey() { + return this.database.transaction(async sql => { + await lockIntegrationTopology(sql, this.auth.tenantId); + const installationId = await this.authority(sql); + if (!await this.projects.get(sql)) throw new ServiceError(404, "hetzner_not_connected", "Connect a Hetzner Cloud project first."); + const { publicKey } = await this.keys.getOrCreate(sql, installationId, generateHetznerSshKey); + return { publicKey, authorizedKeysEntry: `restrict,command="/bin/true" ${publicKey}`, + notice: "An owner must install the complete restricted key line on an existing server. Do not install it as root." }; + }); + } + +} diff --git a/packages/api/src/integrations/application/hetzner-inventory.ts b/packages/api/src/integrations/application/hetzner-inventory.ts index 35871b81..47c34d06 100644 --- a/packages/api/src/integrations/application/hetzner-inventory.ts +++ b/packages/api/src/integrations/application/hetzner-inventory.ts @@ -9,16 +9,16 @@ export class HetznerInventoryService { async connection() { const project = await this.connections.get(); - return { connection: project ? { name: project.name, ...(project.provisioningEnabled ? { provisioningEnabled: true } : {}) } : null }; + return { connection: project ? { name: project.name, ...(project.nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } : null }; } async connectionRevision() { return (await this.connections.get())?.revision ?? null; } async save(input: unknown) { - const { name, token, provisioningEnabled = false } = hetznerConnectionInput.parse(input); + const { name, token, nativeWritesEnabled = false } = hetznerConnectionInput.parse(input); await this.withProviderError("validate_token", () => createHetznerCloudClient().validate(token)); - await this.connections.save(name, token, provisioningEnabled); - return { connection: { name, ...(provisioningEnabled ? { provisioningEnabled: true } : {}) } }; + await this.connections.save(name, token, nativeWritesEnabled); + return { connection: { name, ...(nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } }; } async delete() { return { deleted: await this.connections.delete() }; } diff --git a/packages/api/src/integrations/application/hetzner-provision.ts b/packages/api/src/integrations/application/hetzner-provision.ts deleted file mode 100644 index 6337563e..00000000 --- a/packages/api/src/integrations/application/hetzner-provision.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { signingConfig } from "../../config/runtime"; -import { HetznerClientKeyRepository } from "../../credentials/storage/hetzner-client-key-repository"; -import { HetznerConnectionRepository } from "../../credentials/storage/hetzner-connection-repository"; -import { databaseFor, type DatabaseClient } from "../../postgres/database"; -import { ServiceError } from "../../service-contract"; -import type { Env, OAuthProps } from "../../types"; -import type { HetznerCreateInput } from "../api/hetzner-contracts"; -import { createHetznerCloudClient, HetznerCloudError } from "../providers/hetzner-cloud"; -import { generateHetznerSshKey } from "../providers/hetzner-ssh-transport"; -import { HetznerServerRequests } from "../storage/hetzner-server-requests"; -import { lockIntegrationTopology } from "../storage/integration-removal-topology"; -import { activeHetznerScope } from "./hetzner-access"; -import { reportIntegrationFailure } from "./diagnostics"; - -export class HetznerProvisionService { - constructor(private env: Env, private auth: OAuthProps) {} - private get database() { return databaseFor(this.env); } - private get projects() { return new HetznerConnectionRepository(this.database, this.auth.tenantId, signingConfig(this.env).credentialKey); } - private get keys() { return new HetznerClientKeyRepository(this.auth.tenantId, signingConfig(this.env).credentialKey); } - private get requests() { return new HetznerServerRequests(this.auth.tenantId, this.auth.userId); } - - private async authority(sql: DatabaseClient) { - const { authMethod, oauthInstallationId, oauthGrantId, oauthExpiresAt, tenantId, userId, sessionVersion } = this.auth; - const forbidden = new ServiceError(403, "hetzner_not_authorized", "This client does not have Hetzner access."); - if (authMethod !== "oauth" || !oauthInstallationId || !oauthGrantId || !Number.isFinite(oauthExpiresAt)) throw forbidden; - const current = await activeHetznerScope(sql, { tenantId, userId, sessionVersion, installationId: oauthInstallationId, grantId: oauthGrantId, expiresAt: oauthExpiresAt! }); - if (!current) throw forbidden; - const { rowCount } = await sql.query( - `SELECT 1 FROM app.members m JOIN app.auth_users u ON u.id=m.user_id - WHERE m.tenant_id=$1 AND m.user_id=$2 AND m.role='owner' AND m.session_version=$3 AND u.email_verified`, - [tenantId, userId, sessionVersion], - ); - if (!rowCount) throw forbidden; - return oauthInstallationId; - } - - async publicKey() { - return this.database.transaction(async sql => { - await lockIntegrationTopology(sql, this.auth.tenantId); - const installationId = await this.authority(sql); - if (!await this.projects.get(sql)) throw new ServiceError(404, "hetzner_not_connected", "Connect a Hetzner Cloud project first."); - const { publicKey } = await this.keys.getOrCreate(sql, installationId, generateHetznerSshKey); - return { publicKey, authorizedKeysEntry: `restrict,command="/bin/true" ${publicKey}`, - notice: "An owner must install the complete restricted key line on an existing server. Do not install it as root." }; - }); - } - - async create(input: HetznerCreateInput) { - const { project, ticket, dispatch, serverId, publicKey } = await this.database.transaction(async sql => { - await lockIntegrationTopology(sql, this.auth.tenantId); - const installationId = await this.authority(sql); - const project = await this.projects.get(sql); - if (!project?.provisioningEnabled) throw new ServiceError(403, "hetzner_provisioning_disabled", "The owner has not enabled server provisioning for this Hetzner Cloud project."); - const request = await this.requests.reserve(sql, installationId, project.revision, input); - const { publicKey } = await this.keys.getOrCreate(sql, installationId, generateHetznerSshKey); - return { project, ...request, publicKey }; - }); - const recheck = async () => { - await this.authority(this.database.pool); - if ((await this.projects.get())?.revision !== project.revision) { - throw new ServiceError(409, "hetzner_connection_changed", "The Hetzner project changed."); - } - }; - - let id = serverId; - if (id === null) { - // A durable reservation permits exactly one POST. Repeated calls can only look up the ticket. - const client = createHetznerCloudClient(); - await recheck(); - const started = performance.now(); - try { - id = dispatch ? await client.create(project.token, input, ticket, publicKey) : await client.reconcile(project.token, input.name, ticket); - } catch (error) { - if (!(error instanceof HetznerCloudError)) throw error; - const requestId = reportIntegrationFailure({ provider: "hetzner", operation: "provision_server", reason: error.reason, upstreamStatus: error.upstreamStatus }, started, error.kind !== "auth"); - if (error.kind === "auth") throw new ServiceError(422, "hetzner_provisioning_token_rejected", "Hetzner rejected the project token. Provisioning needs a project token with Read & Write permission.", requestId); - throw new ServiceError(502, "hetzner_create_unconfirmed", "Hetzner did not confirm this server request. Check the project or repeat the same request ID to reconcile without creating another server.", requestId); - } - if (id !== null) await this.requests.complete(this.database.pool, ticket, id); - } - await recheck(); - return id === null ? { state: "unconfirmed" as const, requestId: input.requestId, - notice: "No matching server is visible yet. Reuse this request ID to reconcile; Factorize will not send another create request." } : - { state: "created" as const, requestId: input.requestId, serverId: id, name: input.name, - ssh: "owner_pin_required" as const, notice: "Hetzner accepted the server. The client key is configured at first boot. Before SSH checks, an owner must verify the host fingerprint from a trusted console." }; - } -} diff --git a/packages/api/src/integrations/application/hetzner-ssh.ts b/packages/api/src/integrations/application/hetzner-ssh.ts index a1aed33f..624f939b 100644 --- a/packages/api/src/integrations/application/hetzner-ssh.ts +++ b/packages/api/src/integrations/application/hetzner-ssh.ts @@ -105,13 +105,6 @@ export class HetznerSshService { return this.check(serverId, await this.clientAuthority()); } - async inventoryAsClient() { - await this.clientAuthority(); - const inventory = await new HetznerInventoryService(this.projects).inventory(); - await this.clientAuthority(); - return inventory; - } - private async clientAuthority() { const { authMethod, oauthInstallationId, oauthGrantId, oauthExpiresAt, tenantId, userId, sessionVersion } = this.auth; const forbidden = () => new ServiceError(403, "hetzner_not_authorized", "This client does not have Hetzner access."); diff --git a/packages/api/src/integrations/providers/hetzner-cloud.ts b/packages/api/src/integrations/providers/hetzner-cloud.ts index 5bae6ebf..3d56f8ed 100644 --- a/packages/api/src/integrations/providers/hetzner-cloud.ts +++ b/packages/api/src/integrations/providers/hetzner-cloud.ts @@ -1,4 +1,3 @@ -import type { HetznerCreateInput } from "../api/hetzner-contracts"; import { fetchWithoutRedirects, OutboundRedirectError } from "../../transport/http/fetch-without-redirects"; import { z } from "zod"; @@ -6,7 +5,6 @@ const origin = "https://api.hetzner.cloud"; const pageSize = 25; const maxPages = 4; export const provisionedSshUser = "factorize-agent"; -const provisionLabel = "factorize-request"; const maxPageBytes = 512 * 1024; const serverPage = z.object({ @@ -19,10 +17,6 @@ const serverPage = z.object({ meta: z.object({ pagination: z.object({ next_page: z.number().int().positive().nullable() }) }), }); -const provisionedServer = z.object({id: z.number().int().positive(), name: z.string(), labels: z.record(z.string(), z.string())}); -const provisionResponse = z.object({server: provisionedServer}); -const reconciliationResponse = z.object({servers: z.array(provisionedServer).max(2)}); - const targetResponse = z.object({ server: z.object({ id: z.number().int().positive(), public_net: z.object({ ipv4: z.object({ ip: z.ipv4() }).nullable() }), @@ -70,13 +64,12 @@ async function readJson(response: Response): Promise { /** No caller-controlled origin, method, headers, or URL. */ export function createHetznerCloudClient(fetchImpl: typeof fetch = fetch) { - async function request(url: URL, token: string, signal: AbortSignal, data?: unknown) { + async function request(url: URL, token: string, signal: AbortSignal) { let response: Response; try { response = await fetchWithoutRedirects(url, { - method: data === undefined ? "GET" : "POST", - headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(data === undefined ? {} : { "content-type": "application/json" }) }, - ...(data === undefined ? {} : { body: JSON.stringify(data) }), signal, + method: "GET", headers: { authorization: `Bearer ${token}`, accept: "application/json" }, + signal, }, fetchImpl); } catch (error) { if (error instanceof OutboundRedirectError) throw new HetznerCloudError("unavailable", "unexpected_status", error.status); @@ -123,31 +116,6 @@ export function createHetznerCloudClient(fetchImpl: typeof fetch = fetch) { } return { servers, truncated: next !== null }; }, - async create(token: string, input: HetznerCreateInput, ticket: string, publicKey: string) { - // Do not pass ssh_keys to the API: the key belongs to a dedicated user, not root. - const config = { disable_root: true, ssh_pwauth: false, allow_public_ssh_keys: false, ssh_genkeytypes: ["ed25519"], users: [{ - name: provisionedSshUser, shell: "/bin/sh", lock_passwd: true, sudo: null, - ssh_authorized_keys: [`restrict,command="/bin/true" ${publicKey}`], - }] }; - const body = { name: input.name, server_type: input.serverType, location: input.location, image: "ubuntu-24.04", - start_after_create: true, public_net: { enable_ipv4: true, enable_ipv6: false }, - labels: { [provisionLabel]: ticket }, user_data: "#cloud-config\n" + JSON.stringify(config) + "\n" }; - const reply = provisionResponse.safeParse(await request(new URL("/v1/servers", origin), token, AbortSignal.timeout(8_000), body)); - const server = reply.success ? reply.data.server : null; - if (!server || server.name !== input.name || server.labels[provisionLabel] !== ticket) throw new HetznerCloudError("invalid_response"); - return server.id; - }, - async reconcile(token: string, name: string, ticket: string) { - const url = new URL("/v1/servers", origin); - url.searchParams.set("label_selector", `${provisionLabel}=${ticket}`); - url.searchParams.set("name", name); - url.searchParams.set("per_page", "2"); - const reply = reconciliationResponse.safeParse(await request(url, token, AbortSignal.timeout(5_000))); - if (!reply.success || reply.data.servers.length > 1) throw new HetznerCloudError("invalid_response"); - const server = reply.data.servers[0]; - if (server && (server.name !== name || server.labels[provisionLabel] !== ticket)) throw new HetznerCloudError("invalid_response"); - return server?.id ?? null; - }, /** Internal provider lookup. IPs are never included in inventory responses. */ async target(token: string, id: number) { if (!Number.isSafeInteger(id) || id < 1) throw new HetznerCloudError("not_found"); diff --git a/packages/api/src/integrations/storage/hetzner-server-requests.ts b/packages/api/src/integrations/storage/hetzner-server-requests.ts index b4b0e7d5..accf8f76 100644 --- a/packages/api/src/integrations/storage/hetzner-server-requests.ts +++ b/packages/api/src/integrations/storage/hetzner-server-requests.ts @@ -1,47 +1,9 @@ import type { DatabaseClient } from "../../postgres/database"; -import { ServiceError } from "../../service-contract"; -import type { HetznerCreateInput } from "../api/hetzner-contracts"; - -type RequestRow = { project_revision: string; ticket: string; name: string; server_type: string; location: string; server_id: string | null }; +// Preserve the exact key binding for servers created by the retired typed workflow. export class HetznerServerRequests { constructor(private tenantId: string, private ownerId: string) {} private get owner() { return [this.tenantId, this.ownerId]; } - - /** Call while holding the integration topology transaction lock. */ - async reserve(sql: DatabaseClient, installationId: string, revision: string, input: HetznerCreateInput) { - const [state] = (await sql.query( - "SELECT project_revision,ticket,name,server_type,location,server_id FROM app.hetzner_server_requests WHERE tenant_id=$1 AND owner_id=$2 AND installation_id=$3 AND request_id=$4", - [...this.owner, installationId, input.requestId], - )).rows; - if (state) { - if (state.project_revision !== revision || state.name !== input.name || state.server_type !== input.serverType || state.location !== input.location) { - throw new ServiceError(409, "hetzner_request_conflict", "This request ID was already used with other settings."); - } - return { ticket: state.ticket, serverId: state.server_id === null ? null : Number(state.server_id), dispatch: false }; - } - const counts = (await sql.query<{total: number; daily: number}>( - `SELECT count(*)::int AS total, count(*) FILTER (WHERE created_at>now()-interval '24 hours')::int AS daily - FROM app.hetzner_server_requests WHERE tenant_id=$1 AND project_revision=$2`, [this.tenantId, revision], - )).rows[0]!; - if (counts.total >= 20 || counts.daily >= 3) { - throw new ServiceError(429, "hetzner_create_limit", "This connection has reached its bounded Factorize provisioning limit."); - } - const ticket = crypto.randomUUID(); - const result = await sql.query( - `INSERT INTO app.hetzner_server_requests(tenant_id,owner_id,installation_id,request_id,project_revision,ticket,name,server_type,location) - VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (tenant_id,project_revision,name) DO NOTHING`, - [...this.owner, installationId, input.requestId, revision, ticket, input.name, input.serverType, input.location], - ); - if (!result.rowCount) throw new ServiceError(409, "hetzner_name_reserved", "This project already has a Factorize request for that name."); - return { ticket, serverId: null, dispatch: true }; - } - - async complete(sql: DatabaseClient, ticket: string, serverId: number) { - await sql.query("UPDATE app.hetzner_server_requests SET server_id=$4 WHERE tenant_id=$1 AND owner_id=$2 AND ticket=$3 AND (server_id IS NULL OR server_id=$4)", - [...this.owner, ticket, serverId]); - } - async installation(sql: DatabaseClient, revision: string, serverId: number) { return (await sql.query<{installation_id: string}>( "SELECT installation_id FROM app.hetzner_server_requests WHERE tenant_id=$1 AND owner_id=$2 AND project_revision=$3 AND server_id=$4", diff --git a/packages/api/src/proxy/application/agent-api.ts b/packages/api/src/proxy/application/agent-api.ts index c218981d..4b6a9930 100644 --- a/packages/api/src/proxy/application/agent-api.ts +++ b/packages/api/src/proxy/application/agent-api.ts @@ -1,3 +1,4 @@ +import { activeHetznerScope } from "../../integrations/application/hetzner-access"; import { proxyLimits } from "../../config/limits"; import { appConfig } from "../../config/runtime"; import { CredentialBackedEgress } from "../transport/credential-backed-egress"; @@ -26,7 +27,7 @@ import type { z } from "zod"; const STORAGE_BLOCK_BYTES = proxyLimits.artifactBlockBytes; 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, credentialId: row.credential_id, name: row.name, description: row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) }); +const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.kind === "hetzner" ? "Native Hetzner Cloud project API, with owner-controlled write access." : 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[]) { @@ -79,7 +80,16 @@ export class AgentApiService { 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 || row.kind === "hetzner" || row.policy==="disabled") throw forbidden(); + if (!row || row.policy === "disabled") throw forbidden(); + if (row.kind === "hetzner") { + const { tenantId, userId, sessionVersion, oauthInstallationId, oauthGrantId, oauthExpiresAt } = this.auth; + if (identity.kind !== "oauth" || row.credential_id !== "hetzner" || !oauthInstallationId || !oauthGrantId || + typeof oauthExpiresAt !== "number" || await activeHetznerScope(this.database.pool, { tenantId, userId, sessionVersion, + installationId: oauthInstallationId, grantId: oauthGrantId, expiresAt: oauthExpiresAt }) !== requiredIntegrationScope(row)) { + throw forbidden(); + } + return { identity, integration: row }; + } if (identity.kind === "vm" && (!row.available || !identity.scopes.includes(requiredIntegrationScope(row)))) throw forbidden(); const access = connectionAccess(row, identity.scopes, identity.policy, identity.explicit || this.auth.explicitIntegrationScopes); if (access === "blocked") throw forbidden(); @@ -91,18 +101,16 @@ export class AgentApiService { 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) { - // Hetzner is surfaced in permission settings and by its typed MCP tools, - // never as a generic request_api destination. - if (row.kind === "hetzner" || row.policy === "disabled" || (identity.kind === "vm" && !identity.scopes.includes(requiredIntegrationScope(row)))) continue; + if (row.policy === "disabled" || (identity.kind === "vm" && (row.kind === "hetzner" || !identity.scopes.includes(requiredIntegrationScope(row))))) 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"; } - const path = row.kind === "linear" ? "/graphql" : row.kind === "x" ? "/2/users/me" : row.kind === "cloudflare" ? "/zones" : row.kind === "fly" ? "/v1/apps" : row.kind === "exe" ? "/exec" : "/"; + const path = row.kind === "linear" ? "/graphql" : row.kind === "x" ? "/2/users/me" : row.kind === "cloudflare" ? "/zones" : row.kind === "fly" ? "/v1/apps" : row.kind === "hetzner" ? "/v1/servers" : row.kind === "exe" ? "/exec" : "/"; const method = row.kind === "linear" || row.kind === "exe" ? "POST" : "GET"; const requestExample = {integration:row.id,method,path,...(row.kind === "linear" ? {headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"query { viewer { id name } }"})} : row.kind === "exe" ? {headers:{"Content-Type":"text/plain"},body:"help"} : {})}; - result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use paths relative to the Cloudflare v4 REST API. Cloudflare enforces the accounts and permissions authorized on its consent screen." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")}); + result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use paths relative to the Cloudflare v4 REST API. Cloudflare enforces the accounts and permissions authorized on its consent screen." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "hetzner" ? "Use native Hetzner Cloud /v1 paths, methods, query and body. Reads require the owner’s Hetzner grant. Mutating methods also require explicit native writes enablement and a Read & Write project token." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")}); } return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(identity.scopes).filter(scope => !identity.policy.disabled_scopes.includes(scope)), proxy: { requestUrl: appConfig(this.env).origin + "/api/v1/agent/requests", @@ -118,6 +126,9 @@ export class AgentApiService { forward(integration: string, path: string, request: Request, expectedOperationEpoch?: number) { return this.egress().forward(integration, path, request, expectedOperationEpoch); } + assertRequest(integration: AgentIntegration, path: string, method: string) { + return this.egress().assertRequest(integration, path, method); + } forwardX(connectionId: string, path: string, request: Request) { return this.egress().forwardX(connectionId, path, request); } diff --git a/packages/api/src/proxy/application/proxy-operations.ts b/packages/api/src/proxy/application/proxy-operations.ts index f0fe61a1..eb0eb9e4 100644 --- a/packages/api/src/proxy/application/proxy-operations.ts +++ b/packages/api/src/proxy/application/proxy-operations.ts @@ -30,6 +30,7 @@ export class ProxyOperations { const parsed=requestApiInput.parse(input),api=this.api(); if(this.auth.authMethod==="oauth"&&!this.auth.scopes.includes("proxy:use"))throw new AgentApiError(403,"insufficient_scope","Renew consent with proxy:use before requesting integrations.","proxy:use"); const {identity,integration}=await api.authorize(parsed.integration); + await api.assertRequest(integration, parsed.path, parsed.method); if(!this.env.PROXY_ARTIFACTS || !this.env.SCHEDULER)throw new AgentApiError(503,"proxy_unavailable","Durable proxy storage/scheduling is unavailable."); const size=parsed.body===undefined?0:Buffer.byteLength(parsed.body,parsed.encoding==="base64"?"base64":"utf8"); if(size>proxyLimits.requestBytes)throw new AgentApiError(413,"request_too_large","Request exceeds the fixed 32 MiB limit."); diff --git a/packages/api/src/proxy/transport/credential-backed-egress.ts b/packages/api/src/proxy/transport/credential-backed-egress.ts index 37f61a12..d670ae16 100644 --- a/packages/api/src/proxy/transport/credential-backed-egress.ts +++ b/packages/api/src/proxy/transport/credential-backed-egress.ts @@ -39,12 +39,18 @@ export class CredentialBackedEgress { private requireIdentity: () => Promise, ) {} + /** Deny a locally prohibited Hetzner request before it creates an async receipt. */ + async assertRequest(integration: AgentIntegration, path: string, method: string) { + if (integration.kind === "hetzner" && !await resolveAgentCredential(this.env, this.tenantId, + integration.kind, integration.credential_id, path, method)) throw forbidden(); + } + async forward(integration: string, path: string, request: Request, expectedOperationEpoch?: number) { const grant = await this.authorize(integration); if (expectedOperationEpoch !== undefined && grant.integration.operation_epoch !== expectedOperationEpoch) throw forbidden(); if (grant.integration.kind === "x") return this.forwardX(grant.integration.credential_id, path, request, expectedOperationEpoch); let credential; - try { credential = await resolveAgentCredential(this.env, this.tenantId, grant.integration.kind, grant.integration.credential_id, path); } + try { credential = await resolveAgentCredential(this.env, this.tenantId, grant.integration.kind, grant.integration.credential_id, path, request.method); } catch (error) { if (error instanceof AgentApiError) throw error; throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved."); diff --git a/packages/api/src/transport/mcp/mcp-oauth-scopes.ts b/packages/api/src/transport/mcp/mcp-oauth-scopes.ts index bc71c55a..479d9f58 100644 --- a/packages/api/src/transport/mcp/mcp-oauth-scopes.ts +++ b/packages/api/src/transport/mcp/mcp-oauth-scopes.ts @@ -25,5 +25,6 @@ export async function mcpMissingScopes(env: Env, auth: OAuthProps, body: unknown !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(integration)) return missing; const row = (await databaseFor(env).pool.query( "SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND id=$2", [auth.tenantId, integration])).rows[0]; + // Hetzner access comes from the live owner checkbox rather than OAuth scope escalation. return row && row.kind !== "hetzner" && connectionAccess(row, auth.scopes, policy, auth.explicitIntegrationScopes) === "requestable" ? ["proxy:use", requiredIntegrationScope(row)] : missing; } diff --git a/packages/api/test/hetzner-inventory.postgres.test.ts b/packages/api/test/hetzner-inventory.postgres.test.ts index a310f649..ab290690 100644 --- a/packages/api/test/hetzner-inventory.postgres.test.ts +++ b/packages/api/test/hetzner-inventory.postgres.test.ts @@ -133,11 +133,11 @@ it.skipIf(!databaseUrl)("lets a live client read Hetzner only while its workspac const scope = `integration:${id}:${epoch}`; await f.db.pool.query(`INSERT INTO app.oauth_installations (tenant_id,user_id,id,client_id,redirect_uri,active_grant_id,active_session_version,active_scopes,selected_scopes) - VALUES($1,$2,$3,'fixture-client','https://client.example/callback',$4,$5,'{}','{}')`, + VALUES($1,$2,$3,'fixture-client','https://client.example/callback',$4,$5,ARRAY['proxy:use'],ARRAY['proxy:use'])`, [f.tenantId,f.userId,installation,grant,f.auth.sessionVersion]); const call = mcpRequest(f.env, { ...f.auth, authMethod:"oauth", oauthInstallationId:installation, - oauthClientId:"fixture-client", oauthGrantId:grant, oauthExpiresAt:Date.now()/1000 + 300, scopes:[] }); - const list = () => call("tools/call", { name:"list_hetzner_servers", arguments:{} }); + oauthClientId:"fixture-client", oauthGrantId:grant, oauthExpiresAt:Date.now()/1000 + 300, scopes:["proxy:use"] }); + const list = () => call("tools/call", { name:"request_api", arguments:{integration:id,method:"GET",path:"/v1/servers",execution:"sync"} }); const ssh = () => call("tools/call", { name:"check_hetzner_ssh", arguments:{serverId:1} }); const save = async (scopes: string[]) => worker.fetch(new Request(f.env.APP_ORIGIN + `/api/v1/access/authorizations/${installation}/permissions`, { method: "PUT", headers: { Cookie:f.cookie, Origin:f.env.APP_ORIGIN, "Content-Type":"application/json" }, @@ -146,10 +146,10 @@ it.skipIf(!databaseUrl)("lets a live client read Hetzner only while its workspac expect((await list()).message.result.isError).toBe(true); expect((await ssh()).message.result.isError).toBe(true); expect(provider).not.toHaveBeenCalled(); - expect((await save([scope])).status).toBe(200); - expect((await list()).message.result.structuredContent).toMatchObject({servers:[],truncated:false}); + expect((await save(["proxy:use",scope])).status).toBe(200); + expect((await list()).message.result.structuredContent).toMatchObject({status:200,body:JSON.stringify({ servers: [], meta: { pagination: { next_page: null } } })}); expect(provider).toHaveBeenCalledOnce(); - expect((await save([])).status).toBe(200); + expect((await save(["proxy:use"])).status).toBe(200); expect((await list()).message.result.isError).toBe(true); expect((await ssh()).message.result.isError).toBe(true); expect(provider).toHaveBeenCalledOnce(); diff --git a/packages/api/test/hetzner-provision.postgres.test.ts b/packages/api/test/hetzner-provision.postgres.test.ts deleted file mode 100644 index 8f74c01b..00000000 --- a/packages/api/test/hetzner-provision.postgres.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { expect, it, vi } from "vitest"; -import { loadingFixture } from "./helpers/loading-fixture"; -import { protectedApiFetch } from "../src/protected-api"; -import worker from "../src/worker"; -import type { OAuthProps } from "../src/types"; - -vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, WorkflowEntrypoint: 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; -const ctx = { waitUntil() {} } as unknown as ExecutionContext; - -it.skipIf(!url)("provisions one bounded server per request and binds its SSH key to the exact OAuth installation", async () => { - const f = await loadingFixture(url!); - const origin = f.env.APP_ORIGIN; - const selected = crypto.randomUUID(), other = crypto.randomUUID(), unapproved = crypto.randomUUID(); - const agent = (id = selected): OAuthProps => ({...f.auth, scopes: [], authMethod: "oauth", oauthInstallationId: id, - oauthClientId: "same-app", oauthGrantId: "grant-" + id, oauthExpiresAt: Date.now()/1000 + 60}); - const api = (path: string, method = "GET", body?: object) => worker.fetch(new Request(origin + "/api/v1/hetzner" + path, { - method, headers: { Cookie: f.cookie, Origin: origin, "Content-Type": "application/json" }, ...(body ? { body: JSON.stringify(body) } : {}), - }), f.env, ctx); - const mcp = async (name: string, args: object = {}, auth = agent()) => { - const response = await protectedApiFetch(new Request(origin + "/mcp", { method: "POST", headers: { - Host: new URL(origin).host, "Mcp-Protocol-Version": "2025-11-25", "Content-Type": "application/json", Accept: "application/json, text/event-stream", - }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }), f.env, auth, ctx); - const message = await response.text(); - const payload = message.startsWith("event:") ? message.split("\n").find(line => line.startsWith("data:"))?.slice(5) : message; - return JSON.parse(payload ?? "{}"); - }; - const assign = async (ids: string[]) => { - const { id, epoch } = (await f.db.pool.query("SELECT id,epoch FROM app.agent_integrations WHERE tenant_id=$1 AND kind='hetzner'", [f.tenantId])).rows[0]; - await f.db.pool.query("UPDATE app.oauth_installations SET selected_scopes=$3 WHERE tenant_id=$1 AND id=ANY($2)", [f.tenantId,ids,[`integration:${id}:${epoch}`]]); - }; - const approvals = { accepted: 0, reads: 0, nonce: "", publicKey: "" }; - const fixtureId = 41; - const provider = vi.fn(async (value, init) => { - const url = new URL(String(value)); - const token = new Headers(init?.headers).get("Authorization"); - expect(url.origin).toBe("https://api.hetzner.cloud"); - expect(init?.redirect).toBe("manual"); - if (init?.method === "POST") { - approvals.accepted++; - expect(url.pathname + url.search).toBe("/v1/servers"); - expect(token).toBe("Bearer syntheticWriteToken"); - const payload = JSON.parse(String(init.body)); - expect(payload).toMatchObject({name:"test-inventory", server_type:"cx23", location:"fsn1", image:"ubuntu-24.04", - start_after_create:true, public_net:{enable_ipv4:true,enable_ipv6:false}}); - expect(payload).not.toHaveProperty("ssh_keys"); - expect(payload).not.toHaveProperty("volumes"); - expect(payload.user_data).toMatch(/^#cloud-config\n/); - expect(JSON.parse(payload.user_data.split("\n")[1])).toEqual({ - disable_root:true, ssh_pwauth:false, allow_public_ssh_keys:false, ssh_genkeytypes:["ed25519"], users:[{name:"factorize-agent",shell:"/bin/sh",lock_passwd:true,sudo:null, - ssh_authorized_keys:[`restrict,command="/bin/true" ${approvals.publicKey}`]}], - }); - approvals.nonce = payload.labels["factorize-request"]; - expect(approvals.nonce).not.toBe(selected); - return new Response("synthetic upstream details", { status: 503 }); - } - expect(init?.method).toBe("GET"); - if (url.searchParams.has("label_selector")) { - approvals.reads++; - expect(url.searchParams.get("label_selector")).toBe("factorize-request=" + approvals.nonce); - expect(url.searchParams.get("name")).toBe("test-inventory"); - return Response.json({ servers: [{id:fixtureId,name:"test-inventory",labels:{"factorize-request":approvals.nonce}, root_password:"private"}] }); - } - if (url.pathname === "/v1/servers/41") return Response.json({ server: { id: fixtureId, public_net: { ipv4: { ip: "8.8.4.4" } } } }); - return Response.json({servers:[],meta:{pagination:{next_page:null}}}); - }); - vi.stubGlobal("fetch", provider); - try { - for (const id of [selected,other,unapproved]) { - await f.db.pool.query(`INSERT INTO app.oauth_installations - (tenant_id,user_id,id,client_id,redirect_uri,active_grant_id,active_session_version) VALUES($1,$2,$3,'same-app','https://example.test',$4,$5)`, - [f.tenantId,f.userId,id,"grant-"+id,f.auth.sessionVersion]); - } - await api("/connection","PUT",{ name:"Cloud", token:"syntheticReadToken" }); - await assign([selected,other]); - const input = {requestId:crypto.randomUUID(),name:"test-inventory",serverType:"cx23",location:"fsn1"}; - expect(JSON.stringify(await mcp("create_hetzner_server", input))).toContain("hetzner_provisioning_disabled"); - expect(JSON.stringify(await mcp("list_hetzner_servers"))).toContain("servers"); - expect(approvals.accepted).toBe(0); - const connection = await api("/connection","PUT",{ name:"Cloud", token:"syntheticWriteToken", provisioningEnabled:true }); - expect(await connection.json()).toEqual({ connection:{ name:"Cloud",provisioningEnabled:true } }); - expect(JSON.stringify(await mcp("create_hetzner_server", input))).toContain("hetzner_not_authorized"); - await assign([selected,other]); - expect(JSON.stringify(await mcp("get_hetzner_ssh_public_key", {}, agent(unapproved)))).toContain("hetzner_not_authorized"); - const first = (await mcp("get_hetzner_ssh_public_key")).result.structuredContent; - const second = (await mcp("get_hetzner_ssh_public_key", {}, agent(other))).result.structuredContent; - expect(first.publicKey).toMatch(/^ssh-ed25519 /); - expect(first.publicKey).not.toBe(second.publicKey); - expect(first.privateKey).toBeUndefined(); - expect((await mcp("get_hetzner_ssh_public_key")).result.structuredContent).toEqual(first); - approvals.publicKey = first.publicKey; - expect(JSON.stringify(await mcp("create_hetzner_server", {...input, userData: "not allowed"}))).not.toContain("created"); - expect(approvals.accepted).toBe(0); - const uncertain = JSON.stringify(await mcp("create_hetzner_server",input)); - expect(uncertain).toContain("hetzner_create_unconfirmed"); - expect(uncertain).not.toMatch(/synthetic upstream details|syntheticWriteToken/); - const result = (await mcp("create_hetzner_server",input)).result.structuredContent; - expect(result).toMatchObject({state:"created", serverId:fixtureId, ssh:"owner_pin_required"}); - expect((await mcp("create_hetzner_server",input)).result.structuredContent).toEqual(result); - expect(JSON.stringify(await mcp("create_hetzner_server",{...input,location:"nbg1"}))).toContain("hetzner_request_conflict"); - expect(JSON.stringify(await mcp("create_hetzner_server",{...input,requestId:crypto.randomUUID()},agent(other)))).toContain("hetzner_name_reserved"); - expect(approvals).toMatchObject({ accepted:1,reads:1 }); - const pin = {serverId:fixtureId,username:"factorize-agent",hostFingerprint:"SHA256:" + "A".repeat(43)}; - expect((await api("/ssh","POST",{...pin,clientInstallationId:other})).status).toBe(400); - const enrollment = await api("/ssh","POST",pin); - expect(await enrollment.json()).toMatchObject({...pin, clientInstallationId:selected,publicKey:first.publicKey}); - expect(JSON.stringify(await mcp("check_hetzner_ssh", {serverId:fixtureId}, agent(other)))).toContain("ssh_target_not_found"); - await f.db.pool.query("UPDATE app.oauth_installations SET selected_scopes='{}' WHERE tenant_id=$1 AND id=$2", [f.tenantId,selected]); - expect(JSON.stringify(await mcp("create_hetzner_server",input))).toContain("hetzner_not_authorized"); - const encrypted = await f.db.pool.query("SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind LIKE 'hetzner-client-key:%'",[f.tenantId]); - expect(encrypted.rows).toHaveLength(2); - expect(JSON.stringify(encrypted.rows)).not.toContain(first.publicKey); - expect(approvals.accepted).toBe(1); - } finally { vi.unstubAllGlobals(); await f.cleanup(); } -}); diff --git a/packages/api/test/hetzner-proxy.postgres.test.ts b/packages/api/test/hetzner-proxy.postgres.test.ts new file mode 100644 index 00000000..bcdc90ca --- /dev/null +++ b/packages/api/test/hetzner-proxy.postgres.test.ts @@ -0,0 +1,163 @@ +import { expect, it, vi } from "vitest"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { mcpRequest } from "./helpers/mcp-request"; +import { processProxyOperation } from "../src/proxy/application/proxy-operations"; +import { ConnectionRepository } from "../src/credentials/storage/connection-repository"; +import worker from "../src/worker"; +import type { OAuthProps } from "../src/types"; + +vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, WorkflowEntrypoint: 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; +const ctx = { waitUntil() {} } as ExecutionContext; + +it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy and fences retained results with the current exact grant", async () => { + const f = await loadingFixture(url!); + const first = crypto.randomUUID(), second = crypto.randomUUID(); + const auth = (id = first): OAuthProps => ({ ...f.auth, scopes: ["proxy:use"], authMethod: "oauth", + oauthInstallationId: id, oauthClientId: "same-app", oauthGrantId: "grant-" + id, oauthExpiresAt: Date.now() / 1000 + 120 }); + const mcp = mcpRequest(f.env, auth()); + const invoke = async (name: string, args: object = {}, identity = auth()) => + (await mcp("tools/call", { name, arguments: args }, identity)).message.result; + const project = (body: object) => worker.fetch(new Request(f.env.APP_ORIGIN + "/api/v1/hetzner/connection", { + method: "PUT", headers: { Cookie:f.cookie, Origin:f.env.APP_ORIGIN, "Content-Type":"application/json" }, body:JSON.stringify(body), + }), f.env, ctx); + const registry = async () => (await f.db.pool.query<{id:string;epoch:number}>( + "SELECT id,epoch FROM app.agent_integrations WHERE tenant_id=$1 AND kind='hetzner'", [f.tenantId], + )).rows[0]!; + const ownerGrant = async (installationId: string, enabled: boolean) => { + const { id, epoch } = await registry(); + const result = await worker.fetch(new Request(f.env.APP_ORIGIN + `/api/v1/access/authorizations/${installationId}/permissions`, { + method: "PUT", headers: { Cookie:f.cookie, Origin:f.env.APP_ORIGIN, "Content-Type":"application/json" }, + body: JSON.stringify({ scopes:["proxy:use", ...(enabled ? [`integration:${id}:${epoch}`] : [])] }), + }), f.env, ctx); + expect(result.status).toBe(200); + }; + const objects = new Map(); + f.env.PROXY_ARTIFACTS = { + put: async (key: string, bytes: ArrayBuffer) => { objects.set(key, new Uint8Array(bytes).slice()); }, + get: async (key: string, { range }: {range:{offset:number;length:number}}) => { + const bytes = objects.get(key)?.slice(range.offset, range.offset + range.length); + return bytes ? { arrayBuffer: async () => bytes.buffer } : null; + }, + } as unknown as R2Bucket; + f.env.SCHEDULER = { idFromName:(v:string)=>v, get:()=>({ fetch:async()=>Response.json({scheduled:true}) }) } as unknown as DurableObjectNamespace; + const readToken = "syntheticLegacyProjectToken", writeToken = "syntheticNativeWriteToken"; + const validations = { reads: 0, writes: 0 }; + const nativeBody = '{ "name": "demo", "image": "ubuntu-24.04", "server_type": "cx23", "ssh_keys": [123], "user_data": "#cloud-config\\n" }'; + let redirect = false, huge = false; + const nativeReply = {server:{id:88, name:"demo"}, action:{id:35,status:"running"}, custom:"unmodified-native-response"}; + const provider = vi.fn(async (input, init) => { + const request = new Request(input, init); + expect(new URL(request.url).origin).toBe("https://api.hetzner.cloud"); + expect(request.redirect).toBe("manual"); + const token = request.headers.get("Authorization"); + expect(request.headers.get("X-HTTP-Method-Override")).toBeNull(); + expect(request.headers.get("Cookie")).toBeNull(); + if (redirect) return new Response(null, { status:302, headers:{Location:"https://elsewhere.example/"} }); + if (request.method === "POST") { + expect(token).toBe("Bearer " + writeToken); + expect(new URL(request.url).pathname).toBe("/v1/servers"); + expect(await request.text()).toBe(nativeBody); + expect(request.headers.get("Content-Type")).toBe("application/json"); + validations.writes++; + return Response.json(nativeReply, {status:201,headers:{"x-provider-request":"native-123","x-authorization-token":"filtered"}}); + } + expect(request.method).toBe("GET"); + expect([readToken, writeToken].map(v=>"Bearer "+v)).toContain(token); + validations.reads++; + return Response.json(huge ? { servers:[], pad:"x".repeat(6000) } : + {servers:[{id:88,name:"demo",status:"running",location:{name:"fsn1"}}],meta:{pagination:{next_page:null}}}, {headers:{"x-provider-request":"native-read"}}); + }); + vi.stubGlobal("fetch", provider); + try { + // A project approved for the former bounded tool is still not approved for native writes. + await new ConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY) + .put("hetzner", { name:"Legacy", token:readToken, revision:crypto.randomUUID(), provisioningEnabled:true }); + const { id: integration } = await registry(); + for (const id of [first, second]) await f.db.pool.query(`INSERT INTO app.oauth_installations + (tenant_id,user_id,id,client_id,redirect_uri,active_grant_id,active_session_version,active_scopes,selected_scopes) + VALUES($1,$2,$3,'same-app','https://example.test',$4,$5,ARRAY['proxy:use'],ARRAY['proxy:use'])`, + [f.tenantId,f.userId,id,"grant-"+id,f.auth.sessionVersion]); + const get = { integration, method:"GET", path:"/v1/servers?name=demo", execution:"sync", + headers:{Authorization:"Bearer caller-override",Cookie:"caller-cookie","X-HTTP-Method-Override":"POST"} }; + const post = { integration, method:"POST", path:"/v1/servers", headers:{"Content-Type":"application/json"}, body:nativeBody }; + expect((await invoke("request_api",get)).isError).toBe(true); + expect(provider).not.toHaveBeenCalled(); + await ownerGrant(first,true); + const reflection = (await invoke("get_api_reflection")).structuredContent.integrations.find((row: any)=>row.id===integration); + expect(reflection).toMatchObject({kind:"hetzner",access:"granted",requestExample:{integration,method:"GET",path:"/v1/servers"}}); + expect(JSON.stringify(reflection)).not.toContain(readToken); + expect((await invoke("request_api",get,auth(second))).isError).toBe(true); + expect((await invoke("request_api",{...get,path:"/v1/../oauth/test"})).isError).toBe(true); + expect((await invoke("request_api",{...get,path:"//elsewhere.example/v1/servers"})).isError).toBe(true); + expect((await invoke("request_api",post)).isError).toBe(true); + expect((await invoke("request_api",{...post,execution:"sync"})).isError).toBe(true); + expect(provider).not.toHaveBeenCalled(); + const read = (await invoke("request_api",get)).structuredContent; + expect(read).toMatchObject({status:200,headers:{"x-provider-request":"native-read"}}); + expect(JSON.parse(read.body)).toMatchObject({servers:[{id:88,name:"demo",location:{name:"fsn1"}}]}); + expect(String(provider.mock.calls[0]?.[0])).toBe("https://api.hetzner.cloud/v1/servers?name=demo"); + + const oldKey = (await invoke("get_hetzner_ssh_public_key")).structuredContent; + expect(oldKey.publicKey).toMatch(/^ssh-ed25519 /); + expect(oldKey.privateKey).toBeUndefined(); + expect((await invoke("get_hetzner_ssh_public_key",{},auth(second))).isError).toBe(true); + + const turnedOn = await project({name:"Native",token:writeToken,nativeWritesEnabled:true}); + expect(await turnedOn.json()).toEqual({connection:{name:"Native",nativeWritesEnabled:true}}); + expect((await invoke("request_api",post)).isError).toBe(true); + expect(validations.writes).toBe(0); + await ownerGrant(first,true); + const currentKey = (await invoke("get_hetzner_ssh_public_key")).structuredContent; + expect((await invoke("get_hetzner_ssh_public_key")).structuredContent).toEqual(currentKey); + await ownerGrant(second,true); + expect((await invoke("get_hetzner_ssh_public_key",{},auth(second))).structuredContent.publicKey).not.toBe(currentKey.publicKey); + + const receipt = (await invoke("request_api",{...post,idempotencyKey:"stable-native-post"})).structuredContent; + expect(receipt).toMatchObject({state:"queued",operationId:expect.any(String)}); + expect((await invoke("request_api",{...post,idempotencyKey:"stable-native-post"})).structuredContent.operationId).toBe(receipt.operationId); + await processProxyOperation(f.env,f.tenantId,receipt.operationId); + await processProxyOperation(f.env,f.tenantId,receipt.operationId); + expect(validations.writes).toBe(1); + expect((await invoke("get_api_operation",{operationId:receipt.operationId})).structuredContent).toMatchObject({state:"complete",status:201,responseHandle:receipt.operationId}); + const retained = (await invoke("read_api_response",{handle:receipt.operationId})).structuredContent; + expect(JSON.parse(Buffer.from(retained.body,"base64").toString())).toEqual(nativeReply); + expect((await invoke("read_api_response",{handle:receipt.operationId},auth(second))).isError).toBe(true); + + const live = (await invoke("request_api",{...post,execution:"sync"})).structuredContent; + expect(live.status).toBe(201); + expect(live.headers["x-authorization-token"]).toBeUndefined(); + expect(JSON.parse(live.body)).toEqual(nativeReply); + redirect = true; + expect((await invoke("request_api",get)).isError).toBe(true); + redirect = false; + huge = true; + const handle = (await invoke("request_api",get)).structuredContent.handle; + expect(handle).toBeTruthy(); + expect((await invoke("read_api_response",{handle})).isError).not.toBe(true); + huge = false; + + const canceledGrant = (await invoke("request_api",{...post,idempotencyKey:"revoked-before-dispatch"})).structuredContent; + await ownerGrant(first,false); + await processProxyOperation(f.env,f.tenantId,canceledGrant.operationId); + expect(validations.writes).toBe(2); + expect((await invoke("get_api_operation",{operationId:canceledGrant.operationId})).isError).toBe(true); + expect((await invoke("read_api_response",{handle:receipt.operationId})).isError).toBe(true); + expect((await invoke("read_api_response",{handle})).isError).toBe(true); + expect((await invoke("get_hetzner_ssh_public_key")).isError).toBe(true); + expect((await invoke("request_api",get)).isError).toBe(true); + + await ownerGrant(first,true); + const staleProject = (await invoke("request_api",{...post,idempotencyKey:"rotated-before-dispatch"})).structuredContent; + const rotated = await project({name:"New read-only project",token:readToken}); + expect(await rotated.json()).toEqual({connection:{name:"New read-only project"}}); + await ownerGrant(first,true); + await processProxyOperation(f.env,f.tenantId,staleProject.operationId); + expect(validations.writes).toBe(2); + expect((await invoke("get_api_operation",{operationId:staleProject.operationId})).isError).toBe(true); + expect((await invoke("read_api_response",{handle:receipt.operationId})).isError).toBe(true); + expect((await invoke("request_api",get)).structuredContent.status).toBe(200); + expect((await invoke("request_api",post)).isError).toBe(true); + } finally { vi.unstubAllGlobals(); await f.cleanup(); } +}); diff --git a/packages/api/test/hetzner-ssh-enrollment.postgres.test.ts b/packages/api/test/hetzner-ssh-enrollment.postgres.test.ts index 76fe433e..2adb8ba0 100644 --- a/packages/api/test/hetzner-ssh-enrollment.postgres.test.ts +++ b/packages/api/test/hetzner-ssh-enrollment.postgres.test.ts @@ -46,13 +46,11 @@ it.skipIf(!url)("enrolls only a verified project server, hides its private key a await expect(owner.checkAsClient(41)).rejects.toMatchObject({status:403}); const unapproved = new HetznerSshService(f.env, auth(other, ["integrations:read"]), authorize); await expect(unapproved.checkAsClient(41)).rejects.toMatchObject({status:403}); - await expect(unapproved.inventoryAsClient()).rejects.toMatchObject({status:403}); expect(probe).not.toHaveBeenCalled(); const approved = new HetznerSshService(f.env, auth(selected, []), authorize); - expect(await approved.inventoryAsClient()).toEqual({ servers: [], truncated: false }); expect(await approved.checkAsClient(41)).toEqual({serverId:41,authenticated:true,reusedConnection:false}); - expect(providerGet).toHaveBeenCalledTimes(2); // The internal broker, not the browser/MCP caller, performs the preflight lookup. + expect(providerGet).toHaveBeenCalledTimes(1); // The internal broker, not the browser/MCP caller, performs the preflight lookup. await f.db.pool.query("UPDATE app.oauth_installations SET selected_scopes='{}' WHERE tenant_id=$1 AND id=$2", [f.tenantId,selected]); await expect(approved.checkAsClient(41)).rejects.toMatchObject({status:403}); expect(probe).toHaveBeenCalledOnce(); diff --git a/packages/app/src/features/integrations/hetzner-ssh.tsx b/packages/app/src/features/integrations/hetzner-ssh.tsx index 4e50fe07..161bf390 100644 --- a/packages/app/src/features/integrations/hetzner-ssh.tsx +++ b/packages/app/src/features/integrations/hetzner-ssh.tsx @@ -72,9 +72,9 @@ export function HetznerSsh({ servers }: { servers: Array<{ id: number; name: str {available.map(s => )} -

For a server created here, enter factorize-agent and leave the client on automatic selection.

+

For a server created by the retired Factorize server tool, enter factorize-agent and leave the client on automatic selection.

{clients.error &&

Could not list authorized clients.

} diff --git a/packages/app/src/features/integrations/hetzner.tsx b/packages/app/src/features/integrations/hetzner.tsx index 18ba5fdd..b912ccbe 100644 --- a/packages/app/src/features/integrations/hetzner.tsx +++ b/packages/app/src/features/integrations/hetzner.tsx @@ -19,7 +19,7 @@ export function useHetznerIntegration() { const session = useQuery(sessionQuery); const owner = session.data?.authenticated && session.data.team?.role === "owner"; const [screen, setScreen] = useState<"edit" | "delete" | "inventory" | null>(null); - const [provisioningEnabled, setProvisioningEnabled] = useState(false); + const [nativeWritesEnabled, setNativeWritesEnabled] = useState(false); const [name, setName] = useState(""); const [token, setToken] = useState(""); const [notice, setNotice] = useState(""); @@ -35,7 +35,7 @@ export function useHetznerIntegration() { return data; } }); const write = useMutation({ retry: false, mutationFn: async (operation: "save" | "delete") => { - const result = operation === "save" ? await api.PUT(connectionPath, { body: { name: name.trim(), token: token.trim(), ...(provisioningEnabled ? { provisioningEnabled: true } : {}) } }) : + const result = operation === "save" ? await api.PUT(connectionPath, { body: { name: name.trim(), token: token.trim(), ...(nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } }) : await api.DELETE(connectionPath); if (!result.data || result.error) throw new Error(withRequestReference(messageOf(result.error), result.response)); return operation; @@ -47,7 +47,7 @@ export function useHetznerIntegration() { }, onSettled: () => setToken("") }); function open(next: typeof screen) { setName(connection?.name ?? ""); - setProvisioningEnabled(connection?.provisioningEnabled === true); + setNativeWritesEnabled(connection?.nativeWritesEnabled === true); setToken(""); setNotice(""); write.reset(); @@ -58,22 +58,22 @@ export function useHetznerIntegration() { return { count: owner && connection ? 1 : 0, pending: Boolean(owner && query.isPending), - rows: owner && connection ? open("inventory") }, { label: "Replace connection", onClick: () => open("edit") }, { label: "Delete", destructive: true, onClick: () => open("delete") }, ]} /> : null, - tile: owner && open("edit")} />, feedback: owner && <>{query.error &&

{query.error.message}

}{notice &&

{notice}

}, dialog: owner && <> {screen === "edit" &&
{ event.preventDefault(); write.mutate("save"); }}> - - {provisioningEnabled &&

Creating servers and public IPv4 addresses can incur charges. Enable this only for a project whose costs you control.

} - -

Create a project API token in Hetzner Cloud Console with {provisioningEnabled ? "Read & Write" : "Read"} permission. Factorize tests inventory on save. Hetzner enforces write permission at server creation.

+ + {nativeWritesEnabled &&

Native writes can create billable resources, modify them, or delete them. Enable this only for a project you want these clients to manage.

} + +

Create a project API token in Hetzner Cloud Console with {nativeWritesEnabled ? "Read & Write" : "Read"} permission. Factorize tests inventory on save. Hetzner enforces its token permissions on every request.

{connection &&

Replacing the connection removes saved SSH keys and clears client access. Reassign the Hetzner checkbox for clients you still want to use it.

}
diff --git a/packages/app/test/functional/hetzner.spec.mjs b/packages/app/test/functional/hetzner.spec.mjs index aa65ee82..8933a3ed 100644 --- a/packages/app/test/functional/hetzner.spec.mjs +++ b/packages/app/test/functional/hetzner.spec.mjs @@ -1,6 +1,6 @@ import { test, expect } from "./fixtures.mjs"; -test("an owner saves a read-only Hetzner project, views inventory, explicitly enables provisioning, and confirms local deletion", async ({ page, origin }) => { +test("an owner saves a read-only Hetzner project, views inventory, explicitly enables native writes, and confirms local deletion", async ({ page, origin }) => { const token = "syntheticReadOnlyProjectToken", writeToken = "syntheticReadWriteProjectToken"; const requests = []; let connection = null, unavailable = true; @@ -19,10 +19,10 @@ test("an owner saves a read-only Hetzner project, views inventory, explicitly en requests.push(method); if (method === "PUT") { const provisioning = Boolean(connection); - expect(route.request().postDataJSON()).toEqual({ name: "Fixture project", ...(provisioning ? { token: writeToken, provisioningEnabled: true } : { token }) }); + expect(route.request().postDataJSON()).toEqual({ name: "Fixture project", ...(provisioning ? { token: writeToken, nativeWritesEnabled: true } : { token }) }); if (unavailable) return route.fulfill({ status: 502, headers: { "X-Request-Id": requestId }, json: { error: { code: "hetzner_inventory_error", message: "Hetzner server inventory is unavailable. Try again." } } }); - connection = { name: "Fixture project", ...(provisioning ? { provisioningEnabled: true } : {}) }; + connection = { name: "Fixture project", ...(provisioning ? { nativeWritesEnabled: true } : {}) }; } if (method === "DELETE") { connection = null; @@ -66,13 +66,13 @@ test("an owner saves a read-only Hetzner project, views inventory, explicitly en await row.getByRole("button", { name: "Actions for Hetzner Cloud · Fixture project" }).click(); await page.getByRole("menuitem", { name: "Replace connection", exact: true }).click(); const edit = page.getByRole("dialog", { name: "Replace Hetzner Cloud connection" }); - await expect(edit.getByRole("checkbox", { name: "Allow authorized clients to create small servers" })).not.toBeChecked(); - await edit.getByRole("checkbox", { name: "Allow authorized clients to create small servers" }).check(); - await expect(edit.getByText(/can incur charges/)).toBeVisible(); + await expect(edit.getByRole("checkbox", { name: "Allow authorized clients to make native API writes" })).not.toBeChecked(); + await edit.getByRole("checkbox", { name: "Allow authorized clients to make native API writes" }).check(); + await expect(edit.getByText(/create billable resources/)).toBeVisible(); await edit.getByLabel("Read & Write project API token").fill(writeToken); await edit.getByRole("button", { name: "Save connection" }).click(); await expect(edit).not.toBeVisible(); - await expect(row.getByText("Provisioning enabled")).toBeVisible(); + await expect(row.getByText("Native API writes enabled")).toBeVisible(); await row.getByRole("button", { name: "Actions for Hetzner Cloud · Fixture project" }).click(); await page.getByRole("menuitem", { name: "Delete", exact: true }).click(); const deletion = page.getByRole("dialog", { name: "Delete Hetzner Cloud connection?" }); diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index 30a55960..4da19e38 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -23,55 +23,45 @@ kept. Reconnecting does not restore removed configuration or grants. ### Hetzner Cloud -Open **Integrations → Hetzner Cloud** and enter a project token with **Read** -permission for inventory. To let clients provision servers, explicitly enable -provisioning and use a token with **Read & Write** permission in the same -project. Factorize validates inventory on save; Hetzner checks write permission -when a server is created. Replacing or deleting the project clears the previous -client permissions and Factorize's stored SSH keys and enrollments. Reassign -access for the intended clients after replacing the connection. +Add the project in **Integrations → Hetzner Cloud** with a Hetzner project +token. The default is read only. To allow writes, an owner must explicitly +enable **native API writes**, use a **Read & Write** token, and check the +Hetzner permission for each intended OAuth client. Enabling this makes the +project's native write methods available, including destructive changes. +The former bounded server-provisioning opt-in does not enable native writes. +Replacing the project resets client grants and stored SSH keys. Reassign only +the clients that should have access. -The owner can enable **Hetzner Cloud** in a client's permissions. The change -takes effect on the current OAuth connection. Without that checkbox the client -cannot list servers, create servers, access its Hetzner key, or check SSH. -With access the client can call `list_hetzner_servers` and -`get_hetzner_ssh_public_key`. Each OAuth installation gets a different -Factorize-managed key. The private key is encrypted and is never returned. +Use `get_api_reflection` to find the authorized Hetzner connection ID. Then +use the standard `request_api` tool with the method, relative `/v1/...` path, +query, and JSON body described in the [Hetzner Cloud API](https://docs.hetzner.cloud/reference/cloud). +For example, list servers using `GET /v1/servers`. To create a server, use +Hetzner's native `POST /v1/servers` body. Factorize does not rewrite it or +return the project token. Hetzner enforces the token's access. As with other +proxy connections, OAuth also needs `proxy:use`; Hetzner's checkbox controls +access to the specific project and is rechecked before dispatch and before +retained results can be read. The proxy defaults to asynchronous execution. +Use a stable `idempotencyKey` for a write and inspect the operation instead of +repeating an uncertain request. -#### Provision a server +#### Factorize SSH key management -When provisioning is enabled, `create_hetzner_server` accepts an intentional -lowercase name, a small server type, a supported location, and a request UUID. -It provisions one Ubuntu 24.04 server with public IPv4. The project's cloud -resources may incur charges. Check size availability and pricing in Hetzner -first. Factorize reserves up to three create attempts per day and 20 per -connection, including uncertain attempts. +`get_hetzner_ssh_public_key` returns the calling OAuth installation's public +key and a restricted authorized-keys line. Private keys are encrypted and +not exposed. Owners and their authorized clients can use Hetzner's native +SSH-key API through the proxy. A Hetzner project SSH-key record by itself +does not install a key on an existing server. During native server creation, +Hetzner's `ssh_keys` field places keys according to the selected image's +defaults. To use Factorize's authentication check, configure the complete +restricted key line on a dedicated non-root account, then independently +obtain the host's Ed25519 fingerprint from a trusted console. In **View +servers**, the owner enrolls that account, selects the exact OAuth client, +and sets the trusted fingerprint. Existing enrollments created by Factorize's +former server tool retain their original client binding. -Reuse the same request UUID if the first result is uncertain. Factorize looks -up the original creation and won't send a second create request for that UUID. -Check the provider console before starting a different request. Factorize -does not automatically delete servers in cleanup; owners can do that in -Hetzner. - -The server starts with the requesting client's restricted public key assigned -to the dedicated non-root `factorize-agent` account through cloud-init. Server -creation does not prove that bootstrap finished. In **View servers**, an owner -must independently obtain the server's Ed25519 host-key fingerprint from a trusted -console and enroll `factorize-agent` for SSH authentication. Leave client -selection automatic for provisioned servers. - -#### Enroll an existing server - -Choose an authorized client, a dedicated non-root account, and an Ed25519 -host-key fingerprint from the trusted server console. Install the complete -restricted public-key line shown by Factorize on that account. Leaving the -client blank on an existing server makes it owner-only. For older shared -enrollments, delete and re-enroll with the intended client and replace the old -key on the server before checking again. - -`check_hetzner_ssh` checks only servers enrolled for the calling client. It -revalidates the project's server and enrolled IPv4, authenticates with the -pinned host key, and closes immediately. It cannot run `ls` or any other -command. The server needs a reachable public IPv4 address and SSH on port 22. -Remove the authorized key from the server when retiring access; removing the -integration or enrollment in Factorize does not change the server. +`check_hetzner_ssh` revalidates project membership and the pinned public IPv4 +for the client's enrolled server, proves fresh authentication with the +pinned host key, and closes immediately. It never starts a shell, runs +commands, or returns output. Remove the installed public key on the server +when retiring access; removing a connection in Factorize does not change +the server. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 363e09a2..a663370c 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -353,58 +353,48 @@ kept. Reconnecting does not restore removed configuration or grants. ### Hetzner Cloud -Open **Integrations → Hetzner Cloud** and enter a project token with **Read** -permission for inventory. To let clients provision servers, explicitly enable -provisioning and use a token with **Read & Write** permission in the same -project. Factorize validates inventory on save; Hetzner checks write permission -when a server is created. Replacing or deleting the project clears the previous -client permissions and Factorize's stored SSH keys and enrollments. Reassign -access for the intended clients after replacing the connection. - -The owner can enable **Hetzner Cloud** in a client's permissions. The change -takes effect on the current OAuth connection. Without that checkbox the client -cannot list servers, create servers, access its Hetzner key, or check SSH. -With access the client can call `list_hetzner_servers` and -`get_hetzner_ssh_public_key`. Each OAuth installation gets a different -Factorize-managed key. The private key is encrypted and is never returned. - -#### Provision a server - -When provisioning is enabled, `create_hetzner_server` accepts an intentional -lowercase name, a small server type, a supported location, and a request UUID. -It provisions one Ubuntu 24.04 server with public IPv4. The project's cloud -resources may incur charges. Check size availability and pricing in Hetzner -first. Factorize reserves up to three create attempts per day and 20 per -connection, including uncertain attempts. - -Reuse the same request UUID if the first result is uncertain. Factorize looks -up the original creation and won't send a second create request for that UUID. -Check the provider console before starting a different request. Factorize -does not automatically delete servers in cleanup; owners can do that in -Hetzner. - -The server starts with the requesting client's restricted public key assigned -to the dedicated non-root `factorize-agent` account through cloud-init. Server -creation does not prove that bootstrap finished. In **View servers**, an owner -must independently obtain the server's Ed25519 host-key fingerprint from a trusted -console and enroll `factorize-agent` for SSH authentication. Leave client -selection automatic for provisioned servers. - -#### Enroll an existing server - -Choose an authorized client, a dedicated non-root account, and an Ed25519 -host-key fingerprint from the trusted server console. Install the complete -restricted public-key line shown by Factorize on that account. Leaving the -client blank on an existing server makes it owner-only. For older shared -enrollments, delete and re-enroll with the intended client and replace the old -key on the server before checking again. - -`check_hetzner_ssh` checks only servers enrolled for the calling client. It -revalidates the project's server and enrolled IPv4, authenticates with the -pinned host key, and closes immediately. It cannot run `ls` or any other -command. The server needs a reachable public IPv4 address and SSH on port 22. -Remove the authorized key from the server when retiring access; removing the -integration or enrollment in Factorize does not change the server. +Add the project in **Integrations → Hetzner Cloud** with a Hetzner project +token. The default is read only. To allow writes, an owner must explicitly +enable **native API writes**, use a **Read & Write** token, and check the +Hetzner permission for each intended OAuth client. Enabling this makes the +project's native write methods available, including destructive changes. +The former bounded server-provisioning opt-in does not enable native writes. +Replacing the project resets client grants and stored SSH keys. Reassign only +the clients that should have access. + +Use `get_api_reflection` to find the authorized Hetzner connection ID. Then +use the standard `request_api` tool with the method, relative `/v1/...` path, +query, and JSON body described in the [Hetzner Cloud API](https://docs.hetzner.cloud/reference/cloud). +For example, list servers using `GET /v1/servers`. To create a server, use +Hetzner's native `POST /v1/servers` body. Factorize does not rewrite it or +return the project token. Hetzner enforces the token's access. As with other +proxy connections, OAuth also needs `proxy:use`; Hetzner's checkbox controls +access to the specific project and is rechecked before dispatch and before +retained results can be read. The proxy defaults to asynchronous execution. +Use a stable `idempotencyKey` for a write and inspect the operation instead of +repeating an uncertain request. + +#### Factorize SSH key management + +`get_hetzner_ssh_public_key` returns the calling OAuth installation's public +key and a restricted authorized-keys line. Private keys are encrypted and +not exposed. Owners and their authorized clients can use Hetzner's native +SSH-key API through the proxy. A Hetzner project SSH-key record by itself +does not install a key on an existing server. During native server creation, +Hetzner's `ssh_keys` field places keys according to the selected image's +defaults. To use Factorize's authentication check, configure the complete +restricted key line on a dedicated non-root account, then independently +obtain the host's Ed25519 fingerprint from a trusted console. In **View +servers**, the owner enrolls that account, selects the exact OAuth client, +and sets the trusted fingerprint. Existing enrollments created by Factorize's +former server tool retain their original client binding. + +`check_hetzner_ssh` revalidates project membership and the pinned public IPv4 +for the client's enrolled server, proves fresh authentication with the +pinned host key, and closes immediately. It never starts a shell, runs +commands, or returns output. Remove the installed public key on the server +when retiring access; removing a connection in Factorize does not change +the server. ## Connection problems Source: https://docs.factorize.sh/troubleshooting/connection @@ -463,7 +453,6 @@ its input and enforces the operation's required scope. | `check_hetzner_ssh` | Check SSH access for one owner-enrolled Hetzner Cloud server. Uses the pinned host identity and a Factorize-held credential. Proves fresh key authentication; no SSH channel, commands or remote output. | | `create_app` | Register a server-side app. Create client secrets separately in the browser. | | `create_event` | Create a durable Event that one or more Triggers can publish. | -| `create_hetzner_server` | Create one small Hetzner Cloud server only when the owner enabled provisioning. This can incur charges. Provide an intentionally chosen name and a stable requestId. Retrying the same request only checks its outcome. Requires an owner-verified host fingerprint before SSH. | | `create_payload` | Reserve a temporary request body. Open browserUploadUrl to upload an existing file for that connection, or append/finalize generated text in chunks. Pass the finalized handle to request_api bodySource. | | `create_trigger` | Create an input Trigger attached to an Event. Credentials are never accepted or returned. | | `delete_event` | Permanently delete an Event, all its Triggers and input configurations, and its occurrence history. | @@ -490,7 +479,6 @@ its input and enforces the operation's required scope. | `list_events` | List Events, their current payload schema revisions, and Trigger and occurrence counts. | | `list_exe_connections` | List safe metadata for saved exe.dev connections. API tokens are never returned. | | `list_github_installations` | List connected GitHub App installations, including the installation IDs needed by GitHub Trigger events. Credentials are never returned. | -| `list_hetzner_servers` | List server inventory for a connected Hetzner project whose access is granted to this client. | | `list_trigger_webhook_activity` | List matching, rejected, duplicate, and accepted webhook activity for a trigger | | `list_triggers` | List triggers and their parent Events | | `list_vms` | List active Factorize permission grants for team VMs. Requires vms:read. | diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index b800efb2..7cf76087 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -20,7 +20,6 @@ its input and enforces the operation's required scope. | `check_hetzner_ssh` | Check SSH access for one owner-enrolled Hetzner Cloud server. Uses the pinned host identity and a Factorize-held credential. Proves fresh key authentication; no SSH channel, commands or remote output. | | `create_app` | Register a server-side app. Create client secrets separately in the browser. | | `create_event` | Create a durable Event that one or more Triggers can publish. | -| `create_hetzner_server` | Create one small Hetzner Cloud server only when the owner enabled provisioning. This can incur charges. Provide an intentionally chosen name and a stable requestId. Retrying the same request only checks its outcome. Requires an owner-verified host fingerprint before SSH. | | `create_payload` | Reserve a temporary request body. Open browserUploadUrl to upload an existing file for that connection, or append/finalize generated text in chunks. Pass the finalized handle to request_api bodySource. | | `create_trigger` | Create an input Trigger attached to an Event. Credentials are never accepted or returned. | | `delete_event` | Permanently delete an Event, all its Triggers and input configurations, and its occurrence history. | @@ -47,7 +46,6 @@ its input and enforces the operation's required scope. | `list_events` | List Events, their current payload schema revisions, and Trigger and occurrence counts. | | `list_exe_connections` | List safe metadata for saved exe.dev connections. API tokens are never returned. | | `list_github_installations` | List connected GitHub App installations, including the installation IDs needed by GitHub Trigger events. Credentials are never returned. | -| `list_hetzner_servers` | List server inventory for a connected Hetzner project whose access is granted to this client. | | `list_trigger_webhook_activity` | List matching, rejected, duplicate, and accepted webhook activity for a trigger | | `list_triggers` | List triggers and their parent Events | | `list_vms` | List active Factorize permission grants for team VMs. Requires vms:read. | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index c0ecb54d..4c537277 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -7735,7 +7735,7 @@ paths: properties: name: type: string - provisioningEnabled: + nativeWritesEnabled: type: boolean required: - name @@ -7770,7 +7770,7 @@ paths: put: summary: Save a Hetzner Cloud project connection description: |- - Owner browser session only. Supply a project API token with Read permission, or Read & Write only when enabling server provisioning. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources. + Owner browser session only. Supply a project API token with Read permission, or Read & Write only when explicitly enabling native API writes through the proxy. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources. Requires the integrations:write scope. @@ -7788,7 +7788,7 @@ paths: properties: name: type: string - provisioningEnabled: + nativeWritesEnabled: type: boolean required: - name @@ -7832,7 +7832,7 @@ paths: type: string minLength: 1 maxLength: 120 - provisioningEnabled: + nativeWritesEnabled: type: boolean token: type: string From 2ab655530b1b042018b53e9b5234dd98d03d4429 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Fri, 27 Nov 2026 13:37:37 -0700 Subject: [PATCH 2/2] Fix Hetzner proxy Worker fixture type --- packages/api/test/hetzner-proxy.postgres.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api/test/hetzner-proxy.postgres.test.ts b/packages/api/test/hetzner-proxy.postgres.test.ts index bcdc90ca..7507646b 100644 --- a/packages/api/test/hetzner-proxy.postgres.test.ts +++ b/packages/api/test/hetzner-proxy.postgres.test.ts @@ -9,7 +9,7 @@ import type { OAuthProps } from "../src/types"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, WorkflowEntrypoint: 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; -const ctx = { waitUntil() {} } as ExecutionContext; +const ctx = { waitUntil() {} } as unknown as ExecutionContext; it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy and fences retained results with the current exact grant", async () => { const f = await loadingFixture(url!);