From a87c6cab82a2e664f324f31d7783649ff9b4f377 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Fri, 27 Nov 2026 15:33:33 -0700 Subject: [PATCH] Resolve verified Hetzner SSH targets by server ID --- packages/api-client/src/schema.d.ts | 162 ++++++++++++++ .../storage/hetzner-connection-repository.ts | 2 +- packages/api/src/ssh/api/contracts.ts | 19 +- packages/api/src/ssh/api/mcp.ts | 2 +- packages/api/src/ssh/api/rest.ts | 14 +- .../api/src/ssh/application/hetzner-target.ts | 56 +++++ .../api/src/ssh/application/ssh-service.ts | 41 +++- .../src/ssh/storage/hetzner-pin-repository.ts | 36 ++++ .../api/src/ssh/transport/edgeport-exec.ts | 19 +- packages/api/src/ssh/transport/exec-broker.ts | 40 +++- .../hetzner-ssh-discovery.postgres.test.ts | 106 ++++++++++ .../integrations/hetzner-ssh-commands.tsx | 62 ++++++ .../app/src/features/integrations/hetzner.tsx | 9 +- packages/app/test/functional/hetzner.spec.mjs | 17 +- packages/docs/integrations/oauth.mdx | 15 +- packages/docs/llms-full.txt | 17 +- packages/docs/mcp/tools.mdx | 2 +- packages/docs/openapi.yaml | 197 ++++++++++++++++++ 18 files changed, 780 insertions(+), 36 deletions(-) create mode 100644 packages/api/src/ssh/application/hetzner-target.ts create mode 100644 packages/api/src/ssh/storage/hetzner-pin-repository.ts create mode 100644 packages/api/test/hetzner-ssh-discovery.postgres.test.ts create mode 100644 packages/app/src/features/integrations/hetzner-ssh-commands.tsx diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 55aa884d..6cd7f60d 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1200,6 +1200,56 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/ssh/hetzner-targets": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List verified SSH identities for the connected Hetzner project + * @description Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_ssh_hetzner_targets"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/ssh/hetzner-targets/{serverId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** + * Save an independently verified Hetzner SSH fingerprint + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + put: operations["put_api_v1_ssh_hetzner_targets_serverId"]; + post?: never; + /** + * Remove a saved Hetzner SSH fingerprint + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_ssh_hetzner_targets_serverId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/ssh/targets": { parameters: { query?: never; @@ -5893,6 +5943,118 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_ssh_hetzner_targets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Targets */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + targets: { + username: string; + hostFingerprint: string; + serverId: number; + /** @default false */ + needsVerification: boolean; + }[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + put_api_v1_ssh_hetzner_targets_serverId: { + parameters: { + query?: never; + header?: never; + path: { + serverId: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + username: string; + hostFingerprint: string; + }; + }; + }; + responses: { + /** @description Target */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + username: string; + hostFingerprint: string; + serverId: number; + /** @default false */ + needsVerification: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_ssh_hetzner_targets_serverId: { + parameters: { + query?: never; + header?: never; + path: { + serverId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Removal */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + deleted: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_ssh_targets: { parameters: { query?: never; diff --git a/packages/api/src/credentials/storage/hetzner-connection-repository.ts b/packages/api/src/credentials/storage/hetzner-connection-repository.ts index 8f567233..d11a0357 100644 --- a/packages/api/src/credentials/storage/hetzner-connection-repository.ts +++ b/packages/api/src/credentials/storage/hetzner-connection-repository.ts @@ -43,6 +43,6 @@ export class HetznerConnectionRepository { } private async clearSshCredentials(client: DatabaseClient) { - await client.query("DELETE FROM app.connections WHERE tenant_id=$1 AND (kind LIKE 'hetzner-ssh:%' OR kind LIKE 'hetzner-client-key:%')", [this.tenantId]); + await client.query("DELETE FROM app.connections WHERE tenant_id=$1 AND (kind LIKE 'hetzner-ssh:%' OR kind LIKE 'hetzner-client-key:%' OR kind LIKE 'hetzner-command-ssh:%')", [this.tenantId]); } } diff --git a/packages/api/src/ssh/api/contracts.ts b/packages/api/src/ssh/api/contracts.ts index 0934c91a..a19ec3f0 100644 --- a/packages/api/src/ssh/api/contracts.ts +++ b/packages/api/src/ssh/api/contracts.ts @@ -1,14 +1,25 @@ import { z } from "zod"; import { isPublicAddress } from "../../proxy/transport/public-address"; +const target = { + username: z.string().regex(/^[a-z_][a-z0-9_-]{0,31}$/).refine(username => username !== "root", "Use a non-root account."), + hostFingerprint: z.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/), +}; export const sshTargetInput = z.strictObject({ name: z.string().trim().min(1).max(96), address: z.string().max(45).refine(address => !address.includes("%") && isPublicAddress(address), "Use a public IP address."), - username: z.string().regex(/^[a-z_][a-z0-9_-]{0,31}$/).refine(username => username !== "root", "Use a non-root account."), - hostFingerprint: z.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/), + ...target, }); +export const hetznerSshPinInput = z.strictObject(target); +export const hetznerSshServerId = z.number().int().positive().max(Number.MAX_SAFE_INTEGER); +export const hetznerSshPin = hetznerSshPinInput.extend({ serverId: hetznerSshServerId, revision: z.uuid(), projectRevision: z.uuid(), needsVerification: z.boolean().default(false) }); +export const publicHetznerSshPin = hetznerSshPin.omit({ revision: true, projectRevision: true }).strip(); export const sshTarget = sshTargetInput.extend({ id: z.uuid() }); -export const sshExecInput = z.strictObject({ targetId: z.uuid(), command: z.string().min(1).max(4096).refine(command => !command.includes("\0")) }); +const execFields = z.strictObject({ targetId: z.uuid().optional(), hetznerServerId: hetznerSshServerId.optional(), command: z.string().min(1).max(4096).refine(command => !command.includes("\0")) }); +const oneSelector = (value: { targetId?: string; hetznerServerId?: number }) => + (value.targetId !== undefined) !== (value.hetznerServerId !== undefined); +export const sshExecInput = execFields.refine(oneSelector, "Supply either targetId or hetznerServerId."); +export const sshRoutingTarget = (value: z.infer) => value.targetId ?? "hetzner:" + value.hetznerServerId; export const sshExecResult = z.strictObject({ stdout: z.string(), stderr: z.string(), exitCode: z.number().int().nullable(), signal: z.string().nullable(), reusedConnection: z.boolean(), truncated: z.boolean(), @@ -19,5 +30,5 @@ export const sshClientAuthority = z.strictObject({ oauthInstallationId: z.string().min(1).max(512), oauthClientId: z.string().min(1).max(512).optional(), oauthGrantId: z.string().min(1).max(512), oauthExpiresAt: z.number().finite().positive(), }); -export const sshBrokerRequest = sshExecInput.extend({ authority: sshClientAuthority }); +export const sshBrokerRequest = execFields.extend({ authority: sshClientAuthority }).refine(oneSelector); export type SshClientAuthority = z.infer; diff --git a/packages/api/src/ssh/api/mcp.ts b/packages/api/src/ssh/api/mcp.ts index 1ff96eac..e56c7b5a 100644 --- a/packages/api/src/ssh/api/mcp.ts +++ b/packages/api/src/ssh/api/mcp.ts @@ -5,6 +5,6 @@ import { sshExecInput } from "./contracts"; export const sshTools = [ mcpTool(null, "get_ssh_public_key", "Get the public SSH key of this saved Factorize client. Install it on a server account to grant that key access. The private key is never returned.", z.strictObject({}), service => () => service.ssh.publicKey()), - mcpTool>(null, "ssh_exec", "Run one non-interactive SSH command on a saved target. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly.", + mcpTool>(null, "ssh_exec", "Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. The Hetzner server must have a verified host fingerprint. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly.", sshExecInput, service => input => service.ssh.exec(input)), ]; diff --git a/packages/api/src/ssh/api/rest.ts b/packages/api/src/ssh/api/rest.ts index 6cc807a0..ff40dfcc 100644 --- a/packages/api/src/ssh/api/rest.ts +++ b/packages/api/src/ssh/api/rest.ts @@ -1,11 +1,23 @@ import { z } from "zod"; import { jsonSchema, route } from "../../transport/rest/route-contract"; -import { sshTarget, sshTargetInput } from "./contracts"; +import { hetznerSshPinInput, hetznerSshServerId, publicHetznerSshPin, sshTarget, sshTargetInput } from "./contracts"; const ok = (description: string, schema: z.ZodType) => ({ "200": { description, content: { "application/json": { schema: jsonSchema(schema, "output") } } }, }); +const serverParameters = z.object({ serverId: z.string().regex(/^[1-9][0-9]*$/).refine(value => hetznerSshServerId.safeParse(Number(value)).success) }); export const sshTargetRoutes = [ + route("GET", "/api/v1/ssh/hetzner-targets", "integrations:read", { + summary: "List verified SSH identities for the connected Hetzner project", responses: ok("Targets", z.object({ targets: z.array(publicHetznerSshPin) })), + }, service => service.ssh.listHetznerPins(), { ownerSession: true }), + route("PUT", "/api/v1/ssh/hetzner-targets/{serverId}", "integrations:write", { + summary: "Save an independently verified Hetzner SSH fingerprint", responses: ok("Target", publicHetznerSshPin), + }, (service, { params, body }) => service.ssh.saveHetznerPin(Number(params.serverId), body), + { ownerSession: true, parameters: serverParameters, body: hetznerSshPinInput, maxBodyBytes: 4096 }), + route("DELETE", "/api/v1/ssh/hetzner-targets/{serverId}", "integrations:write", { + summary: "Remove a saved Hetzner SSH fingerprint", responses: ok("Removal", z.object({ deleted: z.boolean() })), + }, (service, { params }) => service.ssh.removeHetznerPin(Number(params.serverId)), + { ownerSession: true, parameters: serverParameters }), route("GET", "/api/v1/ssh/targets", "integrations:read", { summary: "List saved SSH target identities", responses: ok("Targets", z.object({ targets: z.array(sshTarget) })), }, service => service.ssh.listTargets(), { ownerSession: true }), diff --git a/packages/api/src/ssh/application/hetzner-target.ts b/packages/api/src/ssh/application/hetzner-target.ts new file mode 100644 index 00000000..28acef05 --- /dev/null +++ b/packages/api/src/ssh/application/hetzner-target.ts @@ -0,0 +1,56 @@ +import { signingConfig } from "../../config/runtime"; +import { HetznerConnectionRepository } from "../../credentials/storage/hetzner-connection-repository"; +import { activeHetznerScope } from "../../integrations/application/hetzner-access"; +import { HetznerInventoryService } from "../../integrations/application/hetzner-inventory"; +import { lockIntegrationTopology } from "../../integrations/storage/integration-removal-topology"; +import { databaseFor, type DatabaseClient } from "../../postgres/database"; +import { isPublicAddress } from "../../proxy/transport/public-address"; +import { ServiceError } from "../../service-contract"; +import type { Env } from "../../types"; +import type { SshClientAuthority } from "../api/contracts"; +import { HetznerSshPinRepository } from "../storage/hetzner-pin-repository"; + +export function hetznerSshContext(env: Env, identity: { tenantId: string; userId: string }, sql?: DatabaseClient) { + const database = databaseFor(env), key = signingConfig(env).credentialKey; + const connections = new HetznerConnectionRepository(database, identity.tenantId, key); + return { + connections, + inventory: new HetznerInventoryService(connections), + pins: new HetznerSshPinRepository(sql ?? database.pool, identity.tenantId, identity.userId, key), + }; +} + +export function hetznerSshAllowed(db: DatabaseClient, caller: SshClientAuthority) { + return activeHetznerScope(db, { tenantId: caller.tenantId, userId: caller.userId, sessionVersion: caller.sessionVersion, + installationId: caller.oauthInstallationId, grantId: caller.oauthGrantId, expiresAt: caller.oauthExpiresAt }); +} + +export async function resolveHetznerSshTarget(env: Env, caller: SshClientAuthority, serverId: number) { + const db = databaseFor(env).pool, { connections, inventory, pins } = hetznerSshContext(env, caller, db); + if (!await hetznerSshAllowed(db, caller)) throw new ServiceError(403, "hetzner_ssh_access_denied", "This client does not have access to the connected Hetzner project."); + const pin = await pins.get(serverId); + const project = await connections.get(); + if (!pin || pin.needsVerification || pin.projectRevision !== project?.revision) throw new ServiceError(412, "ssh_host_unverified", "Verify this server's SSH host fingerprint in Factorize before connecting."); + const server = await inventory.targetForServer(serverId); + if (!isPublicAddress(server.ipv4) || server.connectionRevision !== pin.projectRevision) { + throw new ServiceError(412, "ssh_host_unverified", "Recheck this server's SSH host identity before connecting."); + } + return { + target: { id: pin.revision, name: "Hetzner " + serverId, address: server.ipv4, username: pin.username, hostFingerprint: pin.hostFingerprint }, + markMismatch: async () => { + const database = databaseFor(env); + await database.transaction(async sql => { + await lockIntegrationTopology(sql, caller.tenantId); + const scoped = hetznerSshContext(env, caller, sql).pins; + const latest = await scoped.get(serverId); + if (latest?.revision === pin.revision && !latest.needsVerification) { + await scoped.save({ ...latest, needsVerification: true }); + } + }); + }, + current: async () => { + const [scope, latest, active] = await Promise.all([hetznerSshAllowed(db, caller), pins.get(serverId), connections.get()]); + return Boolean(scope && latest?.revision === pin.revision && !latest.needsVerification && active?.revision === pin.projectRevision); + }, + }; +} diff --git a/packages/api/src/ssh/application/ssh-service.ts b/packages/api/src/ssh/application/ssh-service.ts index f6ae990f..e8cbe430 100644 --- a/packages/api/src/ssh/application/ssh-service.ts +++ b/packages/api/src/ssh/application/ssh-service.ts @@ -6,7 +6,9 @@ import { lockIntegrationTopology } from "../../integrations/storage/integration- import { databaseFor, type DatabaseClient } from "../../postgres/database"; import { ServiceError } from "../../service-contract"; import type { Env, OAuthProps } from "../../types"; -import { sshClientAuthority, sshExecResult, type SshClientAuthority, type sshExecInput, type sshTargetInput } from "../api/contracts"; +import { publicHetznerSshPin, sshClientAuthority, sshExecResult, sshRoutingTarget, type hetznerSshPinInput, type SshClientAuthority, type sshExecInput, type sshTargetInput } from "../api/contracts"; +import { isPublicAddress } from "../../proxy/transport/public-address"; +import { hetznerSshContext } from "./hetzner-target"; import { SshTargetRepository } from "../storage/target-repository"; export async function activeSshClient(sql: DatabaseClient, caller: SshClientAuthority) { @@ -70,17 +72,52 @@ export class SshService { return { deleted: await this.targets(this.db.pool).remove(id) }; } + async listHetznerPins() { + await this.owner("integrations:read"); + const { connections, pins } = hetznerSshContext(this.env, this.auth); + const project = await connections.get(); + return { targets: project ? (await pins.list(project.revision)).map(pin => publicHetznerSshPin.parse(pin)) : [] }; + } + + async saveHetznerPin(serverId: number, input: z.infer) { + await this.owner("integrations:write"); + const { inventory } = hetznerSshContext(this.env, this.auth); + const server = await inventory.targetForServer(serverId); + if (!isPublicAddress(server.ipv4)) throw new ServiceError(422, "ssh_target_ip_invalid", "This server has no supported public IPv4 address."); + return this.db.transaction(async sql => { + await lockIntegrationTopology(sql, this.auth.tenantId); + const { connections, pins } = hetznerSshContext(this.env, this.auth, sql); + if ((await connections.get(sql))?.revision !== server.connectionRevision) { + throw new ServiceError(409, "hetzner_project_changed", "The Hetzner project changed. Refresh the list and verify the host again."); + } + const saved = await pins.save({ ...input, serverId, revision: crypto.randomUUID(), projectRevision: server.connectionRevision, needsVerification: false }); + return publicHetznerSshPin.parse(saved); + }); + } + + async removeHetznerPin(serverId: number) { + await this.owner("integrations:write"); + return this.db.transaction(async sql => { + await lockIntegrationTopology(sql, this.auth.tenantId); + return { deleted: await hetznerSshContext(this.env, this.auth, sql).pins.remove(serverId) }; + }); + } + async exec(input: z.infer) { const authority = await this.caller(this.db.pool); const broker = this.env.CLIENT_SSH; if (!broker) throw new ServiceError(503, "ssh_unavailable", "The SSH command broker is unavailable."); - const name = JSON.stringify([authority.tenantId, authority.userId, authority.oauthInstallationId, input.targetId]); + const name = JSON.stringify([authority.tenantId, authority.userId, authority.oauthInstallationId, sshRoutingTarget(input)]); const result = await broker.get(broker.idFromName(name)).fetch("https://ssh.internal/exec", { method: "POST", body: JSON.stringify({ ...input, authority }) }); switch (result.status) { case 200: return sshExecResult.parse(await result.json()); case 401: throw new ServiceError(403, "ssh_client_inactive", "The OAuth client was not active."); + case 403: throw new ServiceError(403, "hetzner_ssh_access_denied", "This client does not have access to the connected Hetzner project."); + case 412: throw new ServiceError(412, "ssh_host_unverified", "Verify this server's SSH host fingerprint in Factorize before connecting."); + case 421: throw new ServiceError(421, "ssh_host_fingerprint_changed", "The SSH host fingerprint differs from the verified fingerprint. No command ran. Verify the new fingerprint independently before reconnecting."); + case 424: throw new ServiceError(424, "hetzner_ssh_lookup_failed", "Could not verify the server's current address through Hetzner. No command ran."); case 404: throw new ServiceError(404, "ssh_target_not_found", "Save a verified target before running SSH commands."); case 409: throw new ServiceError(409, "ssh_busy_or_no_key", "Generate this client's SSH key first, and wait for any running command."); case 422: throw new ServiceError(422, "ssh_login_failed", "SSH login failed. Check the saved host key, account, and authorized public key."); diff --git a/packages/api/src/ssh/storage/hetzner-pin-repository.ts b/packages/api/src/ssh/storage/hetzner-pin-repository.ts new file mode 100644 index 00000000..0f4ab669 --- /dev/null +++ b/packages/api/src/ssh/storage/hetzner-pin-repository.ts @@ -0,0 +1,36 @@ +import type { z } from "zod"; +import { decrypt, encrypt } from "../../crypto"; +import type { DatabaseClient } from "../../postgres/database"; +import { hetznerSshPin } from "../api/contracts"; + +export class HetznerSshPinRepository { + constructor(private sql: DatabaseClient, private tenantId: string, private userId: string, private key: string) {} + private get prefix() { return "hetzner-command-ssh:" + this.userId + ":"; } + + private async parse(value: string) { return hetznerSshPin.parse(JSON.parse(await decrypt(value, this.key))); } + + async get(serverId: number) { + const { rows } = await this.sql.query<{ encrypted_value: string }>( + "SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, this.prefix + serverId]); + return rows[0] ? this.parse(rows[0].encrypted_value) : null; + } + + async list(projectRevision: string) { + const { rows } = await this.sql.query<{ encrypted_value: string }>( + "SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind LIKE $2 ORDER BY kind LIMIT 100", + [this.tenantId, this.prefix + "%"]); + return (await Promise.all(rows.map(row => this.parse(row.encrypted_value)))).filter(pin => pin.projectRevision === projectRevision); + } + + async save(pin: z.infer) { + await this.sql.query(`INSERT INTO app.connections (tenant_id,kind,encrypted_value) VALUES ($1,$2,$3) + ON CONFLICT (tenant_id,kind) DO UPDATE SET encrypted_value=excluded.encrypted_value,updated_at=now()`, + [this.tenantId, this.prefix + pin.serverId, await encrypt(JSON.stringify(pin), this.key)]); + return pin; + } + + async remove(serverId: number) { + const result = await this.sql.query("DELETE FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, this.prefix + serverId]); + return Boolean(result.rowCount); + } +} diff --git a/packages/api/src/ssh/transport/edgeport-exec.ts b/packages/api/src/ssh/transport/edgeport-exec.ts index 49685482..fad62b02 100644 --- a/packages/api/src/ssh/transport/edgeport-exec.ts +++ b/packages/api/src/ssh/transport/edgeport-exec.ts @@ -6,14 +6,23 @@ export const SSH_CONNECT_MS = 5_000; export const SSH_COMMAND_MS = 20_000; const OUTPUT_LIMIT = 32 * 1024; -export function openSshSession(target: SshTarget, privateKey: string, port = 22) { +export class SshHostFingerprintMismatch extends Error {} + +export async function openSshSession(target: SshTarget, privateKey: string, port = 22) { const expected = Buffer.from(target.hostFingerprint.slice("SHA256:".length), "base64"); - return connect({ + let mismatch = false; + try { return await connect({ hostname: target.address, port, username: target.username, privateKey: { pem: privateKey }, timeoutMs: SSH_CONNECT_MS, - hostKey: { verify: (type, wireKey) => type === "ssh-ed25519" && - timingSafeEqual(expected, createHash("sha256").update(wireKey).digest()) }, - }); + hostKey: { verify: (type, wireKey) => { + const matches = type === "ssh-ed25519" && timingSafeEqual(expected, createHash("sha256").update(wireKey).digest()); + if (!matches) mismatch = true; + return matches; + } }, + }); } catch (error) { + if (mismatch) throw new SshHostFingerprintMismatch("The SSH host fingerprint did not match."); + throw error; + } } export async function execBounded(session: SshSession, command: string) { diff --git a/packages/api/src/ssh/transport/exec-broker.ts b/packages/api/src/ssh/transport/exec-broker.ts index d6e2f674..9dff3b52 100644 --- a/packages/api/src/ssh/transport/exec-broker.ts +++ b/packages/api/src/ssh/transport/exec-broker.ts @@ -4,10 +4,12 @@ import type { Env } from "../../config/bindings"; import { signingConfig } from "../../config/runtime"; import { SshClientKeyRepository } from "../../credentials/storage/ssh-client-key-repository"; import { databaseFor } from "../../postgres/database"; -import { sshBrokerRequest } from "../api/contracts"; +import { ServiceError } from "../../service-contract"; +import { resolveHetznerSshTarget } from "../application/hetzner-target"; +import { sshBrokerRequest, sshRoutingTarget, type SshTarget } from "../api/contracts"; import { activeSshClient } from "../application/ssh-service"; import { SshTargetRepository } from "../storage/target-repository"; -import { execBounded, openSshSession, SSH_COMMAND_MS, SSH_CONNECT_MS } from "./edgeport-exec"; +import { execBounded, openSshSession, SshHostFingerprintMismatch, SSH_COMMAND_MS, SSH_CONNECT_MS } from "./edgeport-exec"; const idleMs = 30_000, maxAgeMs = 120_000; @@ -36,20 +38,36 @@ export class SshExecBroker extends DurableObject { this.busy = true; clearTimeout(this.idle); try { - const { authority, targetId, command } = sshBrokerRequest.parse(await req.json()); - const name = JSON.stringify([authority.tenantId, authority.userId, authority.oauthInstallationId, targetId]); + const input = sshBrokerRequest.parse(await req.json()); + const { authority, targetId, hetznerServerId, command } = input; + const name = JSON.stringify([authority.tenantId, authority.userId, authority.oauthInstallationId, sshRoutingTarget(input)]); if (this.env.CLIENT_SSH?.idFromName(name).toString() !== this.ctx.id.toString()) return new Response(null, { status: 404 }); const db = databaseFor(this.env).pool, secret = signingConfig(this.env).credentialKey; const targets = new SshTargetRepository(db, authority.tenantId, authority.userId, secret); if (!await activeSshClient(db, authority)) { this.close(); return new Response(null, { status: 401 }); } - const target = await targets.get(targetId); + let target: SshTarget | null; + let current: () => Promise; + let markMismatch: (() => Promise) | undefined; + if (hetznerServerId !== undefined) { + try { + const resolved = await resolveHetznerSshTarget(this.env, authority, hetznerServerId); + ({ target, current, markMismatch } = resolved); + } catch (error) { + this.close(); + const status = error instanceof ServiceError && (error.status === 403 || error.status === 412) ? error.status : 424; + return new Response(null, { status }); + } + } else { + target = await targets.get(targetId!); + current = async () => Boolean(await targets.get(targetId!)); + } if (!target) { this.close(); return new Response(null, { status: 404 }); } const keys = new SshClientKeyRepository(authority.tenantId, secret); const key = await keys.get(db, authority.oauthInstallationId); if (!key) { this.close(); return new Response(null, { status: 409 }); } const now = Date.now(); - const fingerprint = JSON.stringify([target.address, target.username, target.hostFingerprint, key.publicKey]); + const fingerprint = JSON.stringify([target.id, target.address, target.username, target.hostFingerprint, key.publicKey]); if (this.session && (this.session.fingerprint !== fingerprint || now - this.session.lastUsed >= idleMs || now - this.session.opened >= maxAgeMs)) this.close(); const reusedConnection = !!this.session; if (!this.session) { @@ -57,18 +75,22 @@ export class SshExecBroker extends DurableObject { try { const transport = await deadline(pending, SSH_CONNECT_MS); this.session = { transport, opened: Date.now(), lastUsed: Date.now(), fingerprint }; - } catch { + } catch (error) { this.ctx.waitUntil(pending.then(transport => transport.close()).catch(() => {})); + if (error instanceof SshHostFingerprintMismatch) { + await markMismatch?.(); + return new Response(null, { status: 421 }); + } return new Response(null, { status: 422 }); } } const session = this.session; if (!await activeSshClient(db, authority)) { this.close(); return new Response(null, { status: 401 }); } - if (!await targets.get(targetId)) { this.close(); return new Response(null, { status: 404 }); } + if (!await current()) { this.close(); return new Response(null, { status: hetznerServerId === undefined ? 404 : 412 }); } const remaining = maxAgeMs - (Date.now() - session.opened); if (remaining <= 0) { this.close(); return new Response(null, { status: 503 }); } const result = await deadline(execBounded(session.transport, command), Math.min(SSH_COMMAND_MS, remaining)); - if (!await activeSshClient(db, authority) || !await targets.get(targetId)) { + if (!await activeSshClient(db, authority) || !await current()) { this.close(); return new Response(null, { status: 502 }); } session.lastUsed = Date.now(); diff --git a/packages/api/test/hetzner-ssh-discovery.postgres.test.ts b/packages/api/test/hetzner-ssh-discovery.postgres.test.ts new file mode 100644 index 00000000..32bdff2e --- /dev/null +++ b/packages/api/test/hetzner-ssh-discovery.postgres.test.ts @@ -0,0 +1,106 @@ +import { expect, it, vi } from "vitest"; +import { HetznerConnectionRepository } from "../src/credentials/storage/hetzner-connection-repository"; +import { requiredIntegrationScope, type AgentIntegration } from "../src/proxy/application/agent-integration-access"; +import { SshExecBroker } from "../src/ssh/transport/exec-broker"; +import { SshHostFingerprintMismatch, openSshSession, execBounded } from "../src/ssh/transport/edgeport-exec"; +import worker from "../src/worker"; +import type { Env, OAuthProps } from "../src/types"; +import { loadingFixture } from "./helpers/loading-fixture"; +import { mcpRequest } from "./helpers/mcp-request"; + +vi.mock("cloudflare:workers", () => ({ + WorkerEntrypoint: class {}, WorkflowEntrypoint: class {}, + DurableObject: class { constructor(readonly ctx: DurableObjectState, readonly env: Env) {} }, +})); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); +vi.mock("../src/ssh/transport/edgeport-exec", () => ({ + openSshSession: vi.fn(), execBounded: vi.fn(), + SSH_COMMAND_MS: 1_000, SSH_CONNECT_MS: 1_000, SshHostFingerprintMismatch: class extends Error {}, +})); +const url = process.env.AUTH_TEST_DATABASE_URL; +const ctx = { waitUntil() {} } as unknown as ExecutionContext; + +it.skipIf(!url)("resolves Hetzner IDs under the live project grant and fences a changed host pin until explicitly verified again", async () => { + const f = await loadingFixture(url!); + const installation = crypto.randomUUID(), grant = "grant-" + installation, serverId = 987; + const identity: OAuthProps = { ...f.auth, scopes: ["proxy:use"], authMethod: "oauth", + oauthInstallationId: installation, oauthClientId: "test-app", oauthGrantId: grant, oauthExpiresAt: Date.now() / 1000 + 120 }; + const mcp = mcpRequest(f.env, identity); + const ownerRequest = (path: string, method: string, body?: object) => worker.fetch(new Request(f.env.APP_ORIGIN + path, { + method, headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, + ...(body ? { body: JSON.stringify(body) } : {}), + }), f.env, ctx); + const path = "/api/v1/ssh/hetzner-targets"; + const pin = { username: "runner", hostFingerprint: "SHA256:" + "A".repeat(43) }; + const brokers = new Map(); + f.env.CLIENT_SSH = { idFromName: (id: string) => id, get: (id: string) => { + if (!brokers.has(id)) brokers.set(id, new SshExecBroker({ id, waitUntil() {} } as unknown as DurableObjectState, f.env)); + return { fetch: (input: string, init: RequestInit) => brokers.get(id)!.fetch(new Request(input, init)) }; + } } as unknown as DurableObjectNamespace; + let address = "8.8.4.4", missing = false; + const provider = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + expect(new URL(req.url).origin).toBe("https://api.hetzner.cloud"); + expect(new URL(req.url).pathname).toBe("/v1/servers/" + serverId); + if (missing) return new Response(null, { status: 404 }); + return Response.json({ server: { id: serverId, public_net: { ipv4: { ip: address } } } }); + }); + const session = { close: vi.fn(async () => {}) }; + vi.mocked(openSshSession).mockResolvedValue(session as unknown as Awaited>); + vi.mocked(execBounded).mockResolvedValue({ stdout: "ok", stderr: "", exitCode: 0, signal: null, truncated: false }); + vi.stubGlobal("fetch", provider); + const run = async (params: object = { hetznerServerId: serverId }) => + JSON.stringify((await mcp("tools/call", { name: "ssh_exec", arguments: { command: "true", ...params } })).message); + try { + const project = new HetznerConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await project.save("Project", "synthetic-test-token"); + const row = (await f.db.pool.query("SELECT * FROM app.agent_integrations WHERE tenant_id=$1 AND kind='hetzner'", [f.tenantId])).rows[0]!; + const scope = requiredIntegrationScope(row); + const db = f.db.pool; + await db.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,'test-app','https://example.test',$4,$5,ARRAY['proxy:use'],ARRAY['proxy:use'])`, + [f.tenantId,f.userId,installation,grant,f.auth.sessionVersion]); + const setAccess = (granted: boolean) => db.query(`UPDATE app.oauth_installations SET selected_scopes=$3 + WHERE tenant_id=$1 AND id=$2`, [f.tenantId, installation, granted ? ["proxy:use", scope] : ["proxy:use"]]); + + expect(await run()).toContain("hetzner_ssh_access_denied"); + expect(provider).not.toHaveBeenCalled(); + await setAccess(true); + expect(await run()).toContain("ssh_host_unverified"); + expect(provider).not.toHaveBeenCalled(); + expect(await run({})).not.toContain('"stdout"'); + expect(await run({ hetznerServerId: serverId, targetId: crypto.randomUUID() })).not.toContain('"stdout"'); + await mcp("tools/call", { name: "get_ssh_public_key", arguments: {} }); + + expect((await ownerRequest(path + "/" + serverId, "PUT", pin)).status).toBe(200); + expect(await (await ownerRequest(path, "GET")).json()).toEqual({ targets: [{...pin, serverId, needsVerification: false}] }); + expect(await run()).toContain('"stdout":"ok"'); + expect(vi.mocked(openSshSession).mock.calls[0]?.[0]).toMatchObject({ address, username: pin.username, hostFingerprint: pin.hostFingerprint }); + + // Hetzner reassigns its public address. Do not use the old warm connection. + address = "8.8.8.8"; + vi.mocked(openSshSession).mockRejectedValueOnce(new SshHostFingerprintMismatch()); + expect(await run()).toContain("ssh_host_fingerprint_changed"); + expect(session.close).toHaveBeenCalled(); + expect(execBounded).toHaveBeenCalledTimes(1); + expect(await run()).toContain("ssh_host_unverified"); + expect(openSshSession).toHaveBeenCalledTimes(2); + expect(await (await ownerRequest(path, "GET")).json()).toEqual({ targets: [{...pin, serverId, needsVerification: true}] }); + + const verified = { ...pin, hostFingerprint: "SHA256:" + "B".repeat(43) }; + expect((await ownerRequest(path + "/" + serverId, "PUT", verified)).status).toBe(200); + expect(await run()).toContain('"stdout":"ok"'); + expect(vi.mocked(openSshSession).mock.calls[2]?.[0]).toMatchObject({ address, hostFingerprint: verified.hostFingerprint }); + missing = true; + expect(await run()).toContain("hetzner_ssh_lookup_failed"); + expect(execBounded).toHaveBeenCalledTimes(2); + await setAccess(false); + expect(await run()).toContain("hetzner_ssh_access_denied"); + await project.save("Replacement", "synthetic-replacement"); + expect(await (await ownerRequest(path, "GET")).json()).toEqual({ targets: [] }); + } finally { + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); diff --git a/packages/app/src/features/integrations/hetzner-ssh-commands.tsx b/packages/app/src/features/integrations/hetzner-ssh-commands.tsx new file mode 100644 index 00000000..786e9dcd --- /dev/null +++ b/packages/app/src/features/integrations/hetzner-ssh-commands.tsx @@ -0,0 +1,62 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Button, Input, Label } from "../../shared/ui"; +import { messageOf } from "../auth/session"; + +const key = ["settings", "hetzner", "ssh-command-targets"]; +const path = "/api/v1/ssh/hetzner-targets/{serverId}"; + +export function HetznerSshCommands({ servers }: { servers: Array<{ id: number; name: string }> }) { + const cache = useQueryClient(); + const [server, setServer] = useState(""); + const [username, setUsername] = useState(""); + const [fingerprint, setFingerprint] = useState(""); + const [notice, setNotice] = useState(""); + const pins = useQuery({ queryKey: key, retry: false, queryFn: async ({ signal }) => { + const { data, error } = await api.GET("/api/v1/ssh/hetzner-targets", { signal }); + if (!data || error) throw new Error(messageOf(error)); + return data.targets; + } }); + const write = useMutation({ mutationFn: async ({ serverId, remove }: { serverId: string; remove?: true }) => { + const params = { path: { serverId } }; + const { data, error } = remove ? await api.DELETE(path, { params }) : + await api.PUT(path, { params, body: { username: username.trim(), hostFingerprint: fingerprint.trim() } }); + if (!data || error) throw new Error(messageOf(error)); + }, onSuccess: async (_, { remove }) => { + setFingerprint(""); + setNotice(remove ? "SSH fingerprint removed." : "SSH fingerprint verified and saved."); + await cache.invalidateQueries({ queryKey: key }); + } }); + + if (servers.length === 0 && !pins.data?.length && !pins.error) return null; + return
+

SSH commands

+

Choose an existing server. Verify its Ed25519 host fingerprint through a trusted console before saving it. The server must also have the client’s public key installed on the selected non-root account.

+ {notice &&

{notice}

} + {(pins.error || write.error) &&

{(pins.error ?? write.error)?.message}

} + {pins.data?.map(pin =>
+ {servers.find(s => s.id === pin.serverId)?.name ?? "Server " + pin.serverId} (#{pin.serverId}) + {pin.needsVerification ? "Fingerprint changed. Verify again." : "Verified"} + +
)} + {servers.length > 0 &&
{ event.preventDefault(); write.mutate({ serverId: server }); }}> + + + + +
} +
; +} diff --git a/packages/app/src/features/integrations/hetzner.tsx b/packages/app/src/features/integrations/hetzner.tsx index 586861bb..0e30e4c7 100644 --- a/packages/app/src/features/integrations/hetzner.tsx +++ b/packages/app/src/features/integrations/hetzner.tsx @@ -6,6 +6,7 @@ import { SecretInput } from "../../shared/credential-fields"; import { Button, Input, Label, Table, tableCellClasses, tableHeadClasses, tableRowClasses } from "../../shared/ui"; import { messageOf, sessionQuery } from "../auth/session"; import { IntegrationRow, ProviderTile } from "./integration-ui"; +import { HetznerSshCommands } from "./hetzner-ssh-commands"; import { HetznerSsh } from "./hetzner-ssh"; import { withRequestReference } from "./request-reference"; @@ -69,14 +70,14 @@ export function useHetznerIntegration() {
{ event.preventDefault(); write.mutate("save"); }}> -

Choose Read for inventory only. A Read & Write token lets clients with the Hetzner checkbox create billable resources, modify them, or delete them. The checkbox also grants enrolled SSH access.

- {connection &&

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

} +

Choose Read for inventory only. A Read & Write token lets clients with the Hetzner checkbox create billable resources, modify them, or delete them. The checkbox also lets a client select this project’s servers for SSH. The server still decides whether to accept the client’s key.

+ {connection &&

Replacing the connection clears this project’s saved host fingerprints and client access. Client key pairs are kept. Reassign the Hetzner checkbox for clients you still want to use it.

}
{error} } {screen === "delete" && -

This removes the saved connection and its saved SSH keys from Factorize. It does not delete or change anything at Hetzner.

+

This removes the connection and its saved host fingerprints from Factorize. Client key pairs are kept. It does not delete or change anything at Hetzner.

{error} @@ -93,7 +94,7 @@ export function useHetznerIntegration() { {inventory.data.truncated &&

Showing the first 100 servers.

} } - {inventory.data && } + {inventory.data && <>}
} , }; diff --git a/packages/app/test/functional/hetzner.spec.mjs b/packages/app/test/functional/hetzner.spec.mjs index a0251d89..f561cd7e 100644 --- a/packages/app/test/functional/hetzner.spec.mjs +++ b/packages/app/test/functional/hetzner.spec.mjs @@ -3,7 +3,8 @@ import { test, expect } from "./fixtures.mjs"; test("an owner saves a read-only Hetzner project, views inventory, replaces the token without a separate permission switch, and confirms local deletion", async ({ page, origin }) => { const token = "syntheticReadOnlyProjectToken", writeToken = "syntheticReadWriteProjectToken"; const requests = []; - let connection = null, unavailable = true; + let connection = null, unavailable = true, verifiedPin = null; + const hostFingerprint = "SHA256:" + "A".repeat(43); const requestId = "f0bda107-b72f-4a94-8148-c4282983b994"; await page.route("**/api/v1/**", route => { const path = new URL(route.request().url()).pathname; @@ -35,6 +36,13 @@ test("an owner saves a read-only Hetzner project, views inventory, replaces the expect(route.request().method()).toBe("GET"); return route.fulfill({ json: { servers: [{ id: 41, name: "ci-worker", status: "running", location: "hel1" }], truncated: true } }); } + if (path === "/api/v1/ssh/hetzner-targets") return route.fulfill({ json: { targets: verifiedPin ? [verifiedPin] : [] } }); + if (path === "/api/v1/ssh/hetzner-targets/41") { + expect(route.request().method()).toBe("PUT"); + expect(route.request().postDataJSON()).toEqual({ username: "runner", hostFingerprint }); + verifiedPin = { serverId: 41, username: "runner", hostFingerprint, needsVerification: false }; + return route.fulfill({ json: verifiedPin }); + } if (path === "/api/v1/fly/connection") return route.fulfill({ json: { connection: null } }); if (path === "/api/v1/integrations/bearer") return route.fulfill({ json: { integrations: [], revision: 0 } }); if (path === "/api/v1/x/connections" || path === "/api/v1/integrations/cloudflare") return route.fulfill({ json: { connections: [] } }); @@ -62,6 +70,13 @@ test("an owner saves a read-only Hetzner project, views inventory, replaces the await expect(inventory.getByRole("table").getByRole("row", { name: "ci-worker running hel1" })).toBeVisible(); await expect(inventory.getByText("Showing the first 100 servers.")).toBeVisible(); expect(requests).toContain("inventory"); + const ssh = inventory.getByRole("region", { name: "Hetzner SSH commands" }); + await ssh.getByLabel("Server for SSH commands").selectOption("41"); + await ssh.getByLabel("SSH username", { exact: true }).fill("runner"); + await ssh.getByLabel("Verified SSH host fingerprint").fill(hostFingerprint); + await ssh.getByRole("button", { name: "Save verified fingerprint" }).click(); + await expect(ssh.getByText("SSH fingerprint verified and saved.")).toBeVisible(); + await expect(ssh.getByText("Verified", { exact: true })).toBeVisible(); await inventory.getByRole("button", { name: "Close Hetzner Cloud servers" }).click(); await row.getByRole("button", { name: "Actions for Hetzner Cloud · Fixture project" }).click(); await page.getByRole("menuitem", { name: "Replace connection", exact: true }).click(); diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index 737b8495..5cfb9267 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -88,9 +88,18 @@ The broker can reuse the authenticated connection for up to 30 seconds idle and no more than two minutes in total. A timed-out command may still have run; do not retry without reconciling its effects. -The Hetzner checkbox governs native API access and the legacy Hetzner -authentication probe. It does not remove installed server keys or govern -the generic SSH tool. Removing an authorized key on the server denies fresh +For an existing Hetzner Cloud server, list the project inventory through +`request_api` or open **View servers** in Factorize. In **SSH commands**, +choose the server and save its independently verified Ed25519 host +fingerprint and the SSH username. The client can then call `ssh_exec` +with `hetznerServerId` instead of `targetId`. Factorize checks the connected +project and resolves its current address through Hetzner; it never trusts the +first SSH response. A changed host fingerprint stops execution and requires +verification again. + +The Hetzner checkbox governs provider access, including the server-ID lookup. +It does not install or remove authorized keys on the server and does not +govern generic targets selected by `targetId`. Removing an authorized key on the server denies fresh SSH connections; terminate the existing connection on the server too if revocation must be immediate. Previously installed probe-only keys remain probe-only unless the server operator changes the authorization. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index cced6edc..01f3af4b 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -418,9 +418,18 @@ The broker can reuse the authenticated connection for up to 30 seconds idle and no more than two minutes in total. A timed-out command may still have run; do not retry without reconciling its effects. -The Hetzner checkbox governs native API access and the legacy Hetzner -authentication probe. It does not remove installed server keys or govern -the generic SSH tool. Removing an authorized key on the server denies fresh +For an existing Hetzner Cloud server, list the project inventory through +`request_api` or open **View servers** in Factorize. In **SSH commands**, +choose the server and save its independently verified Ed25519 host +fingerprint and the SSH username. The client can then call `ssh_exec` +with `hetznerServerId` instead of `targetId`. Factorize checks the connected +project and resolves its current address through Hetzner; it never trusts the +first SSH response. A changed host fingerprint stops execution and requires +verification again. + +The Hetzner checkbox governs provider access, including the server-ID lookup. +It does not install or remove authorized keys on the server and does not +govern generic targets selected by `targetId`. Removing an authorized key on the server denies fresh SSH connections; terminate the existing connection on the server too if revocation must be immediate. Previously installed probe-only keys remain probe-only unless the server operator changes the authorization. @@ -524,7 +533,7 @@ its input and enforces the operation's required scope. | `revoke_vm_permissions` | Revoke a VM's Factorize permissions. The VM keeps running. Requires vms:edit. | | `run_aws_script` | Run Python in the AWS-hosted MCP sandbox through an AWS connection whose owner granted this OAuth installation Use access. The customer role controls AWS API permissions; permitted writes can change resources and incur charges. Never assume a retry after timeout is safe. | | `set_event_processing_acknowledgments` | Opt in to processing acknowledgments for future occurrences on your exact MCP subscription. Turning off waives unresolved acknowledgments and clears cooldown; does not alter standard MCP subscription behavior. | -| `ssh_exec` | Run one non-interactive SSH command on a saved target. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly. | +| `ssh_exec` | Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. The Hetzner server must have a verified host fingerprint. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly. | | `test_trigger_webhook_conditions` | Evaluate conditions on supplied prepared webhook context. No authentication of the example, routing, live GitHub verification, or Trigger firing. | | `update_app` | Update redirect URLs, visibility, or enabled state for a registered app. | | `update_event` | Create a new Event payload schema revision; existing occurrences retain their original revision. | diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 23b58d3f..6aef4555 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -62,7 +62,7 @@ its input and enforces the operation's required scope. | `revoke_vm_permissions` | Revoke a VM's Factorize permissions. The VM keeps running. Requires vms:edit. | | `run_aws_script` | Run Python in the AWS-hosted MCP sandbox through an AWS connection whose owner granted this OAuth installation Use access. The customer role controls AWS API permissions; permitted writes can change resources and incur charges. Never assume a retry after timeout is safe. | | `set_event_processing_acknowledgments` | Opt in to processing acknowledgments for future occurrences on your exact MCP subscription. Turning off waives unresolved acknowledgments and clears cooldown; does not alter standard MCP subscription behavior. | -| `ssh_exec` | Run one non-interactive SSH command on a saved target. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly. | +| `ssh_exec` | Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. The Hetzner server must have a verified host fingerprint. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly. | | `test_trigger_webhook_conditions` | Evaluate conditions on supplied prepared webhook context. No authentication of the example, routing, live GitHub verification, or Trigger firing. | | `update_app` | Update redirect URLs, visibility, or enabled state for a registered app. | | `update_event` | Create a new Event payload schema revision; existing occurrences retain their original revision. | diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 7f84e29f..e06c259e 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -5472,6 +5472,203 @@ paths: schema: type: string pattern: ^[1-9][0-9]*$ + /api/v1/ssh/hetzner-targets: + get: + summary: List verified SSH identities for the connected Hetzner project + responses: + "200": + description: Targets + content: + application/json: + schema: + type: object + properties: + targets: + type: array + items: + type: object + properties: + username: + type: string + pattern: ^[a-z_][a-z0-9_-]{0,31}$ + hostFingerprint: + type: string + pattern: ^SHA256:[A-Za-z0-9+/]{43}$ + serverId: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + needsVerification: + default: false + type: boolean + required: + - username + - hostFingerprint + - serverId + - needsVerification + additionalProperties: false + required: + - targets + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the integrations:read scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: get_api_v1_ssh_hetzner_targets + tags: + - ssh + security: + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + /api/v1/ssh/hetzner-targets/{serverId}: + put: + summary: Save an independently verified Hetzner SSH fingerprint + responses: + "200": + description: Target + content: + application/json: + schema: + type: object + properties: + username: + type: string + pattern: ^[a-z_][a-z0-9_-]{0,31}$ + hostFingerprint: + type: string + pattern: ^SHA256:[A-Za-z0-9+/]{43}$ + serverId: + type: integer + exclusiveMinimum: 0 + maximum: 9007199254740991 + needsVerification: + default: false + type: boolean + required: + - username + - hostFingerprint + - serverId + - needsVerification + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "415": + $ref: "#/components/responses/Error415" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: put_api_v1_ssh_hetzner_targets_serverId + tags: + - ssh + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: serverId + in: path + required: true + schema: + type: string + pattern: ^[1-9][0-9]*$ + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + username: + type: string + pattern: ^[a-z_][a-z0-9_-]{0,31}$ + hostFingerprint: + type: string + pattern: ^SHA256:[A-Za-z0-9+/]{43}$ + required: + - username + - hostFingerprint + additionalProperties: false + delete: + summary: Remove a saved Hetzner SSH fingerprint + responses: + "200": + description: Removal + content: + application/json: + schema: + type: object + properties: + deleted: + type: boolean + required: + - deleted + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + description: |- + Requires the integrations:write scope. + + An interactive owner session is required; bearer tokens cannot call this operation. + operationId: delete_api_v1_ssh_hetzner_targets_serverId + tags: + - ssh + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: serverId + in: path + required: true + schema: + type: string + pattern: ^[1-9][0-9]*$ /api/v1/ssh/targets: get: summary: List saved SSH target identities