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
8 changes: 4 additions & 4 deletions packages/api-client/src/schema.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export class AccessControlService {
const globallyAvailable = [...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)];
const liveScopes = new Set(integrations.filter(row => row.kind === "hetzner" && row.available && row.policy !== "disabled").map(row => row.requiredScope));
const scopeLabels = Object.fromEntries(integrations.map(row => [row.requiredScope,
row.kind === "hetzner" ? "Hetzner Cloud (inventory, enrolled SSH, and provisioning if enabled)" : `${row.name} integration access`]));
row.kind === "hetzner" ? "Hetzner Cloud (native API and enrolled SSH)" : `${row.name} integration access`]));
return publicValue(z.array(authorizedClient), rows.map(row => {
const appName = byId.get(row.client_id)?.clientName ?? row.client_id;
const inactive = (row.active_expires_at !== null && row.active_expires_at.getTime() <= Date.now()) || row.active_session_version !== this.auth.sessionVersion;
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HetznerProvisionService } from "./integrations/application/hetzner-provision";
import { HetznerClientKeyService } from "./integrations/application/hetzner-client-key";
import { AwsIntegrationService } from "./integrations/application/aws-service";
import { HetznerSshService } from "./integrations/application/hetzner-ssh";
import { ProxyService } from "./proxy/application/proxy-service";
Expand Down Expand Up @@ -47,7 +47,7 @@ export class ApiService {
get integrations() {
return new IntegrationsService(this.env, this.auth, scope => this.authorize(scope), scope => this.authorizeOwnerSession(scope));
}
get hetznerProvision() { return new HetznerProvisionService(this.env, this.auth); }
get hetznerKeys() { return new HetznerClientKeyService(this.env, this.auth); }
get hetznerSsh() {
return new HetznerSshService(this.env, this.auth, scope => this.authorizeOwnerSession(scope));
}
Expand Down
23 changes: 22 additions & 1 deletion packages/api/src/credentials/application/agent-credentials.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { HetznerConnectionRepository } from "../storage/hetzner-connection-repository";
import { AgentApiError } from "../../proxy/api/agent-api-error";
import { appConfig, signingConfig } from "../../config/runtime";
import { cloudflareCredential } from "../../integrations/providers/cloudflare-oauth";
import type { Env } from "../../types";
Expand All @@ -11,9 +13,28 @@ import { FlyConnectionRepository } from "../storage/fly-connection-repository";
import { isPublicHttpsOrigin } from "../../proxy/transport/public-address";

/** Only call after shared identity/grant authorization. No caller origin or secret. */
export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string): Promise<OutboundCredential | null> {
export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string, method: string): Promise<OutboundCredential | null> {
if (kind === "cloudflare") return cloudflareCredential(env, tenantId, credentialId, relativePath);
const database = databaseFor(env);
if (kind === "hetzner") {
if (credentialId !== "hetzner") return null;
const origin = "https://api.hetzner.cloud";
const rawPath = relativePath.split("?", 1)[0]!;
if (!rawPath.startsWith("/") || rawPath.startsWith("//") || /%2f|%5c|%25/i.test(rawPath) || /[\\\s\0#]/.test(relativePath)) {
throw new AgentApiError(400, "invalid_request", "Use a relative Hetzner Cloud /v1/ API path.");
}
const target = new URL(relativePath, origin);
if (target.origin !== origin || !target.pathname.startsWith("/v1/")) {
throw new AgentApiError(400, "invalid_request", "Use a relative Hetzner Cloud /v1/ API path.");
}
const project = await new HetznerConnectionRepository(database, tenantId, signingConfig(env).credentialKey).get();
if (!project) return null;
if (method !== "GET" && method !== "HEAD" && project.nativeWritesEnabled !== true) {
throw new AgentApiError(403, "hetzner_native_writes_disabled", "The owner has not enabled native Hetzner Cloud API writes.");
}
return { origin, path: target.pathname + target.search, credential: project.token,
requestHeaders: ["accept", "content-type", "if-match", "if-none-match"] };
}
if (kind === "fly") {
if (credentialId !== "fly") return null;
const token = await new FlyConnectionRepository(database, tenantId, signingConfig(env).credentialKey).token();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { decrypt, encrypt } from "../../crypto";
import { lockIntegrationTopology } from "../../integrations/storage/integration-removal-topology";
import type { Database, DatabaseClient } from "../../postgres/database";

export type HetznerProject = { name: string; token: string; revision: string; provisioningEnabled?: boolean };
export type HetznerProject = { name: string; token: string; revision: string; nativeWritesEnabled?: boolean };

export class HetznerConnectionRepository {
constructor(private database: Database, private tenantId: string, private encryptionKey: string) {
Expand All @@ -16,8 +16,8 @@ export class HetznerConnectionRepository {
return rows[0] ? JSON.parse(await decrypt(rows[0].encrypted_value, this.encryptionKey)) as HetznerProject : null;
}

async save(name: string, token: string, provisioningEnabled = false) {
const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID(), provisioningEnabled }), this.encryptionKey);
async save(name: string, token: string, nativeWritesEnabled = false) {
const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID(), nativeWritesEnabled }), this.encryptionKey);
await this.database.transaction(async client => {
await lockIntegrationTopology(client, this.tenantId);
const hadProject = Boolean(await this.get(client));
Expand Down
12 changes: 2 additions & 10 deletions packages/api/src/integrations/api/hetzner-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,14 @@ import { z } from "zod";

export const hetznerConnectionInput = z.strictObject({
name: z.string().trim().min(1).max(120),
provisioningEnabled: z.boolean().optional(),
nativeWritesEnabled: z.boolean().optional(),
token: z.string().trim().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/).meta({ writeOnly: true }),
});
export const hetznerConnectionMetadata = z.object({ name: z.string(), provisioningEnabled: z.boolean().optional() });
export const hetznerConnectionMetadata = z.object({ name: z.string(), nativeWritesEnabled: z.boolean().optional() });
export const hetznerServer = z.object({
id: z.number().int().positive(),
name: z.string().min(1).max(255),
status: z.string().min(1).max(64),
location: z.string().min(1).max(64).nullable(),
});
export const hetznerInventory = z.object({ servers: z.array(hetznerServer).max(100), truncated: z.boolean() });

export const hetznerCreateInput = z.strictObject({
requestId: z.uuid(),
name: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,46}[a-z0-9])?$/),
serverType: z.enum(["cx23", "cpx22", "cax11"]),
location: z.enum(["fsn1", "nbg1", "hel1", "ash", "hil", "sin"]),
});
export type HetznerCreateInput = z.infer<typeof hetznerCreateInput>;
5 changes: 1 addition & 4 deletions packages/api/src/integrations/api/mcp.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { hetznerCreateInput, type HetznerCreateInput } from "./hetzner-contracts";
import { awsCodeInput } from "./aws-contracts";
import { hetznerSshToolInput } from "./hetzner-ssh-contracts";
import { z } from "zod";
Expand All @@ -19,9 +18,7 @@ export const tailTools = [


export const hetznerTools = [
mcpTool(null, "list_hetzner_servers", "List server inventory for a connected Hetzner project whose access is granted to this client.", z.strictObject({}), service => () => service.hetznerSsh.inventoryAsClient()),
mcpTool(null, "get_hetzner_ssh_public_key", "Get this authorized OAuth installation’s public SSH key. The owner must install it on existing servers; the private key is never returned.", z.strictObject({}), service => () => service.hetznerProvision.publicKey()),
mcpTool<HetznerCreateInput>(null, "create_hetzner_server", "Create one small Hetzner Cloud server only when the owner enabled provisioning. This can incur charges. Provide an intentionally chosen name and a stable requestId. Retrying the same request only checks its outcome. Requires an owner-verified host fingerprint before SSH.", hetznerCreateInput, service => input => service.hetznerProvision.create(input)),
mcpTool(null, "get_hetzner_ssh_public_key", "Get this authorized OAuth installation’s public SSH key. The owner must install it on existing servers; the private key is never returned.", z.strictObject({}), service => () => service.hetznerKeys.publicKey()),
mcpTool(null, "check_hetzner_ssh", "Check SSH access for one owner-enrolled Hetzner Cloud server. Uses the pinned host identity and a Factorize-held credential. Proves fresh key authentication; no SSH channel, commands or remote output.", hetznerSshToolInput, service =>
(input: {serverId: number}) => service.hetznerSsh.checkAsClient(input.serverId)),
];
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/integrations/api/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export const integrationRoutes = [
}, service => service.integrations.getHetznerConnection(), { ownerSession: true }),
route("PUT", "/api/v1/hetzner/connection", "integrations:write", {
summary: "Save a Hetzner Cloud project connection",
description: "Owner browser session only. Supply a project API token with Read permission, or Read & Write only when enabling server provisioning. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources.",
description: "Owner browser session only. Supply a project API token with Read permission, or Read & Write only when explicitly enabling native API writes through the proxy. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources.",
responses: { "200": { description: "Saved connection metadata", content: { "application/json": { schema: jsonSchema(z.object({ connection: hetznerConnectionMetadata }), "output") } } } },
}, (service, { body }) => service.integrations.saveHetznerConnection(body), { body: hetznerConnectionInput, ownerSession: true, maxBodyBytes: 4096 }),
route("DELETE", "/api/v1/hetzner/connection", "integrations:write", {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/integrations/application/diagnostics.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { HetznerFailure } from "../providers/hetzner-cloud";

type Diagnostic =
| { provider: "hetzner"; operation: "validate_token" | "list_servers" | "lookup_server" | "provision_server";
| { provider: "hetzner"; operation: "validate_token" | "list_servers" | "lookup_server";
reason: HetznerFailure;
upstreamStatus?: number }
| { provider: "aws"; operation: "list_connections" | "prepare_connection" | "download_template" | "verify_role";
Expand Down
43 changes: 43 additions & 0 deletions packages/api/src/integrations/application/hetzner-client-key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { signingConfig } from "../../config/runtime";
import { HetznerClientKeyRepository } from "../../credentials/storage/hetzner-client-key-repository";
import { HetznerConnectionRepository } from "../../credentials/storage/hetzner-connection-repository";
import { databaseFor, type DatabaseClient } from "../../postgres/database";
import { ServiceError } from "../../service-contract";
import type { Env, OAuthProps } from "../../types";
import { generateHetznerSshKey } from "../providers/hetzner-ssh-transport";
import { lockIntegrationTopology } from "../storage/integration-removal-topology";
import { activeHetznerScope } from "./hetzner-access";

export class HetznerClientKeyService {
constructor(private env: Env, private auth: OAuthProps) {}
private get database() { return databaseFor(this.env); }
private get projects() { return new HetznerConnectionRepository(this.database, this.auth.tenantId, signingConfig(this.env).credentialKey); }
private get keys() { return new HetznerClientKeyRepository(this.auth.tenantId, signingConfig(this.env).credentialKey); }

private async authority(sql: DatabaseClient) {
const { authMethod, oauthInstallationId, oauthGrantId, oauthExpiresAt, tenantId, userId, sessionVersion } = this.auth;
const forbidden = new ServiceError(403, "hetzner_not_authorized", "This client does not have Hetzner access.");
if (authMethod !== "oauth" || !oauthInstallationId || !oauthGrantId || !Number.isFinite(oauthExpiresAt)) throw forbidden;
const current = await activeHetznerScope(sql, { tenantId, userId, sessionVersion, installationId: oauthInstallationId, grantId: oauthGrantId, expiresAt: oauthExpiresAt! });
if (!current) throw forbidden;
const { rowCount } = await sql.query(
`SELECT 1 FROM app.members m JOIN app.auth_users u ON u.id=m.user_id
WHERE m.tenant_id=$1 AND m.user_id=$2 AND m.role='owner' AND m.session_version=$3 AND u.email_verified`,
[tenantId, userId, sessionVersion],
);
if (!rowCount) throw forbidden;
return oauthInstallationId;
}

async publicKey() {
return this.database.transaction(async sql => {
await lockIntegrationTopology(sql, this.auth.tenantId);
const installationId = await this.authority(sql);
if (!await this.projects.get(sql)) throw new ServiceError(404, "hetzner_not_connected", "Connect a Hetzner Cloud project first.");
const { publicKey } = await this.keys.getOrCreate(sql, installationId, generateHetznerSshKey);
return { publicKey, authorizedKeysEntry: `restrict,command="/bin/true" ${publicKey}`,
notice: "An owner must install the complete restricted key line on an existing server. Do not install it as root." };
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ export class HetznerInventoryService {

async connection() {
const project = await this.connections.get();
return { connection: project ? { name: project.name, ...(project.provisioningEnabled ? { provisioningEnabled: true } : {}) } : null };
return { connection: project ? { name: project.name, ...(project.nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } : null };
}

async connectionRevision() { return (await this.connections.get())?.revision ?? null; }

async save(input: unknown) {
const { name, token, provisioningEnabled = false } = hetznerConnectionInput.parse(input);
const { name, token, nativeWritesEnabled = false } = hetznerConnectionInput.parse(input);
await this.withProviderError("validate_token", () => createHetznerCloudClient().validate(token));
await this.connections.save(name, token, provisioningEnabled);
return { connection: { name, ...(provisioningEnabled ? { provisioningEnabled: true } : {}) } };
await this.connections.save(name, token, nativeWritesEnabled);
return { connection: { name, ...(nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } };
}

async delete() { return { deleted: await this.connections.delete() }; }
Expand Down
Loading
Loading