From 38cf5ba67397eec4b5a9e4e86ba5f46fd75c5f32 Mon Sep 17 00:00:00 2001 From: Brendan Asselstine Date: Fri, 27 Nov 2026 14:53:39 -0700 Subject: [PATCH] Run SSH commands with stable per-client keys --- package-lock.json | 23 ++ packages/api-client/src/schema.d.ts | 164 ++++++++++++++ .../migrations/0121_ssh_client_identity.sql | 5 + packages/api/package.json | 1 + packages/api/src/api-service.ts | 2 + packages/api/src/cloudflare-entry.ts | 1 + packages/api/src/config/bindings.ts | 1 + .../storage/hetzner-client-key-repository.ts | 21 +- .../storage/ssh-client-key-repository.ts | 28 +++ packages/api/src/integrations/api/rest.ts | 2 + packages/api/src/ssh/api/contracts.ts | 23 ++ packages/api/src/ssh/api/mcp.ts | 10 + packages/api/src/ssh/api/rest.ts | 20 ++ .../api/src/ssh/application/ssh-service.ts | 90 ++++++++ .../api/src/ssh/storage/target-repository.ts | 38 ++++ .../api/src/ssh/transport/edgeport-exec.ts | 40 ++++ packages/api/src/ssh/transport/exec-broker.ts | 84 +++++++ packages/api/src/transport/mcp/registry.ts | 3 +- packages/api/test/client-ssh.postgres.test.ts | 91 ++++++++ .../api/test/fixtures/hetzner-ssh-worker.ts | 19 +- packages/api/wrangler.jsonc | 5 +- packages/docs/integrations/oauth.mdx | 28 ++- packages/docs/llms-full.txt | 30 ++- packages/docs/mcp/tools.mdx | 2 + packages/docs/openapi.yaml | 210 ++++++++++++++++++ scripts/hetzner-ssh-runtime.test.mjs | 43 +++- scripts/hosting-invariants.test.mjs | 4 +- 27 files changed, 955 insertions(+), 33 deletions(-) create mode 100644 packages/api/migrations/0121_ssh_client_identity.sql create mode 100644 packages/api/src/credentials/storage/ssh-client-key-repository.ts create mode 100644 packages/api/src/ssh/api/contracts.ts create mode 100644 packages/api/src/ssh/api/mcp.ts create mode 100644 packages/api/src/ssh/api/rest.ts create mode 100644 packages/api/src/ssh/application/ssh-service.ts create mode 100644 packages/api/src/ssh/storage/target-repository.ts create mode 100644 packages/api/src/ssh/transport/edgeport-exec.ts create mode 100644 packages/api/src/ssh/transport/exec-broker.ts create mode 100644 packages/api/test/client-ssh.postgres.test.ts diff --git a/package-lock.json b/package-lock.json index a2b95f02..f47872b9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3016,6 +3016,18 @@ "node": "^22.20 || ^24.12 || >=25" } }, + "node_modules/@noble/ciphers": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz", + "integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@nodable/entities": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz", @@ -5853,6 +5865,16 @@ } } }, + "node_modules/edgeport": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/edgeport/-/edgeport-1.0.6.tgz", + "integrity": "sha512-3pvBm7JiNguC0nVspf1Pz211nE6QB1G04tN9vmfbmZ6/dpr9QRM3A1JyeQcq+Fvh5HnhD6xTUCLSmMu0XIIDgw==", + "license": "MIT", + "dependencies": { + "@noble/ciphers": "^2.2.0", + "bcrypt-pbkdf": "^1.0.2" + } + }, "node_modules/enhanced-resolve": { "version": "5.24.5", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz", @@ -9466,6 +9488,7 @@ "aws4fetch": "1.0.20", "cron-parser": "^5.10.1", "drizzle-orm": "^0.45.2", + "edgeport": "1.0.6", "fast-xml-parser": "5.12.1", "hono": "^4.11.4", "json-rules-engine": "^7.3.1", diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index f374d575..55aa884d 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/targets": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List saved SSH target identities + * @description Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_ssh_targets"]; + put?: never; + /** + * Save an independently verified SSH target identity + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_ssh_targets"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/ssh/targets/{targetId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Remove a saved SSH target + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_ssh_targets_targetId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/integrations/aws": { parameters: { query?: never; @@ -5843,6 +5893,120 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_ssh_targets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Targets */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + targets: { + name: string; + address: string; + username: string; + hostFingerprint: string; + /** Format: uuid */ + id: string; + }[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_ssh_targets: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + name: string; + address: string; + username: string; + hostFingerprint: string; + }; + }; + }; + responses: { + /** @description Target */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + name: string; + address: string; + username: string; + hostFingerprint: string; + /** Format: uuid */ + id: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_ssh_targets_targetId: { + parameters: { + query?: never; + header?: never; + path: { + targetId: 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_integrations_aws: { parameters: { query?: never; diff --git a/packages/api/migrations/0121_ssh_client_identity.sql b/packages/api/migrations/0121_ssh_client_identity.sql new file mode 100644 index 00000000..bc3d4498 --- /dev/null +++ b/packages/api/migrations/0121_ssh_client_identity.sql @@ -0,0 +1,5 @@ +-- Keep keys attached to saved clients, independent of provider connection lifecycle. +INSERT INTO app.connections (tenant_id, kind, encrypted_value) +SELECT tenant_id, replace(kind, 'hetzner-client-key:', 'ssh-client-key:'), encrypted_value +FROM app.connections WHERE kind LIKE 'hetzner-client-key:%' +ON CONFLICT (tenant_id, kind) DO NOTHING; diff --git a/packages/api/package.json b/packages/api/package.json index 5ba7dbfd..9d586f62 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -28,6 +28,7 @@ "aws4fetch": "1.0.20", "cron-parser": "^5.10.1", "drizzle-orm": "^0.45.2", + "edgeport": "1.0.6", "fast-xml-parser": "5.12.1", "hono": "^4.11.4", "json-rules-engine": "^7.3.1", diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index 66d6a8ac..b01f23ce 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,3 +1,4 @@ +import { SshService } from "./ssh/application/ssh-service"; import { HetznerClientKeyService } from "./integrations/application/hetzner-client-key"; import { AwsIntegrationService } from "./integrations/application/aws-service"; import { HetznerSshService } from "./integrations/application/hetzner-ssh"; @@ -47,6 +48,7 @@ export class ApiService { get integrations() { return new IntegrationsService(this.env, this.auth, scope => this.authorize(scope), scope => this.authorizeOwnerSession(scope)); } + get ssh() { return new SshService(this.env, this.auth, scope => this.authorizeOwnerSession(scope)); } 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/cloudflare-entry.ts b/packages/api/src/cloudflare-entry.ts index a7503ac6..1b63a660 100644 --- a/packages/api/src/cloudflare-entry.ts +++ b/packages/api/src/cloudflare-entry.ts @@ -2,6 +2,7 @@ import { WorkflowEntrypoint } from "cloudflare:workers"; import type { Env } from "./types"; export { default, AlarmCoordinator } from "./worker"; +export { SshExecBroker } from "./ssh/transport/exec-broker"; export { HetznerSshBroker } from "./integrations/providers/hetzner-ssh-broker"; // Preserve the deployed workflow binding while the retirement runs through release. diff --git a/packages/api/src/config/bindings.ts b/packages/api/src/config/bindings.ts index 8690840b..77ee56b8 100644 --- a/packages/api/src/config/bindings.ts +++ b/packages/api/src/config/bindings.ts @@ -1,4 +1,5 @@ export interface Env { + CLIENT_SSH?: DurableObjectNamespace; HETZNER_SSH?: DurableObjectNamespace; SCHEDULER?: DurableObjectNamespace; ASSETS: Fetcher; diff --git a/packages/api/src/credentials/storage/hetzner-client-key-repository.ts b/packages/api/src/credentials/storage/hetzner-client-key-repository.ts index 18e4dfac..c5880df2 100644 --- a/packages/api/src/credentials/storage/hetzner-client-key-repository.ts +++ b/packages/api/src/credentials/storage/hetzner-client-key-repository.ts @@ -1,20 +1 @@ -import { z } from "zod"; -import { decrypt, encrypt } from "../../crypto"; -import type { DatabaseClient } from "../../postgres/database"; - -const keyPair = z.strictObject({ privateKey: z.string().min(1), publicKey: z.string().regex(/^ssh-ed25519 [A-Za-z0-9+/]+=*$/) }); -type KeyPair = z.infer; - -export class HetznerClientKeyRepository { - constructor(private tenantId: string, private key: string) {} - - /** Call while holding the integration topology transaction lock. */ - async getOrCreate(sql: DatabaseClient, installationId: string, create: () => KeyPair) { - const kind = "hetzner-client-key:" + installationId; - const { rows } = await sql.query<{encrypted_value: string}>("SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, kind]); - if (rows[0]) return keyPair.parse(JSON.parse(await decrypt(rows[0].encrypted_value, this.key))); - const pair = keyPair.parse(create()); - await sql.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,$2,$3)", [this.tenantId, kind, await encrypt(JSON.stringify(pair), this.key)]); - return pair; - } -} +export { SshClientKeyRepository as HetznerClientKeyRepository } from "./ssh-client-key-repository"; diff --git a/packages/api/src/credentials/storage/ssh-client-key-repository.ts b/packages/api/src/credentials/storage/ssh-client-key-repository.ts new file mode 100644 index 00000000..17da81e3 --- /dev/null +++ b/packages/api/src/credentials/storage/ssh-client-key-repository.ts @@ -0,0 +1,28 @@ +import { z } from "zod"; +import { decrypt, encrypt } from "../../crypto"; +import type { DatabaseClient } from "../../postgres/database"; + +const keyPair = z.strictObject({ privateKey: z.string().min(1), publicKey: z.string().regex(/^ssh-ed25519 [A-Za-z0-9+/]+=*$/) }); +type KeyPair = z.infer; + +export class SshClientKeyRepository { + constructor(private tenantId: string, private key: string) {} + + async get(sql: DatabaseClient, installationId: string) { + const kind = "ssh-client-key:" + installationId; + const { rows } = await sql.query<{encrypted_value: string}>( + "SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, kind], + ); + return rows[0] ? keyPair.parse(JSON.parse(await decrypt(rows[0].encrypted_value, this.key))) : null; + } + + /** Call while holding the integration topology transaction lock. */ + async getOrCreate(sql: DatabaseClient, installationId: string, create: () => KeyPair) { + const kind = "ssh-client-key:" + installationId; + const existing = await this.get(sql, installationId); + if (existing) return existing; + const pair = keyPair.parse(create()); + await sql.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,$2,$3)", [this.tenantId, kind, await encrypt(JSON.stringify(pair), this.key)]); + return pair; + } +} diff --git a/packages/api/src/integrations/api/rest.ts b/packages/api/src/integrations/api/rest.ts index 2aa792c5..1946ff93 100644 --- a/packages/api/src/integrations/api/rest.ts +++ b/packages/api/src/integrations/api/rest.ts @@ -1,4 +1,5 @@ import { awsRoutes } from "./aws-rest"; +import { sshTargetRoutes } from "../../ssh/api/rest"; import { hetznerSshRoutes } from "./hetzner-ssh-rest"; import { hetznerConnectionInput, hetznerConnectionMetadata, hetznerInventory } from "./hetzner-contracts"; import { integrationRemovalConfirmation, integrationRemovalPreview, integrationRemovalTarget } from "../../integrations/api/integration-removal-contracts"; @@ -59,6 +60,7 @@ const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonne const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() }); export const integrationRoutes = [ ...hetznerSshRoutes, + ...sshTargetRoutes, ...awsRoutes, route("POST", "/api/v1/integrations/removal/preview", "integrations:write", { summary: "Preview what deleting one installed integration affects", diff --git a/packages/api/src/ssh/api/contracts.ts b/packages/api/src/ssh/api/contracts.ts new file mode 100644 index 00000000..0934c91a --- /dev/null +++ b/packages/api/src/ssh/api/contracts.ts @@ -0,0 +1,23 @@ +import { z } from "zod"; +import { isPublicAddress } from "../../proxy/transport/public-address"; + +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}$/), +}); +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")) }); +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(), +}); +export type SshTarget = z.infer; +export const sshClientAuthority = z.strictObject({ + tenantId: z.uuid(), userId: z.uuid(), sessionVersion: z.number().int().positive(), + 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 type SshClientAuthority = z.infer; diff --git a/packages/api/src/ssh/api/mcp.ts b/packages/api/src/ssh/api/mcp.ts new file mode 100644 index 00000000..1ff96eac --- /dev/null +++ b/packages/api/src/ssh/api/mcp.ts @@ -0,0 +1,10 @@ +import { z } from "zod"; +import { mcpTool } from "../../transport/mcp/tool"; +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.", + 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 new file mode 100644 index 00000000..6cc807a0 --- /dev/null +++ b/packages/api/src/ssh/api/rest.ts @@ -0,0 +1,20 @@ +import { z } from "zod"; +import { jsonSchema, route } from "../../transport/rest/route-contract"; +import { sshTarget, sshTargetInput } from "./contracts"; + +const ok = (description: string, schema: z.ZodType) => ({ + "200": { description, content: { "application/json": { schema: jsonSchema(schema, "output") } } }, +}); +export const sshTargetRoutes = [ + 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 }), + route("POST", "/api/v1/ssh/targets", "integrations:write", { + summary: "Save an independently verified SSH target identity", responses: ok("Target", sshTarget), + }, (service, { body }) => service.ssh.addTarget(body), { ownerSession: true, body: sshTargetInput, maxBodyBytes: 4096 }), + route("DELETE", "/api/v1/ssh/targets/{targetId}", "integrations:write", { + summary: "Remove a saved SSH target", responses: ok("Removal", z.object({ deleted: z.boolean() })), + }, (service, { params }) => service.ssh.removeTarget(params.targetId), { ownerSession: true, + parameters: z.object({ targetId: z.uuid() }), + }), +]; diff --git a/packages/api/src/ssh/application/ssh-service.ts b/packages/api/src/ssh/application/ssh-service.ts new file mode 100644 index 00000000..f6ae990f --- /dev/null +++ b/packages/api/src/ssh/application/ssh-service.ts @@ -0,0 +1,90 @@ +import type { z } from "zod"; +import { signingConfig } from "../../config/runtime"; +import { SshClientKeyRepository } from "../../credentials/storage/ssh-client-key-repository"; +import { generateHetznerSshKey } from "../../integrations/providers/hetzner-ssh-transport"; +import { lockIntegrationTopology } from "../../integrations/storage/integration-removal-topology"; +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 { SshTargetRepository } from "../storage/target-repository"; + +export async function activeSshClient(sql: DatabaseClient, caller: SshClientAuthority) { + if (caller.oauthExpiresAt <= Date.now() / 1000) return false; + const active = await sql.query(`SELECT 1 FROM app.oauth_installations i + JOIN app.members m ON m.tenant_id=i.tenant_id AND m.user_id=i.user_id + JOIN app.auth_users u ON u.id=m.user_id + WHERE i.tenant_id=$1 AND i.user_id=$2 AND i.id=$3 AND i.active_grant_id=$4 + AND m.session_version=$5 AND i.active_session_version=$5 AND i.revoked_at IS NULL + AND u.email_verified AND m.role='owner' AND ($6::text IS NULL OR i.client_id=$6)`, + [caller.tenantId, caller.userId, caller.oauthInstallationId, caller.oauthGrantId, caller.sessionVersion, caller.oauthClientId ?? null]); + return Boolean(active.rowCount); +} + +export class SshService { + constructor(private env: Env, private auth: OAuthProps, + private owner: (scope: "integrations:read" | "integrations:write") => Promise) {} + + private get db() { return databaseFor(this.env); } + private targets(sql: DatabaseClient) { + return new SshTargetRepository(sql, this.auth.tenantId, this.auth.userId, signingConfig(this.env).credentialKey); + } + + private async caller(sql: DatabaseClient) { + const forbidden = new ServiceError(403, "ssh_client_required", "Connect an active Factorize OAuth client."); + if (this.auth.authMethod !== "oauth") throw forbidden; + const { tenantId, userId, sessionVersion, oauthInstallationId, oauthClientId, oauthGrantId, oauthExpiresAt } = this.auth; + const parsed = sshClientAuthority.safeParse({ tenantId, userId, sessionVersion, + oauthInstallationId: oauthInstallationId ?? oauthGrantId, oauthClientId, oauthGrantId, oauthExpiresAt }); + if (!parsed.success || !await activeSshClient(sql, parsed.data)) throw forbidden; + return parsed.data; + } + + async publicKey() { + return this.db.transaction(async sql => { + await lockIntegrationTopology(sql, this.auth.tenantId); + const caller = await this.caller(sql); + const keys = new SshClientKeyRepository(this.auth.tenantId, signingConfig(this.env).credentialKey); + const { publicKey } = await keys.getOrCreate(sql, caller.oauthInstallationId, generateHetznerSshKey); + return { publicKey }; + }); + } + + async listTargets() { + await this.owner("integrations:read"); + return { targets: await this.targets(this.db.pool).list() }; + } + + async addTarget(input: z.infer) { + await this.owner("integrations:write"); + return this.db.transaction(async sql => { + await lockIntegrationTopology(sql, this.auth.tenantId); + const targets = this.targets(sql); + if ((await targets.list()).length >= 100) throw new ServiceError(409, "ssh_target_limit", "Remove a saved SSH target before adding another."); + return targets.add({ ...input, id: crypto.randomUUID() }); + }); + } + + async removeTarget(id: string) { + await this.owner("integrations:write"); + return { deleted: await this.targets(this.db.pool).remove(id) }; + } + + 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 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 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."); + default: throw new ServiceError(502, "ssh_outcome_unknown", "SSH disconnected or timed out. The command may have run. Do not retry blindly."); + } + } +} diff --git a/packages/api/src/ssh/storage/target-repository.ts b/packages/api/src/ssh/storage/target-repository.ts new file mode 100644 index 00000000..0c594083 --- /dev/null +++ b/packages/api/src/ssh/storage/target-repository.ts @@ -0,0 +1,38 @@ +import { decrypt, encrypt } from "../../crypto"; +import type { DatabaseClient } from "../../postgres/database"; +import { sshTarget, type SshTarget } from "../api/contracts"; + +export class SshTargetRepository { + constructor(private sql: DatabaseClient, private tenantId: string, private userId: string, private key: string) {} + private get prefix() { return "ssh-target:" + this.userId + ":"; } + + private async decode(encryptedValue: string) { + return sshTarget.parse(JSON.parse(await decrypt(encryptedValue, this.key))); + } + + async list() { + 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 Promise.all(rows.map(row => this.decode(row.encrypted_value))); + } + + async get(id: string) { + 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 + id] + ); + return rows[0] ? this.decode(rows[0].encrypted_value) : null; + } + + async add(value: SshTarget) { + await this.sql.query("INSERT INTO app.connections (tenant_id, kind, encrypted_value) VALUES ($1,$2,$3)", + [this.tenantId, this.prefix + value.id, await encrypt(JSON.stringify(value), this.key)]); + return value; + } + + async remove(id: string) { + const result = await this.sql.query("DELETE FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, this.prefix + id]); + return Boolean(result.rowCount); + } +} diff --git a/packages/api/src/ssh/transport/edgeport-exec.ts b/packages/api/src/ssh/transport/edgeport-exec.ts new file mode 100644 index 00000000..49685482 --- /dev/null +++ b/packages/api/src/ssh/transport/edgeport-exec.ts @@ -0,0 +1,40 @@ +import { createHash, timingSafeEqual } from "node:crypto"; +import { connect, type SshSession } from "edgeport/ssh"; +import type { SshTarget } from "../api/contracts"; + +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) { + const expected = Buffer.from(target.hostFingerprint.slice("SHA256:".length), "base64"); + return 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()) }, + }); +} + +export async function execBounded(session: SshSession, command: string) { + const channel = await session.execStream(command); + const read = async (stream: ReadableStream) => { + const reader = stream.getReader(), buffer = new Uint8Array(OUTPUT_LIMIT); + let size = 0, truncated = false; + try { + for (;;) { + const result = await reader.read(); + if (result.done) break; + const take = Math.min(OUTPUT_LIMIT - size, result.value.length); + if (take < result.value.length) truncated = true; + buffer.set(result.value.subarray(0, take), size); + size += take; + } + return { text: new TextDecoder().decode(buffer.subarray(0, size)), truncated }; + } finally { reader.releaseLock(); } + }; + try { + const [stdout, stderr, exit] = await Promise.all([read(channel.stdout), read(channel.stderr), channel.exit, channel.eof()]); + return { stdout: stdout.text, stderr: stderr.text, exitCode: exit.code, signal: exit.signal, truncated: stdout.truncated || stderr.truncated }; + } finally { await channel.close(); } +} diff --git a/packages/api/src/ssh/transport/exec-broker.ts b/packages/api/src/ssh/transport/exec-broker.ts new file mode 100644 index 00000000..d6e2f674 --- /dev/null +++ b/packages/api/src/ssh/transport/exec-broker.ts @@ -0,0 +1,84 @@ +import { DurableObject } from "cloudflare:workers"; +import type { SshSession } from "edgeport/ssh"; +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 { activeSshClient } from "../application/ssh-service"; +import { SshTargetRepository } from "../storage/target-repository"; +import { execBounded, openSshSession, SSH_COMMAND_MS, SSH_CONNECT_MS } from "./edgeport-exec"; + +const idleMs = 30_000, maxAgeMs = 120_000; + +function deadline(promise: Promise, timeout: number) { + let timer: ReturnType | undefined; + return Promise.race([promise, new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("SSH deadline exceeded")), Math.max(0, timeout)); + })]).finally(() => clearTimeout(timer)); +} + +export class SshExecBroker extends DurableObject { + private session?: { transport: SshSession; opened: number; lastUsed: number; fingerprint: string }; + private idle?: ReturnType; + private busy = false; + + private close() { + clearTimeout(this.idle); + const current = this.session; + this.session = undefined; + if (current) this.ctx.waitUntil(current.transport.close().catch(() => {})); + } + + override async fetch(req: Request): Promise { + if (req.method !== "POST" || new URL(req.url).pathname !== "/exec") return new Response(null, { status: 404 }); + if (this.busy) return new Response(null, { status: 409 }); + 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]); + 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); + 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]); + 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); + try { + const transport = await deadline(pending, SSH_CONNECT_MS); + this.session = { transport, opened: Date.now(), lastUsed: Date.now(), fingerprint }; + } catch { + this.ctx.waitUntil(pending.then(transport => transport.close()).catch(() => {})); + 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 }); } + 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)) { + this.close(); return new Response(null, { status: 502 }); + } + session.lastUsed = Date.now(); + return Response.json({ ...result, reusedConnection }); + } catch { + this.close(); + return new Response(null, { status: 502 }); + } finally { + this.busy = false; + if (this.session) this.idle = setTimeout(() => this.close(), Math.min(idleMs, Math.max(0, maxAgeMs - (Date.now() - this.session.opened)))); + } + } +} diff --git a/packages/api/src/transport/mcp/registry.ts b/packages/api/src/transport/mcp/registry.ts index 5e589da2..9ff31cbc 100644 --- a/packages/api/src/transport/mcp/registry.ts +++ b/packages/api/src/transport/mcp/registry.ts @@ -1,3 +1,4 @@ +import { sshTools } from "../../ssh/api/mcp"; import { subscriptionsProtocol, processingTools } from "../../subscriptions/api/mcp"; import { skillsProtocol } from "../../skills/api/mcp"; import { eventsProtocol, definitionTools, occurrenceTools } from "../../events/api/mcp"; @@ -11,7 +12,7 @@ import { McpServer } from "@modelcontextprotocol/server"; import type { ApiService } from "../../api-service"; import { SKILLS_EXTENSION } from "../../skills/api/mcp-skills"; -const tools = [...clientTools, ...proxyTools, ...exeTools, ...vmTools, ...appTools, ...githubTools, ...definitionTools, ...processingTools, ...occurrenceTools, ...triggerTools, ...tailTools, ...hetznerTools, ...awsTools]; +const tools = [...clientTools, ...proxyTools, ...exeTools, ...vmTools, ...appTools, ...githubTools, ...definitionTools, ...processingTools, ...occurrenceTools, ...triggerTools, ...tailTools, ...hetznerTools, ...sshTools, ...awsTools]; const scopes = new Map(tools.map(tool => [tool.name, tool.scope])); if (scopes.size !== tools.length) throw new Error("Duplicate MCP tool declaration."); export const requiredMcpToolScope = (name: string) => scopes.get(name) ?? undefined; diff --git a/packages/api/test/client-ssh.postgres.test.ts b/packages/api/test/client-ssh.postgres.test.ts new file mode 100644 index 00000000..3977020f --- /dev/null +++ b/packages/api/test/client-ssh.postgres.test.ts @@ -0,0 +1,91 @@ +import { readFile } from "node:fs/promises"; +import { expect, it, vi } from "vitest"; +import { HetznerConnectionRepository } from "../src/credentials/storage/hetzner-connection-repository"; +import { SshClientKeyRepository } from "../src/credentials/storage/ssh-client-key-repository"; +import { generateHetznerSshKey } from "../src/integrations/providers/hetzner-ssh-transport"; +import worker from "../src/worker"; +import type { 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 {} })); +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)("keeps a separate client key across OAuth and project changes and restricts target management to the owner session", async () => { + const f = await loadingFixture(url!); + const first = crypto.randomUUID(), second = crypto.randomUUID(); + const auth = (id = first, grant = "grant-" + id): OAuthProps => ({ ...f.auth, scopes: [], authMethod: "oauth", + oauthInstallationId: id, oauthClientId: "same-app", oauthGrantId: grant, 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 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 legacyKey = generateHetznerSshKey(); + const db = f.db.pool; + try { + for (const id of [first, second]) 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,'same-app','https://example.test',$4,$5,ARRAY[]::text[],ARRAY[]::text[])`, + [f.tenantId,f.userId,id,"grant-"+id,f.auth.sessionVersion]); + const repo = new SshClientKeyRepository(f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await repo.getOrCreate(db, first, () => legacyKey); + await db.query("UPDATE app.connections SET kind=$3 WHERE tenant_id=$1 AND kind=$2", [f.tenantId, "ssh-client-key:"+first, "hetzner-client-key:"+first]); + const migration = await readFile(new URL("../migrations/0121_ssh_client_identity.sql", import.meta.url), "utf8"); + // Scope this migration assertion to the isolated fixture tenant. + await db.query(migration.replace("FROM app.connections WHERE kind LIKE", "FROM app.connections WHERE tenant_id=$1 AND kind LIKE"), [f.tenantId]); + const tools = (await mcp("tools/list", {})).message.result; + expect(tools.tools).toEqual(expect.arrayContaining([expect.objectContaining({name:"get_ssh_public_key"}), expect.objectContaining({name:"ssh_exec"})])); + const getKey = async (identity = auth()) => JSON.stringify(await invoke("get_ssh_public_key", {}, identity) ?? null); + const original = await getKey(); + expect(original).toContain(legacyKey.publicKey); + expect(original).not.toContain("PRIVATE KEY"); + const other = await getKey(auth(second)); + expect(other).toContain("ssh-ed25519"); + expect(other).not.toContain(legacyKey.publicKey); + + await db.query("UPDATE app.oauth_installations SET active_grant_id=$4 WHERE tenant_id=$1 AND user_id=$2 AND id=$3", + [f.tenantId, f.userId, first, "new-grant"]); + const reconnected = auth(first, "new-grant"); + expect(await getKey(reconnected)).toBe(original); + expect(await getKey()).not.toContain(legacyKey.publicKey); + + const project = new HetznerConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY); + await project.save("First test project", "synthetic-project-token"); + await project.save("Replacement test project", "synthetic-replacement-token"); + expect(await getKey(reconnected)).toBe(original); + expect(await project.delete()).toBe(true); + expect(await getKey(reconnected)).toBe(original); + expect(await repo.get(db, first)).toEqual(legacyKey); + + const config = { name:"Test", address:"8.8.4.4", username:"runner", hostFingerprint:"SHA256:"+"A".repeat(43) }; + for (const bad of [{...config,address:"127.0.0.1"},{...config,username:"root"}]) + expect((await ownerRequest("/api/v1/ssh/targets","POST",bad)).status).toBe(400); + const saved = await ownerRequest("/api/v1/ssh/targets","POST",config); + expect(saved.status).toBe(200); + const target = await saved.json() as { id:string }; + expect(target.id).toBeTruthy(); + const list = await ownerRequest("/api/v1/ssh/targets","GET"); + expect(await list.json()).toEqual({targets:[{...config,id:target.id}]}); + + f.env.CLIENT_SSH = { idFromName: (value: string) => value, get: (key: string) => ({ + fetch: async (_url: string, request: RequestInit) => { + const body = JSON.parse(String(request.body)); + expect(JSON.parse(key)).toEqual([f.tenantId, f.userId, first, target.id]); + expect(body.authority.oauthGrantId).toBe("new-grant"); + expect(body.authority.oauthInstallationId).toBe(first); + expect(body.command).toBe("ls"); + expect(JSON.stringify(body)).not.toContain("PRIVATE KEY"); + return Response.json({ stdout:"workspace\n", stderr:"", exitCode:0, signal:null, reusedConnection:true, truncated:false }); + }, + }) } as unknown as DurableObjectNamespace; + expect(JSON.stringify(await invoke("ssh_exec", {targetId:target.id,command:"ls"}, reconnected))).toContain("workspace"); + expect((await ownerRequest("/api/v1/ssh/targets/" + target.id,"DELETE")).status).toBe(200); + } finally { + await f.cleanup(); + } +}); diff --git a/packages/api/test/fixtures/hetzner-ssh-worker.ts b/packages/api/test/fixtures/hetzner-ssh-worker.ts index 0469ccc4..cda58b55 100644 --- a/packages/api/test/fixtures/hetzner-ssh-worker.ts +++ b/packages/api/test/fixtures/hetzner-ssh-worker.ts @@ -2,14 +2,27 @@ import { DurableObject } from "cloudflare:workers"; import { authenticateHetznerSsh, generateHetznerSshKey } from "../../src/integrations/providers/hetzner-ssh-transport"; +import type { SshSession } from "edgeport/ssh"; +import { execBounded, openSshSession } from "../../src/ssh/transport/edgeport-exec"; + type Env = { SSH_FIXTURE: DurableObjectNamespace }; export class FixtureBroker extends DurableObject { private readonly client = generateHetznerSshKey(); + private session?: SshSession; + async fetch(request: Request) { - if (new URL(request.url).pathname === "/public") return Response.json({ publicKey: this.client.publicKey }); - if (new URL(request.url).pathname !== "/probe") return new Response(null, { status: 404 }); - const { port, fingerprint } = await request.json<{ port: number; fingerprint: string }>(); + 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 }); + const { port, fingerprint, command } = await request.json<{ port: number; fingerprint: string; command?: string }>(); try { + if (path === "/exec" && command) { + const reusedConnection = Boolean(this.session); + this.session ??= await openSshSession({ id: "test", name: "fixture", address: "127.0.0.1", + username: "fixture-check", hostFingerprint: fingerprint }, this.client.privateKey, port); + return Response.json({ ...await execBounded(this.session, command), reusedConnection }); + } await authenticateHetznerSsh({ address: "127.0.0.1", username: "fixture-check", hostFingerprint: fingerprint, privateKey: this.client.privateKey }, undefined, port); return Response.json({ authenticated: true }); diff --git a/packages/api/wrangler.jsonc b/packages/api/wrangler.jsonc index 43658f8f..88d0642d 100644 --- a/packages/api/wrangler.jsonc +++ b/packages/api/wrangler.jsonc @@ -26,7 +26,7 @@ "ratelimits": [{ "name": "GOOGLE_SIGN_IN_START_LIMIT", "namespace_id": "10430", "simple": { "limit": 15, "period": 60 } }], "r2_buckets": [{ "binding": "PROXY_ARTIFACTS", "bucket_name": "factorize-run-artifacts" }], "durable_objects": { - "bindings": [{ "name": "SCHEDULER", "class_name": "AlarmCoordinator" }, { "name": "HETZNER_SSH", "class_name": "HetznerSshBroker" }] + "bindings": [{ "name": "SCHEDULER", "class_name": "AlarmCoordinator" }, { "name": "HETZNER_SSH", "class_name": "HetznerSshBroker" }, { "name": "CLIENT_SSH", "class_name": "SshExecBroker" }] }, "migrations": [ { "tag": "v1", "new_sqlite_classes": ["Tenant"] }, @@ -35,7 +35,8 @@ { "tag": "v4-auth-store", "new_sqlite_classes": ["AuthStore"] }, { "tag": "v5-postgres-alarm-coordinator", "new_sqlite_classes": ["AlarmCoordinator"] }, { "tag": "v6-postgres-cutover", "deleted_classes": ["Tenant", "GitHubInstallationRegistry", "TenantV2", "GitHubInstallationRegistryV2", "AuthStore"] }, - { "tag": "v7-hetzner-ssh-broker", "new_sqlite_classes": ["HetznerSshBroker"] } + { "tag": "v7-hetzner-ssh-broker", "new_sqlite_classes": ["HetznerSshBroker"] }, + { "tag": "v8-client-ssh-exec", "new_sqlite_classes": ["SshExecBroker"] } ], "vars": { "APP_ORIGIN": "https://app.factorize.sh", diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index b874b4aa..737b8495 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -33,7 +33,8 @@ only. With a **Read & Write** token, checked clients can make changes, delete resources, and incur charges. The existing client checkboxes are unchanged by this update: a client already checked for a project with a Read & Write token can make writes immediately. Replacing the project still resets client -grants and stored SSH keys; reassign only clients that should have access. +API grants and probe enrollments; reassign only clients that need API access. +Client SSH key pairs stay attached to the client, independent of the project. Use `get_api_reflection` to find the authorized Hetzner connection ID. Then use the standard `request_api` tool with the method, relative `/v1/...` path, @@ -68,3 +69,28 @@ 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. + + +### Run commands over SSH + +The SSH server decides whether a client can log in. Ask the connected client +to call `get_ssh_public_key`; add that public key to the account it should use. +For a new Hetzner server, use the native Hetzner API through `request_api`. +Use a dedicated non-root account and discover its host fingerprint through a +trusted provider console. An owner then saves the public IP, username, and +fingerprint using `POST /api/v1/ssh/targets` from an authenticated owner session, +and supplies the returned target ID to the client. No private key is exposed. + +`ssh_exec` takes that target ID and one command. It returns stdout, stderr +and the exit code, with a truncation flag if output exceeded the response +limit. Commands do not share a shell, working directory, or environment. +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 +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 3e43ccd8..cced6edc 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -363,7 +363,8 @@ only. With a **Read & Write** token, checked clients can make changes, delete resources, and incur charges. The existing client checkboxes are unchanged by this update: a client already checked for a project with a Read & Write token can make writes immediately. Replacing the project still resets client -grants and stored SSH keys; reassign only clients that should have access. +API grants and probe enrollments; reassign only clients that need API access. +Client SSH key pairs stay attached to the client, independent of the project. Use `get_api_reflection` to find the authorized Hetzner connection ID. Then use the standard `request_api` tool with the method, relative `/v1/...` path, @@ -399,6 +400,31 @@ 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. + +### Run commands over SSH + +The SSH server decides whether a client can log in. Ask the connected client +to call `get_ssh_public_key`; add that public key to the account it should use. +For a new Hetzner server, use the native Hetzner API through `request_api`. +Use a dedicated non-root account and discover its host fingerprint through a +trusted provider console. An owner then saves the public IP, username, and +fingerprint using `POST /api/v1/ssh/targets` from an authenticated owner session, +and supplies the returned target ID to the client. No private key is exposed. + +`ssh_exec` takes that target ID and one command. It returns stdout, stderr +and the exit code, with a truncation flag if output exceeded the response +limit. Commands do not share a shell, working directory, or environment. +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 +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. + ## Connection problems Source: https://docs.factorize.sh/troubleshooting/connection @@ -471,6 +497,7 @@ its input and enforces the operation's required scope. | `get_event` | Read an Event and its current payload schema revision. | | `get_event_processing_acknowledgments` | Read optional processing acknowledgment settings for your exact active MCP subscription. Off by default; independent of HTTP receipt and client-side throttling. | | `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. | +| `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. | | `get_trigger` | Get a Trigger, its parent Event, and input configuration | | `get_webhook_delivery` | Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned. | | `grant_vm_permissions` | Grant or replace Factorize permissions for an existing VM. Use explicit scopes within your effective access. Requires vms:edit. | @@ -497,6 +524,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. | | `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 7cf76087..23b58d3f 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -35,6 +35,7 @@ its input and enforces the operation's required scope. | `get_event` | Read an Event and its current payload schema revision. | | `get_event_processing_acknowledgments` | Read optional processing acknowledgment settings for your exact active MCP subscription. Off by default; independent of HTTP receipt and client-side throttling. | | `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. | +| `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. | | `get_trigger` | Get a Trigger, its parent Event, and input configuration | | `get_webhook_delivery` | Get a webhook delivery and its safe processing timeline. Secrets and payloads are never returned. | | `grant_vm_permissions` | Grant or replace Factorize permissions for an existing VM. Use explicit scopes within your effective access. Requires vms:edit. | @@ -61,6 +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. | | `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 326bd280..7f84e29f 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -5472,6 +5472,216 @@ paths: schema: type: string pattern: ^[1-9][0-9]*$ + /api/v1/ssh/targets: + get: + summary: List saved SSH target identities + responses: + "200": + description: Targets + content: + application/json: + schema: + type: object + properties: + targets: + type: array + items: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 96 + address: + type: string + maxLength: 45 + username: + type: string + pattern: ^[a-z_][a-z0-9_-]{0,31}$ + hostFingerprint: + type: string + pattern: ^SHA256:[A-Za-z0-9+/]{43}$ + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + required: + - name + - address + - username + - hostFingerprint + - id + 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_targets + tags: + - ssh + security: + - cookieAuth: [] + x-required-scope: integrations:read + x-owner-session-required: true + post: + summary: Save an independently verified SSH target identity + responses: + "200": + description: Target + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 96 + address: + type: string + maxLength: 45 + username: + type: string + pattern: ^[a-z_][a-z0-9_-]{0,31}$ + hostFingerprint: + type: string + pattern: ^SHA256:[A-Za-z0-9+/]{43}$ + id: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ + required: + - name + - address + - username + - hostFingerprint + - id + 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: post_api_v1_ssh_targets + tags: + - ssh + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 96 + address: + type: string + maxLength: 45 + username: + type: string + pattern: ^[a-z_][a-z0-9_-]{0,31}$ + hostFingerprint: + type: string + pattern: ^SHA256:[A-Za-z0-9+/]{43}$ + required: + - name + - address + - username + - hostFingerprint + additionalProperties: false + /api/v1/ssh/targets/{targetId}: + delete: + summary: Remove a saved SSH target + 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_targets_targetId + tags: + - ssh + security: + - cookieAuth: [] + x-required-scope: integrations:write + x-owner-session-required: true + parameters: + - name: targetId + in: path + required: true + schema: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$ /api/v1/integrations/aws: get: summary: List AWS connections diff --git a/scripts/hetzner-ssh-runtime.test.mjs b/scripts/hetzner-ssh-runtime.test.mjs index 5d3b247f..e23e04be 100644 --- a/scripts/hetzner-ssh-runtime.test.mjs +++ b/scripts/hetzner-ssh-runtime.test.mjs @@ -29,7 +29,7 @@ function ready(child) { }); } -test("workerd uses fresh SSH authentication and closes without a command channel", { timeout: 55_000 }, async () => { +test("workerd keeps legacy probes command-free and reuses generic SSH command channels", { timeout: 55_000 }, async () => { const fixture = await mkdtemp(join(tmpdir(), "factorize-ssh-test-")); const peers = new Set(); let worker, server; @@ -62,7 +62,7 @@ test("workerd uses fresh SSH authentication and closes without a command channel const hostKey = ssh2.utils.parseKey(host.public); assert.ok(!(clientKey instanceof Error) && !(hostKey instanceof Error)); const fingerprint = "SHA256:" + createHash("sha256").update(hostKey.getPublicSSH()).digest("base64").replace(/=+$/, ""); - let sessions = 0, channels = 0, signed = 0, allowedKey = true; + let sessions = 0, channels = 0, signed = 0, allowedKey = true, allowExec = false; server = new ssh2.Server({ hostKeys: [host.private], algorithms: { cipher: ["aes128-gcm@openssh.com"] } }, connection => { peers.add(connection); sessions++; connection.on("error", () => {}); @@ -75,7 +75,21 @@ test("workerd uses fresh SSH authentication and closes without a command channel } ctx.accept(); }); - connection.on("ready", () => connection.on("session", (_accept, reject) => { channels++; reject(); })); + connection.on("ready", () => connection.on("session", (accept, reject) => { + channels++; + if (!allowExec) return reject(); + accept().on("exec", (acceptExec, _rejectExec, { command }) => { + const channel = acceptExec(); + channel.on("error", () => {}); + if (command === "large") channel.write(Buffer.alloc(70_000, 0x78)); + else { + channel.write(command); + channel.stderr.write("fixture stderr"); + } + channel.exit(command === "one" ? 7 : 0); + channel.end(); + }); + })); }); server.listen(0, "127.0.0.1"); await once(server, "listening"); @@ -93,6 +107,29 @@ test("workerd uses fresh SSH authentication and closes without a command channel assert.equal(signed, 2); assert.equal((await probe("SHA256:" + "A".repeat(43))).status, 502); assert.equal(channels, 0); + + allowedKey = true; + allowExec = true; + const command = (command, expectedFingerprint = fingerprint) => fetch(url + "/exec", { + method: "POST", body: JSON.stringify({ port: server.address().port, fingerprint: expectedFingerprint, command }), + }); + assert.equal((await command("denied", "SHA256:"+"A".repeat(43))).status, 502); + const beforeExec = signed; + const firstExec = await command("one"); + assert.equal(firstExec.status, 200, await firstExec.clone().text()); + assert.deepEqual(await firstExec.json(), { stdout:"one", stderr:"fixture stderr", exitCode:7, signal:null, truncated:false, reusedConnection:false }); + const secondExec = await (await command("two")).json(); + assert.equal(secondExec.stdout, "two"); + assert.equal(secondExec.reusedConnection, true); + assert.equal(signed, beforeExec + 1, "two command channels reuse one SSH authentication"); + const large = await (await command("large")).json(); + assert.equal(large.stdout.length, 32768); + assert.equal(large.truncated, true); + assert.equal(channels, 3); + assert.equal((await fetch(url + "/close")).status, 204); + allowedKey = false; + assert.equal((await command("denied")).status, 502); + assert.equal(channels, 3); } finally { if (worker && worker.exitCode === null) { const exited = once(worker, "exit"); worker.kill(); await exited.catch(() => {}); } for (const peer of peers) peer.end(); diff --git a/scripts/hosting-invariants.test.mjs b/scripts/hosting-invariants.test.mjs index bd108f72..c64b95c3 100644 --- a/scripts/hosting-invariants.test.mjs +++ b/scripts/hosting-invariants.test.mjs @@ -11,8 +11,8 @@ test("static cutover preserves the existing production Worker and state identiti const { durable_objects: oldObjects, migrations: oldMigrations, ...oldWorker } = oldBackend; assert.deepEqual(nextWorker, oldWorker); assert.deepEqual(build, { command: "node scripts/prepare-worker-ssh.mjs" }); - assert.deepEqual(nextObjects.bindings, [...oldObjects.bindings, { name: "HETZNER_SSH", class_name: "HetznerSshBroker" }]); - assert.deepEqual(nextMigrations, [...oldMigrations, { tag: "v7-hetzner-ssh-broker", new_sqlite_classes: ["HetznerSshBroker"] }]); + assert.deepEqual(nextObjects.bindings, [...oldObjects.bindings, { name: "HETZNER_SSH", class_name: "HetznerSshBroker" }, { name: "CLIENT_SSH", class_name: "SshExecBroker" }]); + assert.deepEqual(nextMigrations, [...oldMigrations, { tag: "v7-hetzner-ssh-broker", new_sqlite_classes: ["HetznerSshBroker"] }, { tag: "v8-client-ssh-exec", new_sqlite_classes: ["SshExecBroker"] }]); assert.deepEqual(buckets, [{ binding: "PROXY_ARTIFACTS", bucket_name: oldBuckets[0].bucket_name }]); assert.equal(oldAssets.binding, assets.binding); assert.deepEqual(assets, { directory: "../app/dist", binding: "ASSETS", run_worker_first: true, not_found_handling: "none" });