From 01595ca235f910cfa0779fb45356b4045d72d3c0 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Fri, 27 Nov 2026 16:28:34 -0700 Subject: [PATCH] Pin Hetzner SSH host fingerprint on first successful login --- packages/api/src/ssh/api/contracts.ts | 12 +++-- packages/api/src/ssh/api/mcp.ts | 2 +- .../api/src/ssh/application/hetzner-target.ts | 49 +++++++++++++++---- .../api/src/ssh/transport/edgeport-exec.ts | 12 ++++- packages/api/src/ssh/transport/exec-broker.ts | 29 ++++++++--- .../api/test/fixtures/hetzner-ssh-worker.ts | 9 +++- .../hetzner-ssh-discovery.postgres.test.ts | 33 +++++++++---- .../integrations/hetzner-ssh-commands.tsx | 4 +- packages/app/test/functional/hetzner.spec.mjs | 2 +- packages/docs/integrations/oauth.mdx | 21 +++++--- packages/docs/llms-full.txt | 23 +++++---- packages/docs/mcp/tools.mdx | 2 +- scripts/hetzner-ssh-runtime.test.mjs | 7 +++ 13 files changed, 148 insertions(+), 57 deletions(-) diff --git a/packages/api/src/ssh/api/contracts.ts b/packages/api/src/ssh/api/contracts.ts index a19ec3f0..bb2b4fa2 100644 --- a/packages/api/src/ssh/api/contracts.ts +++ b/packages/api/src/ssh/api/contracts.ts @@ -1,8 +1,9 @@ import { z } from "zod"; import { isPublicAddress } from "../../proxy/transport/public-address"; +const sshUsername = z.string().regex(/^[a-z_][a-z0-9_-]{0,31}$/).refine(username => username !== "root", "Use a non-root account."); const target = { - username: z.string().regex(/^[a-z_][a-z0-9_-]{0,31}$/).refine(username => username !== "root", "Use a non-root account."), + username: sshUsername, hostFingerprint: z.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/), }; export const sshTargetInput = z.strictObject({ @@ -15,10 +16,11 @@ export const hetznerSshServerId = z.number().int().positive().max(Number.MAX_SAF 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() }); -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."); +const execFields = z.strictObject({ targetId: z.uuid().optional(), hetznerServerId: hetznerSshServerId.optional(), username: sshUsername.optional(), command: z.string().min(1).max(4096).refine(command => !command.includes("\0")) }); +const oneSelector = (value: { targetId?: string; hetznerServerId?: number; username?: string }) => + (value.targetId !== undefined) !== (value.hetznerServerId !== undefined) && + (value.username === undefined || value.hetznerServerId !== undefined); +export const sshExecInput = execFields.refine(oneSelector, "Supply either targetId or hetznerServerId; username is only for Hetzner targets."); 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(), diff --git a/packages/api/src/ssh/api/mcp.ts b/packages/api/src/ssh/api/mcp.ts index e56c7b5a..b1d02e98 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. 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.", + mcpTool>(null, "ssh_exec", "Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. For Hetzner, Factorize saves the Ed25519 host fingerprint after the first successful login and blocks changes. Set username to a non-root account with the client key installed (default: factorize-agent or the saved username). 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/application/hetzner-target.ts b/packages/api/src/ssh/application/hetzner-target.ts index 28acef05..700c6358 100644 --- a/packages/api/src/ssh/application/hetzner-target.ts +++ b/packages/api/src/ssh/application/hetzner-target.ts @@ -25,20 +25,49 @@ export function hetznerSshAllowed(db: DatabaseClient, caller: SshClientAuthority 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); +export async function resolveHetznerSshTarget(env: Env, caller: SshClientAuthority, serverId: number, username?: string) { + const database = databaseFor(env), db = database.pool; + const { 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 pin = await pins.get(serverId); + const unverified = () => new ServiceError(412, "ssh_host_unverified", "Recheck this server's SSH host identity before connecting."); + if (!project || (pin && (pin.needsVerification || pin.projectRevision !== project.revision))) throw unverified(); 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."); - } + if (!isPublicAddress(server.ipv4) || server.connectionRevision !== project.revision) throw unverified(); + + const target = { + id: pin?.revision ?? crypto.randomUUID(), + name: "Hetzner " + serverId, + address: server.ipv4, + username: username ?? pin?.username ?? "factorize-agent", + hostFingerprint: pin?.hostFingerprint ?? null, + }; + const persist = async (observed: string): Promise<"saved" | "changed" | "stale"> => + database.transaction(async sql => { + await lockIntegrationTopology(sql, caller.tenantId); + const scoped = hetznerSshContext(env, caller, sql); + if (!await hetznerSshAllowed(sql, caller) || (await scoped.connections.get(sql))?.revision !== project.revision) return "stale"; + const latest = await scoped.pins.get(serverId); + if (latest) { + if (latest.needsVerification || latest.projectRevision !== project.revision) return "stale"; + if (latest.hostFingerprint !== observed) { + // A concurrent first connection or owner write won. Never overwrite its fingerprint. + return "changed"; + } + target.id = latest.revision; + } else { + await scoped.pins.save({ serverId, revision: target.id, username: target.username, + hostFingerprint: observed, projectRevision: project.revision, needsVerification: false }); + } + target.hostFingerprint = observed; + return "saved"; + }); + return { - target: { id: pin.revision, name: "Hetzner " + serverId, address: server.ipv4, username: pin.username, hostFingerprint: pin.hostFingerprint }, + target, persist, markMismatch: async () => { - const database = databaseFor(env); + if (!pin) return; await database.transaction(async sql => { await lockIntegrationTopology(sql, caller.tenantId); const scoped = hetznerSshContext(env, caller, sql).pins; @@ -50,7 +79,7 @@ export async function resolveHetznerSshTarget(env: Env, caller: SshClientAuthori }, 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); + return Boolean(scope && latest?.revision === target.id && !latest.needsVerification && active?.revision === project.revision); }, }; } diff --git a/packages/api/src/ssh/transport/edgeport-exec.ts b/packages/api/src/ssh/transport/edgeport-exec.ts index fad62b02..0de43751 100644 --- a/packages/api/src/ssh/transport/edgeport-exec.ts +++ b/packages/api/src/ssh/transport/edgeport-exec.ts @@ -8,13 +8,21 @@ const OUTPUT_LIMIT = 32 * 1024; 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"); +type ConnectionTarget = Omit & { hostFingerprint: string | null }; + +export async function openSshSession(target: ConnectionTarget, privateKey: string, port = 22, observe?: (fingerprint: string) => void) { + const expected = target.hostFingerprint === null ? null : Buffer.from(target.hostFingerprint.slice("SHA256:".length), "base64"); 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) => { + if (!expected) { + if (type !== "ssh-ed25519" || !observe) return false; + // edgeport verifies the server's proof of possession before invoking this callback. + observe("SHA256:" + createHash("sha256").update(wireKey).digest("base64").replace(/=+$/, "")); + return true; + } const matches = type === "ssh-ed25519" && timingSafeEqual(expected, createHash("sha256").update(wireKey).digest()); if (!matches) mismatch = true; return matches; diff --git a/packages/api/src/ssh/transport/exec-broker.ts b/packages/api/src/ssh/transport/exec-broker.ts index 9dff3b52..1abb3ea4 100644 --- a/packages/api/src/ssh/transport/exec-broker.ts +++ b/packages/api/src/ssh/transport/exec-broker.ts @@ -6,7 +6,7 @@ import { SshClientKeyRepository } from "../../credentials/storage/ssh-client-key import { databaseFor } from "../../postgres/database"; import { ServiceError } from "../../service-contract"; import { resolveHetznerSshTarget } from "../application/hetzner-target"; -import { sshBrokerRequest, sshRoutingTarget, type SshTarget } from "../api/contracts"; +import { sshBrokerRequest, sshRoutingTarget } from "../api/contracts"; import { activeSshClient } from "../application/ssh-service"; import { SshTargetRepository } from "../storage/target-repository"; import { execBounded, openSshSession, SshHostFingerprintMismatch, SSH_COMMAND_MS, SSH_CONNECT_MS } from "./edgeport-exec"; @@ -39,19 +39,20 @@ export class SshExecBroker extends DurableObject { clearTimeout(this.idle); try { const input = sshBrokerRequest.parse(await req.json()); - const { authority, targetId, hetznerServerId, command } = input; + const { authority, targetId, hetznerServerId, username, 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 }); } - let target: SshTarget | null; + let target: Parameters[0] | null; + let persist: Awaited>["persist"] | undefined; let current: () => Promise; let markMismatch: (() => Promise) | undefined; if (hetznerServerId !== undefined) { try { - const resolved = await resolveHetznerSshTarget(this.env, authority, hetznerServerId); - ({ target, current, markMismatch } = resolved); + const resolved = await resolveHetznerSshTarget(this.env, authority, hetznerServerId, username); + ({ target, current, markMismatch, persist } = resolved); } catch (error) { this.close(); const status = error instanceof ServiceError && (error.status === 403 || error.status === 412) ? error.status : 424; @@ -67,11 +68,16 @@ export class SshExecBroker extends DurableObject { if (!key) { this.close(); return new Response(null, { status: 409 }); } const now = Date.now(); - const fingerprint = JSON.stringify([target.id, target.address, target.username, target.hostFingerprint, key.publicKey]); + const identity = (t: NonNullable) => JSON.stringify([t.id, t.address, t.username, t.hostFingerprint, key.publicKey]); + const fingerprint = identity(target); 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) { - const pending = openSshSession(target, key.privateKey); + let observed: string | undefined; + const firstUse = target.hostFingerprint === null; + const pending = firstUse + ? openSshSession(target, key.privateKey, 22, fingerprint => { observed = fingerprint; }) + : openSshSession(target, key.privateKey); try { const transport = await deadline(pending, SSH_CONNECT_MS); this.session = { transport, opened: Date.now(), lastUsed: Date.now(), fingerprint }; @@ -83,6 +89,15 @@ export class SshExecBroker extends DurableObject { } return new Response(null, { status: 422 }); } + if (firstUse) { + // Never save a key from a failed login or run a command before the pin is durable. + const status = observed && persist ? await persist(observed) : "stale"; + if (status !== "saved") { + this.close(); + return new Response(null, { status: status === "changed" ? 421 : 412 }); + } + this.session.fingerprint = identity(target); + } } const session = this.session; if (!await activeSshClient(db, authority)) { this.close(); return new Response(null, { status: 401 }); } diff --git a/packages/api/test/fixtures/hetzner-ssh-worker.ts b/packages/api/test/fixtures/hetzner-ssh-worker.ts index cda58b55..786c9de1 100644 --- a/packages/api/test/fixtures/hetzner-ssh-worker.ts +++ b/packages/api/test/fixtures/hetzner-ssh-worker.ts @@ -14,9 +14,16 @@ export class FixtureBroker extends DurableObject { const path = new URL(request.url).pathname; if (path === "/close") { await this.session?.close(); this.session = undefined; return new Response(null, {status: 204}); } if (path === "/public") return Response.json({ publicKey: this.client.publicKey }); - if (path !== "/probe" && path !== "/exec") return new Response(null, { status: 404 }); + if (path !== "/probe" && path !== "/exec" && path !== "/observe") return new Response(null, { status: 404 }); const { port, fingerprint, command } = await request.json<{ port: number; fingerprint: string; command?: string }>(); try { + if (path === "/observe") { + let observed: string | undefined; + const session = await openSshSession({ id: "test", name: "fixture", address: "127.0.0.1", + username: "fixture-check", hostFingerprint: null }, this.client.privateKey, port, value => { observed = value; }); + await session.close(); + return Response.json({ fingerprint: observed }); + } if (path === "/exec" && command) { const reusedConnection = Boolean(this.session); this.session ??= await openSshSession({ id: "test", name: "fixture", address: "127.0.0.1", diff --git a/packages/api/test/hetzner-ssh-discovery.postgres.test.ts b/packages/api/test/hetzner-ssh-discovery.postgres.test.ts index 32bdff2e..7c4d67ba 100644 --- a/packages/api/test/hetzner-ssh-discovery.postgres.test.ts +++ b/packages/api/test/hetzner-ssh-discovery.postgres.test.ts @@ -20,7 +20,7 @@ vi.mock("../src/ssh/transport/edgeport-exec", () => ({ 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 () => { +it.skipIf(!url)("pins a Hetzner SSH fingerprint on the first successful login and fences changes 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", @@ -67,34 +67,47 @@ it.skipIf(!url)("resolves Hetzner IDs under the live project grant and fences a 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()).toContain("ssh_busy_or_no_key"); + expect(openSshSession).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: [] }); + vi.mocked(openSshSession).mockImplementationOnce(async (_target, _privateKey, _port, observe) => { + observe?.(pin.hostFingerprint); + throw new Error("login refused"); + }); + expect(await run({ hetznerServerId: serverId, username: pin.username })).toContain("ssh_login_failed"); + expect(await (await ownerRequest(path, "GET")).json()).toEqual({ targets: [] }); + expect(execBounded).not.toHaveBeenCalled(); + vi.mocked(openSshSession).mockImplementationOnce(async (target, _privateKey, _port, observe) => { + expect(target).toMatchObject({ address, username: pin.username, hostFingerprint: null }); + observe?.(pin.hostFingerprint); + return session as unknown as Awaited>; + }); + + expect(await run({ hetznerServerId: serverId, username: pin.username })).toContain('"stdout":"ok"'); 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 }); + expect(await run()).toContain('"reusedConnection":true'); // 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(execBounded).toHaveBeenCalledTimes(2); expect(await run()).toContain("ssh_host_unverified"); - expect(openSshSession).toHaveBeenCalledTimes(2); + expect(openSshSession).toHaveBeenCalledTimes(3); 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 }); + expect(vi.mocked(openSshSession).mock.calls[3]?.[0]).toMatchObject({ address, hostFingerprint: verified.hostFingerprint }); missing = true; expect(await run()).toContain("hetzner_ssh_lookup_failed"); - expect(execBounded).toHaveBeenCalledTimes(2); + expect(execBounded).toHaveBeenCalledTimes(3); await setAccess(false); expect(await run()).toContain("hetzner_ssh_access_denied"); await project.save("Replacement", "synthetic-replacement"); diff --git a/packages/app/src/features/integrations/hetzner-ssh-commands.tsx b/packages/app/src/features/integrations/hetzner-ssh-commands.tsx index 786e9dcd..214c3119 100644 --- a/packages/app/src/features/integrations/hetzner-ssh-commands.tsx +++ b/packages/app/src/features/integrations/hetzner-ssh-commands.tsx @@ -32,12 +32,12 @@ export function HetznerSshCommands({ servers }: { servers: Array<{ id: number; n 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.

