diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 0f9e736a..f374d575 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1730,7 +1730,7 @@ export interface paths { get: operations["get_api_v1_hetzner_connection"]; /** * Save a Hetzner Cloud project connection - * @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. + * @description Owner browser session only. Choose Read to limit checked clients to reads or Read & Write to allow native changes, deletions, and billable resources. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources. * * Requires the integrations:write scope. * @@ -6940,7 +6940,6 @@ export interface operations { "application/json": { connection: { name: string; - nativeWritesEnabled?: boolean; } | null; }; }; @@ -6966,7 +6965,6 @@ export interface operations { content: { "application/json": { name: string; - nativeWritesEnabled?: boolean; token: string; }; }; @@ -6981,7 +6979,6 @@ export interface operations { "application/json": { connection: { name: string; - nativeWritesEnabled?: boolean; }; }; }; diff --git a/packages/api/src/access-control/application/access-control-service.ts b/packages/api/src/access-control/application/access-control-service.ts index e24772d2..50beda97 100644 --- a/packages/api/src/access-control/application/access-control-service.ts +++ b/packages/api/src/access-control/application/access-control-service.ts @@ -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 (native API and enrolled SSH)" : `${row.name} integration access`])); + row.kind === "hetzner" ? "Hetzner Cloud (native API and enrolled SSH; a Read & Write token allows changes, deletions, and charges)" : `${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; diff --git a/packages/api/src/credentials/application/agent-credentials.ts b/packages/api/src/credentials/application/agent-credentials.ts index 10c86298..d5f30484 100644 --- a/packages/api/src/credentials/application/agent-credentials.ts +++ b/packages/api/src/credentials/application/agent-credentials.ts @@ -13,7 +13,7 @@ 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, method: string): Promise { +export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string): Promise { if (kind === "cloudflare") return cloudflareCredential(env, tenantId, credentialId, relativePath); const database = databaseFor(env); if (kind === "hetzner") { @@ -29,9 +29,6 @@ export async function resolveAgentCredential(env: Env, tenantId: string, kind: s } 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"] }; } diff --git a/packages/api/src/credentials/storage/hetzner-connection-repository.ts b/packages/api/src/credentials/storage/hetzner-connection-repository.ts index fac9ff87..8f567233 100644 --- a/packages/api/src/credentials/storage/hetzner-connection-repository.ts +++ b/packages/api/src/credentials/storage/hetzner-connection-repository.ts @@ -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; nativeWritesEnabled?: boolean }; +export type HetznerProject = { name: string; token: string; revision: string }; export class HetznerConnectionRepository { constructor(private database: Database, private tenantId: string, private encryptionKey: string) { @@ -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, nativeWritesEnabled = false) { - const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID(), nativeWritesEnabled }), this.encryptionKey); + async save(name: string, token: string) { + const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID() }), this.encryptionKey); await this.database.transaction(async client => { await lockIntegrationTopology(client, this.tenantId); const hadProject = Boolean(await this.get(client)); @@ -26,7 +26,7 @@ export class HetznerConnectionRepository { `INSERT INTO app.connections (tenant_id,kind,encrypted_value) VALUES ($1,'hetzner',$2) ON CONFLICT (tenant_id,kind) DO UPDATE SET encrypted_value=excluded.encrypted_value,updated_at=now()`, [this.tenantId, value]); - // Existing grants never cross a project/token replacement or gain new provisioning power. + // Existing grants never cross a project/token replacement. if (hadProject) await client.query( "UPDATE app.agent_integrations SET epoch=epoch+1,revision=revision+1 WHERE tenant_id=$1 AND kind='hetzner' AND credential_id='hetzner'", [this.tenantId]); diff --git a/packages/api/src/integrations/api/hetzner-contracts.ts b/packages/api/src/integrations/api/hetzner-contracts.ts index 2580b463..ec5f03a3 100644 --- a/packages/api/src/integrations/api/hetzner-contracts.ts +++ b/packages/api/src/integrations/api/hetzner-contracts.ts @@ -2,10 +2,9 @@ import { z } from "zod"; export const hetznerConnectionInput = z.strictObject({ name: z.string().trim().min(1).max(120), - 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(), nativeWritesEnabled: z.boolean().optional() }); +export const hetznerConnectionMetadata = z.object({ name: z.string() }); export const hetznerServer = z.object({ id: z.number().int().positive(), name: z.string().min(1).max(255), diff --git a/packages/api/src/integrations/api/rest.ts b/packages/api/src/integrations/api/rest.ts index cb5e7122..2aa792c5 100644 --- a/packages/api/src/integrations/api/rest.ts +++ b/packages/api/src/integrations/api/rest.ts @@ -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 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.", + description: "Owner browser session only. Choose Read to limit checked clients to reads or Read & Write to allow native changes, deletions, and billable resources. 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", { diff --git a/packages/api/src/integrations/application/hetzner-inventory.ts b/packages/api/src/integrations/application/hetzner-inventory.ts index 47c34d06..05840706 100644 --- a/packages/api/src/integrations/application/hetzner-inventory.ts +++ b/packages/api/src/integrations/application/hetzner-inventory.ts @@ -9,16 +9,16 @@ export class HetznerInventoryService { async connection() { const project = await this.connections.get(); - return { connection: project ? { name: project.name, ...(project.nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } : null }; + return { connection: project ? { name: project.name } : null }; } async connectionRevision() { return (await this.connections.get())?.revision ?? null; } async save(input: unknown) { - const { name, token, nativeWritesEnabled = false } = hetznerConnectionInput.parse(input); + const { name, token } = hetznerConnectionInput.parse(input); await this.withProviderError("validate_token", () => createHetznerCloudClient().validate(token)); - await this.connections.save(name, token, nativeWritesEnabled); - return { connection: { name, ...(nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } }; + await this.connections.save(name, token); + return { connection: { name } }; } async delete() { return { deleted: await this.connections.delete() }; } diff --git a/packages/api/src/proxy/application/agent-api.ts b/packages/api/src/proxy/application/agent-api.ts index 4b6a9930..0d61047e 100644 --- a/packages/api/src/proxy/application/agent-api.ts +++ b/packages/api/src/proxy/application/agent-api.ts @@ -27,7 +27,7 @@ import type { z } from "zod"; const STORAGE_BLOCK_BYTES = proxyLimits.artifactBlockBytes; const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized."); const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active."); -const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.kind === "hetzner" ? "Native Hetzner Cloud project API, with owner-controlled write access." : row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) }); +const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.kind === "hetzner" ? "Native Hetzner Cloud project API, bounded by the project token’s permissions." : row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) }); /** These are structural checks only: reflection never refreshes/decrypts secrets. */ export async function integrationConsentLabels(env: Env, tenantId: string, scopes: string[]) { @@ -110,7 +110,7 @@ export class AgentApiService { const path = row.kind === "linear" ? "/graphql" : row.kind === "x" ? "/2/users/me" : row.kind === "cloudflare" ? "/zones" : row.kind === "fly" ? "/v1/apps" : row.kind === "hetzner" ? "/v1/servers" : row.kind === "exe" ? "/exec" : "/"; const method = row.kind === "linear" || row.kind === "exe" ? "POST" : "GET"; const requestExample = {integration:row.id,method,path,...(row.kind === "linear" ? {headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"query { viewer { id name } }"})} : row.kind === "exe" ? {headers:{"Content-Type":"text/plain"},body:"help"} : {})}; - result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use paths relative to the Cloudflare v4 REST API. Cloudflare enforces the accounts and permissions authorized on its consent screen." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "hetzner" ? "Use native Hetzner Cloud /v1 paths, methods, query and body. Reads require the owner’s Hetzner grant. Mutating methods also require explicit native writes enablement and a Read & Write project token." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")}); + result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use paths relative to the Cloudflare v4 REST API. Cloudflare enforces the accounts and permissions authorized on its consent screen." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "hetzner" ? "Use native Hetzner Cloud /v1 paths, methods, query and body. The owner’s Hetzner checkbox grants access to the project API. Hetzner enforces the token’s permissions; a Read & Write token permits changes, deletions, and billable resources." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")}); } return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(identity.scopes).filter(scope => !identity.policy.disabled_scopes.includes(scope)), proxy: { requestUrl: appConfig(this.env).origin + "/api/v1/agent/requests", @@ -126,8 +126,8 @@ export class AgentApiService { forward(integration: string, path: string, request: Request, expectedOperationEpoch?: number) { return this.egress().forward(integration, path, request, expectedOperationEpoch); } - assertRequest(integration: AgentIntegration, path: string, method: string) { - return this.egress().assertRequest(integration, path, method); + assertRequest(integration: AgentIntegration, path: string) { + return this.egress().assertRequest(integration, path); } forwardX(connectionId: string, path: string, request: Request) { return this.egress().forwardX(connectionId, path, request); diff --git a/packages/api/src/proxy/application/proxy-operations.ts b/packages/api/src/proxy/application/proxy-operations.ts index eb0eb9e4..a8b1e4a4 100644 --- a/packages/api/src/proxy/application/proxy-operations.ts +++ b/packages/api/src/proxy/application/proxy-operations.ts @@ -30,7 +30,7 @@ export class ProxyOperations { const parsed=requestApiInput.parse(input),api=this.api(); if(this.auth.authMethod==="oauth"&&!this.auth.scopes.includes("proxy:use"))throw new AgentApiError(403,"insufficient_scope","Renew consent with proxy:use before requesting integrations.","proxy:use"); const {identity,integration}=await api.authorize(parsed.integration); - await api.assertRequest(integration, parsed.path, parsed.method); + await api.assertRequest(integration, parsed.path); if(!this.env.PROXY_ARTIFACTS || !this.env.SCHEDULER)throw new AgentApiError(503,"proxy_unavailable","Durable proxy storage/scheduling is unavailable."); const size=parsed.body===undefined?0:Buffer.byteLength(parsed.body,parsed.encoding==="base64"?"base64":"utf8"); if(size>proxyLimits.requestBytes)throw new AgentApiError(413,"request_too_large","Request exceeds the fixed 32 MiB limit."); diff --git a/packages/api/src/proxy/transport/credential-backed-egress.ts b/packages/api/src/proxy/transport/credential-backed-egress.ts index d670ae16..b9fb4c8b 100644 --- a/packages/api/src/proxy/transport/credential-backed-egress.ts +++ b/packages/api/src/proxy/transport/credential-backed-egress.ts @@ -40,9 +40,9 @@ export class CredentialBackedEgress { ) {} /** Deny a locally prohibited Hetzner request before it creates an async receipt. */ - async assertRequest(integration: AgentIntegration, path: string, method: string) { + async assertRequest(integration: AgentIntegration, path: string) { if (integration.kind === "hetzner" && !await resolveAgentCredential(this.env, this.tenantId, - integration.kind, integration.credential_id, path, method)) throw forbidden(); + integration.kind, integration.credential_id, path)) throw forbidden(); } async forward(integration: string, path: string, request: Request, expectedOperationEpoch?: number) { @@ -50,7 +50,7 @@ export class CredentialBackedEgress { if (expectedOperationEpoch !== undefined && grant.integration.operation_epoch !== expectedOperationEpoch) throw forbidden(); if (grant.integration.kind === "x") return this.forwardX(grant.integration.credential_id, path, request, expectedOperationEpoch); let credential; - try { credential = await resolveAgentCredential(this.env, this.tenantId, grant.integration.kind, grant.integration.credential_id, path, request.method); } + try { credential = await resolveAgentCredential(this.env, this.tenantId, grant.integration.kind, grant.integration.credential_id, path); } catch (error) { if (error instanceof AgentApiError) throw error; throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved."); diff --git a/packages/api/test/hetzner-proxy.postgres.test.ts b/packages/api/test/hetzner-proxy.postgres.test.ts index 7507646b..27cc6bff 100644 --- a/packages/api/test/hetzner-proxy.postgres.test.ts +++ b/packages/api/test/hetzner-proxy.postgres.test.ts @@ -43,7 +43,7 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy } as unknown as R2Bucket; f.env.SCHEDULER = { idFromName:(v:string)=>v, get:()=>({ fetch:async()=>Response.json({scheduled:true}) }) } as unknown as DurableObjectNamespace; const readToken = "syntheticLegacyProjectToken", writeToken = "syntheticNativeWriteToken"; - const validations = { reads: 0, writes: 0 }; + const validations = { reads: 0, writes: 0, rejectedWrites: 0 }; const nativeBody = '{ "name": "demo", "image": "ubuntu-24.04", "server_type": "cx23", "ssh_keys": [123], "user_data": "#cloud-config\\n" }'; let redirect = false, huge = false; const nativeReply = {server:{id:88, name:"demo"}, action:{id:35,status:"running"}, custom:"unmodified-native-response"}; @@ -56,10 +56,14 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy expect(request.headers.get("Cookie")).toBeNull(); if (redirect) return new Response(null, { status:302, headers:{Location:"https://elsewhere.example/"} }); if (request.method === "POST") { - expect(token).toBe("Bearer " + writeToken); expect(new URL(request.url).pathname).toBe("/v1/servers"); expect(await request.text()).toBe(nativeBody); expect(request.headers.get("Content-Type")).toBe("application/json"); + if (token === "Bearer " + readToken) { + validations.rejectedWrites++; + return Response.json({error:{code:"forbidden",message:"Read-only project token"}}, {status:403}); + } + expect(token).toBe("Bearer " + writeToken); validations.writes++; return Response.json(nativeReply, {status:201,headers:{"x-provider-request":"native-123","x-authorization-token":"filtered"}}); } @@ -71,9 +75,9 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy }); vi.stubGlobal("fetch", provider); try { - // A project approved for the former bounded tool is still not approved for native writes. + // Ignore a historical local write flag: the provider enforces the actual token permissions. await new ConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY) - .put("hetzner", { name:"Legacy", token:readToken, revision:crypto.randomUUID(), provisioningEnabled:true }); + .put("hetzner", { name:"Legacy", token:readToken, revision:crypto.randomUUID(), nativeWritesEnabled:true }); const { id: integration } = await registry(); for (const id of [first, second]) await f.db.pool.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) @@ -83,6 +87,9 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy headers:{Authorization:"Bearer caller-override",Cookie:"caller-cookie","X-HTTP-Method-Override":"POST"} }; const post = { integration, method:"POST", path:"/v1/servers", headers:{"Content-Type":"application/json"}, body:nativeBody }; expect((await invoke("request_api",get)).isError).toBe(true); + expect((await invoke("request_api",post)).isError).toBe(true); + expect((await invoke("get_hetzner_ssh_public_key")).isError).toBe(true); + expect((await invoke("check_hetzner_ssh",{serverId:88})).isError).toBe(true); expect(provider).not.toHaveBeenCalled(); await ownerGrant(first,true); const reflection = (await invoke("get_api_reflection")).structuredContent.integrations.find((row: any)=>row.id===integration); @@ -91,21 +98,27 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy expect((await invoke("request_api",get,auth(second))).isError).toBe(true); expect((await invoke("request_api",{...get,path:"/v1/../oauth/test"})).isError).toBe(true); expect((await invoke("request_api",{...get,path:"//elsewhere.example/v1/servers"})).isError).toBe(true); - expect((await invoke("request_api",post)).isError).toBe(true); - expect((await invoke("request_api",{...post,execution:"sync"})).isError).toBe(true); expect(provider).not.toHaveBeenCalled(); const read = (await invoke("request_api",get)).structuredContent; expect(read).toMatchObject({status:200,headers:{"x-provider-request":"native-read"}}); expect(JSON.parse(read.body)).toMatchObject({servers:[{id:88,name:"demo",location:{name:"fsn1"}}]}); expect(String(provider.mock.calls[0]?.[0])).toBe("https://api.hetzner.cloud/v1/servers?name=demo"); + const readOnlyWrite = (await invoke("request_api",{...post,execution:"sync"})).structuredContent; + expect(readOnlyWrite.status).toBe(403); + expect(JSON.parse(readOnlyWrite.body)).toEqual({error:{code:"forbidden",message:"Read-only project token"}}); + const roQueued = (await invoke("request_api",post)).structuredContent; + await processProxyOperation(f.env,f.tenantId,roQueued.operationId); + expect((await invoke("get_api_operation",{operationId:roQueued.operationId})).structuredContent).toMatchObject({state:"complete",status:403}); + expect(validations.rejectedWrites).toBe(2); + const oldKey = (await invoke("get_hetzner_ssh_public_key")).structuredContent; expect(oldKey.publicKey).toMatch(/^ssh-ed25519 /); expect(oldKey.privateKey).toBeUndefined(); expect((await invoke("get_hetzner_ssh_public_key",{},auth(second))).isError).toBe(true); - const turnedOn = await project({name:"Native",token:writeToken,nativeWritesEnabled:true}); - expect(await turnedOn.json()).toEqual({connection:{name:"Native",nativeWritesEnabled:true}}); + const turnedOn = await project({name:"Native",token:writeToken}); + expect(await turnedOn.json()).toEqual({connection:{name:"Native"}}); expect((await invoke("request_api",post)).isError).toBe(true); expect(validations.writes).toBe(0); await ownerGrant(first,true); @@ -146,7 +159,9 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy expect((await invoke("read_api_response",{handle:receipt.operationId})).isError).toBe(true); expect((await invoke("read_api_response",{handle})).isError).toBe(true); expect((await invoke("get_hetzner_ssh_public_key")).isError).toBe(true); + expect((await invoke("check_hetzner_ssh",{serverId:88})).isError).toBe(true); expect((await invoke("request_api",get)).isError).toBe(true); + expect((await invoke("request_api",{...post,execution:"sync"})).isError).toBe(true); await ownerGrant(first,true); const staleProject = (await invoke("request_api",{...post,idempotencyKey:"rotated-before-dispatch"})).structuredContent; @@ -158,6 +173,6 @@ it.skipIf(!url)("routes native Hetzner reads and writes through sync/async proxy expect((await invoke("get_api_operation",{operationId:staleProject.operationId})).isError).toBe(true); expect((await invoke("read_api_response",{handle:receipt.operationId})).isError).toBe(true); expect((await invoke("request_api",get)).structuredContent.status).toBe(200); - expect((await invoke("request_api",post)).isError).toBe(true); + expect((await invoke("request_api",{...post,execution:"sync"})).structuredContent.status).toBe(403); } finally { vi.unstubAllGlobals(); await f.cleanup(); } }); diff --git a/packages/app/src/features/integrations/hetzner.tsx b/packages/app/src/features/integrations/hetzner.tsx index b912ccbe..586861bb 100644 --- a/packages/app/src/features/integrations/hetzner.tsx +++ b/packages/app/src/features/integrations/hetzner.tsx @@ -19,7 +19,6 @@ export function useHetznerIntegration() { const session = useQuery(sessionQuery); const owner = session.data?.authenticated && session.data.team?.role === "owner"; const [screen, setScreen] = useState<"edit" | "delete" | "inventory" | null>(null); - const [nativeWritesEnabled, setNativeWritesEnabled] = useState(false); const [name, setName] = useState(""); const [token, setToken] = useState(""); const [notice, setNotice] = useState(""); @@ -35,7 +34,7 @@ export function useHetznerIntegration() { return data; } }); const write = useMutation({ retry: false, mutationFn: async (operation: "save" | "delete") => { - const result = operation === "save" ? await api.PUT(connectionPath, { body: { name: name.trim(), token: token.trim(), ...(nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } }) : + const result = operation === "save" ? await api.PUT(connectionPath, { body: { name: name.trim(), token: token.trim() } }) : await api.DELETE(connectionPath); if (!result.data || result.error) throw new Error(withRequestReference(messageOf(result.error), result.response)); return operation; @@ -47,7 +46,6 @@ export function useHetznerIntegration() { }, onSettled: () => setToken("") }); function open(next: typeof screen) { setName(connection?.name ?? ""); - setNativeWritesEnabled(connection?.nativeWritesEnabled === true); setToken(""); setNotice(""); write.reset(); @@ -58,7 +56,7 @@ export function useHetznerIntegration() { return { count: owner && connection ? 1 : 0, pending: Boolean(owner && query.isPending), - rows: owner && connection ? open("inventory") }, { label: "Replace connection", onClick: () => open("edit") }, { label: "Delete", destructive: true, onClick: () => open("delete") }, @@ -70,10 +68,8 @@ export function useHetznerIntegration() { {screen === "edit" &&
{ event.preventDefault(); write.mutate("save"); }}> - - {nativeWritesEnabled &&

Native writes can create billable resources, modify them, or delete them. Enable this only for a project you want these clients to manage.

} - -

Create a project API token in Hetzner Cloud Console with {nativeWritesEnabled ? "Read & Write" : "Read"} permission. Factorize tests inventory on save. Hetzner enforces its token permissions on every request.

+ +

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

{connection &&

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

}
diff --git a/packages/app/test/functional/hetzner.spec.mjs b/packages/app/test/functional/hetzner.spec.mjs index 8933a3ed..a0251d89 100644 --- a/packages/app/test/functional/hetzner.spec.mjs +++ b/packages/app/test/functional/hetzner.spec.mjs @@ -1,6 +1,6 @@ import { test, expect } from "./fixtures.mjs"; -test("an owner saves a read-only Hetzner project, views inventory, explicitly enables native writes, and confirms local deletion", async ({ page, origin }) => { +test("an owner saves a read-only Hetzner project, views inventory, replaces the token without a separate permission switch, and confirms local deletion", async ({ page, origin }) => { const token = "syntheticReadOnlyProjectToken", writeToken = "syntheticReadWriteProjectToken"; const requests = []; let connection = null, unavailable = true; @@ -19,10 +19,10 @@ test("an owner saves a read-only Hetzner project, views inventory, explicitly en requests.push(method); if (method === "PUT") { const provisioning = Boolean(connection); - expect(route.request().postDataJSON()).toEqual({ name: "Fixture project", ...(provisioning ? { token: writeToken, nativeWritesEnabled: true } : { token }) }); + expect(route.request().postDataJSON()).toEqual({ name: "Fixture project", ...(provisioning ? { token: writeToken } : { token }) }); if (unavailable) return route.fulfill({ status: 502, headers: { "X-Request-Id": requestId }, json: { error: { code: "hetzner_inventory_error", message: "Hetzner server inventory is unavailable. Try again." } } }); - connection = { name: "Fixture project", ...(provisioning ? { nativeWritesEnabled: true } : {}) }; + connection = { name: "Fixture project" }; } if (method === "DELETE") { connection = null; @@ -44,7 +44,7 @@ test("an owner saves a read-only Hetzner project, views inventory, explicitly en await page.getByRole("button", { name: "Add Hetzner Cloud integration" }).click(); const add = page.getByRole("dialog", { name: "Add Hetzner Cloud integration" }); await add.getByLabel("Project name").fill("Fixture project"); - const tokenInput = add.getByLabel("Read-only project API token"); + const tokenInput = add.getByLabel("Project API token"); await expect(tokenInput).toHaveAttribute("type", "password"); await tokenInput.fill(token); await add.getByRole("button", { name: "Save connection" }).click(); @@ -66,13 +66,11 @@ test("an owner saves a read-only Hetzner project, views inventory, explicitly en await row.getByRole("button", { name: "Actions for Hetzner Cloud · Fixture project" }).click(); await page.getByRole("menuitem", { name: "Replace connection", exact: true }).click(); const edit = page.getByRole("dialog", { name: "Replace Hetzner Cloud connection" }); - await expect(edit.getByRole("checkbox", { name: "Allow authorized clients to make native API writes" })).not.toBeChecked(); - await edit.getByRole("checkbox", { name: "Allow authorized clients to make native API writes" }).check(); + await expect(edit.getByRole("checkbox")).toHaveCount(0); await expect(edit.getByText(/create billable resources/)).toBeVisible(); - await edit.getByLabel("Read & Write project API token").fill(writeToken); + await edit.getByLabel("Project API token").fill(writeToken); await edit.getByRole("button", { name: "Save connection" }).click(); await expect(edit).not.toBeVisible(); - await expect(row.getByText("Native API writes enabled")).toBeVisible(); await row.getByRole("button", { name: "Actions for Hetzner Cloud · Fixture project" }).click(); await page.getByRole("menuitem", { name: "Delete", exact: true }).click(); const deletion = page.getByRole("dialog", { name: "Delete Hetzner Cloud connection?" }); diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index 4da19e38..b874b4aa 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -24,13 +24,16 @@ kept. Reconnecting does not restore removed configuration or grants. ### Hetzner Cloud Add the project in **Integrations → Hetzner Cloud** with a Hetzner project -token. The default is read only. To allow writes, an owner must explicitly -enable **native API writes**, use a **Read & Write** token, and check the -Hetzner permission for each intended OAuth client. Enabling this makes the -project's native write methods available, including destructive changes. -The former bounded server-provisioning opt-in does not enable native writes. -Replacing the project resets client grants and stored SSH keys. Reassign only -the clients that should have access. +token. Check **Hetzner Cloud** in an OAuth client's permissions to allow it +to use the native API and its enrolled SSH access. Unchecking it removes +both immediately; neither change requires reconnecting the OAuth client. + +Hetzner enforces the project token's permissions. Choose **Read** for inventory +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. Use `get_api_reflection` to find the authorized Hetzner connection ID. Then use the standard `request_api` tool with the method, relative `/v1/...` path, diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index a663370c..3e43ccd8 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -354,13 +354,16 @@ kept. Reconnecting does not restore removed configuration or grants. ### Hetzner Cloud Add the project in **Integrations → Hetzner Cloud** with a Hetzner project -token. The default is read only. To allow writes, an owner must explicitly -enable **native API writes**, use a **Read & Write** token, and check the -Hetzner permission for each intended OAuth client. Enabling this makes the -project's native write methods available, including destructive changes. -The former bounded server-provisioning opt-in does not enable native writes. -Replacing the project resets client grants and stored SSH keys. Reassign only -the clients that should have access. +token. Check **Hetzner Cloud** in an OAuth client's permissions to allow it +to use the native API and its enrolled SSH access. Unchecking it removes +both immediately; neither change requires reconnecting the OAuth client. + +Hetzner enforces the project token's permissions. Choose **Read** for inventory +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. Use `get_api_reflection` to find the authorized Hetzner connection ID. Then use the standard `request_api` tool with the method, relative `/v1/...` path, diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 4c537277..326bd280 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -7735,8 +7735,6 @@ paths: properties: name: type: string - nativeWritesEnabled: - type: boolean required: - name additionalProperties: false @@ -7770,7 +7768,7 @@ paths: put: 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 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. + Owner browser session only. Choose Read to limit checked clients to reads or Read & Write to allow native changes, deletions, and billable resources. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources. Requires the integrations:write scope. @@ -7788,8 +7786,6 @@ paths: properties: name: type: string - nativeWritesEnabled: - type: boolean required: - name additionalProperties: false @@ -7832,8 +7828,6 @@ paths: type: string minLength: 1 maxLength: 120 - nativeWritesEnabled: - type: boolean token: type: string minLength: 1