Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions packages/api/src/ssh/api/contracts.ts
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -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<typeof sshExecInput>) => value.targetId ?? "hetzner:" + value.hetznerServerId;
export const sshExecResult = z.strictObject({
stdout: z.string(), stderr: z.string(), exitCode: z.number().int().nullable(),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/ssh/api/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<z.infer<typeof sshExecInput>>(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<z.infer<typeof sshExecInput>>(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)),
];
49 changes: 39 additions & 10 deletions packages/api/src/ssh/application/hetzner-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
},
};
}
12 changes: 10 additions & 2 deletions packages/api/src/ssh/transport/edgeport-exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SshTarget, "hostFingerprint"> & { 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;
Expand Down
29 changes: 22 additions & 7 deletions packages/api/src/ssh/transport/exec-broker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -39,19 +39,20 @@ export class SshExecBroker extends DurableObject<Env> {
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<typeof openSshSession>[0] | null;
let persist: Awaited<ReturnType<typeof resolveHetznerSshTarget>>["persist"] | undefined;
let current: () => Promise<boolean>;
let markMismatch: (() => Promise<void>) | 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;
Expand All @@ -67,11 +68,16 @@ export class SshExecBroker extends DurableObject<Env> {
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<typeof target>) => 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 };
Expand All @@ -83,6 +89,15 @@ export class SshExecBroker extends DurableObject<Env> {
}
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 }); }
Expand Down
9 changes: 8 additions & 1 deletion packages/api/test/fixtures/hetzner-ssh-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,16 @@ export class FixtureBroker extends DurableObject<Env> {
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",
Expand Down
33 changes: 23 additions & 10 deletions packages/api/test/hetzner-ssh-discovery.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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<ReturnType<typeof openSshSession>>;
});

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");
Expand Down
Loading
Loading