+

Factorize saves the host fingerprint after the first successful SSH login and blocks changes. To verify the first fingerprint independently or replace a changed one, check it through a trusted console and save it here. Install the client’s public key on the server’s non-root SSH account before connecting.

{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"} + {pin.needsVerification ? "Fingerprint changed. Verify again." : "Fingerprint saved"}
)} {servers.length > 0 &&
{ event.preventDefault(); write.mutate({ serverId: server }); }}> diff --git a/packages/app/test/functional/hetzner.spec.mjs b/packages/app/test/functional/hetzner.spec.mjs index f561cd7e..cff6702b 100644 --- a/packages/app/test/functional/hetzner.spec.mjs +++ b/packages/app/test/functional/hetzner.spec.mjs @@ -76,7 +76,7 @@ test("an owner saves a read-only Hetzner project, views inventory, replaces the 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 expect(ssh.getByText("Fingerprint saved", { 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 5cfb9267..13b6fb01 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -88,14 +88,19 @@ 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. -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. +For a Hetzner Cloud server, list the project inventory through `request_api` +or open **View servers** in Factorize. Call `ssh_exec` with `hetznerServerId` +instead of `targetId`. Install the client's public key on a non-root account +first. Factorize uses the saved username, or `factorize-agent` if none is +saved; use the optional `username` argument to choose another account. + +Factorize looks up the current address through the connected Hetzner project +and saves the Ed25519 host fingerprint after the first successful SSH login, +before executing a command. This is trust on first use, not independent +verification of the initial fingerprint. To verify it out of band, save it +in **SSH commands** before connecting. A changed fingerprint blocks execution +until an owner verifies and saves the replacement. Generic `targetId` targets +still require a fingerprint before the first connection. 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 diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 01f3af4b..cf379801 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -418,14 +418,19 @@ 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. -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. +For a Hetzner Cloud server, list the project inventory through `request_api` +or open **View servers** in Factorize. Call `ssh_exec` with `hetznerServerId` +instead of `targetId`. Install the client's public key on a non-root account +first. Factorize uses the saved username, or `factorize-agent` if none is +saved; use the optional `username` argument to choose another account. + +Factorize looks up the current address through the connected Hetzner project +and saves the Ed25519 host fingerprint after the first successful SSH login, +before executing a command. This is trust on first use, not independent +verification of the initial fingerprint. To verify it out of band, save it +in **SSH commands** before connecting. A changed fingerprint blocks execution +until an owner verifies and saves the replacement. Generic `targetId` targets +still require a fingerprint before the first connection. 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 @@ -533,7 +538,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. 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. | +| `ssh_exec` | Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. For Hetzner, Factorize saves the Ed25519 host fingerprint after the first successful login and blocks changes. Set username to a non-root account with the client key installed (default: factorize-agent or the saved username). 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 6aef4555..e3e74762 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. 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. | +| `ssh_exec` | Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. For Hetzner, Factorize saves the Ed25519 host fingerprint after the first successful login and blocks changes. Set username to a non-root account with the client key installed (default: factorize-agent or the saved username). 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/scripts/hetzner-ssh-runtime.test.mjs b/scripts/hetzner-ssh-runtime.test.mjs index e23e04be..3c0c560d 100644 --- a/scripts/hetzner-ssh-runtime.test.mjs +++ b/scripts/hetzner-ssh-runtime.test.mjs @@ -130,6 +130,13 @@ test("workerd keeps legacy probes command-free and reuses generic SSH command ch allowedKey = false; assert.equal((await command("denied")).status, 502); assert.equal(channels, 3); + const observe = () => fetch(url + "/observe", { method: "POST", body: JSON.stringify({ port: server.address().port }) }); + assert.equal((await observe()).status, 502, "unauthenticated login cannot supply a pin"); + allowedKey = true; + const observed = await observe(); + assert.equal(observed.status, 200); + assert.deepEqual(await observed.json(), { fingerprint }); + assert.equal(channels, 3, "observing the host key opens no command channel"); } finally { if (worker && worker.exitCode === null) { const exited = once(worker, "exit"); worker.kill(); await exited.catch(() => {}); } for (const peer of peers) peer.end();