Skip to content
Merged
2 changes: 1 addition & 1 deletion .claude/rules/06-vm-agent-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Required pattern:

1. Edit `packages/cloud-init/src/template.ts`
2. Update variable types in `src/variables.ts`, validation in `src/validate.ts` and wiring in `src/generate.ts` when needed
3. Ingress-mode blocks (Origin CA direct mode, Cloudflare Tunnel mode) live in `src/template-ingress.ts` and render only for their mode; keep user-data under the 32 KB Hetzner limit
3. Ingress-mode blocks (Origin CA direct mode, Cloudflare Tunnel mode) live in `src/template-ingress.ts`, and the self-host reverse-tunnel (frpc) blocks in `src/template-reverse-tunnel.ts`; each renders only for its mode. Keep user-data under the 32 KB Hetzner limit, and keep `tests/cloudflare-output-snapshot.test.ts` passing unchanged when editing shared fragments
4. Test cloud-init generation through the workspace provisioning flow

### Runcmd Interpreter Contract
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/routes/node-boot-failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const BootFailureSchema = v.object({
'origin_ca_bootstrap',
'vm_agent_download',
'cloudflared_install',
'frpc_install',
'tunnel_firewall',
'tunnel_connector',
]),
Expand Down
1 change: 1 addition & 0 deletions apps/api/tests/unit/routes/node-boot-failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ describe('boot failure callback', () => {
'origin_ca_bootstrap',
'vm_agent_download',
'cloudflared_install',
'frpc_install',
'tunnel_firewall',
'tunnel_connector',
])('records %s through authenticated callback routing', async (reason) => {
Expand Down
115 changes: 115 additions & 0 deletions apps/api/tests/unit/services/node-reverse-tunnel-boot-render.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Register shared boundary mocks before importing production services.
import './node-tunnel-fixture';

import type * as CloudInit from '@simple-agent-manager/cloud-init';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import YAML from 'yaml';

import { installReverseTunnelTransport } from '../../../src/selfhost/reverse-tunnel/transport';
import { provisionNode } from '../../../src/services/nodes';
import { applySqliteMigration } from '../../helpers/sqlite-d1';
import { env, freshNode, mocks, setEnv, sqlite, tunnelEnv } from './node-tunnel-fixture';

/**
* L18 vertical slice: the real provisionNode leases a reverse-tunnel port, the self-host driver
* passes the lease to the REAL cloud-init renderer (the fixture's capture mock is bypassed), and
* the provider receives user-data that boots frpc against that lease. The lifecycle slice
* (node-reverse-tunnel-lifecycle.test.ts) covers leases and teardown with captured variables;
* this one proves the rendered boot document is what a node would actually run.
*/
const GATEWAY_SECRET = ['gateway', 'fixture', 'value', 'for', 'reverse', 'tunnel', 'tests'].join(
'-'
);

const rendered: string[] = [];

type BootDoc = {
runcmd: string[];
write_files: Array<{ path: string; content: string; permissions?: string; owner?: string }>;
};

function file(doc: BootDoc, path: string) {
const entry = doc.write_files.find((f) => f.path === path);
if (!entry) throw new Error(`missing write_files entry ${path}`);
return entry;
}

beforeEach(async () => {
rendered.length = 0;
applySqliteMigration(
sqlite,
new URL('../../../src/selfhost/migrations/0255_node_reverse_tunnel_leases.sql', import.meta.url)
);
const real = await vi.importActual<typeof CloudInit>('@simple-agent-manager/cloud-init');
installReverseTunnelTransport((variables) => {
const userData = real.generateCloudInit(variables);
rendered.push(userData);
return userData;
});
});

describe('reverse-tunnel node boot document', () => {
it('renders frpc bound to the leased port, with the credential only in the root-only file', async () => {
setEnv(
tunnelEnv({
VM_AGENT_TRANSPORT: 'reverse-tunnel',
REVERSE_TUNNEL_GATEWAY_SECRET: GATEWAY_SECRET,
ENCRYPTION_KEY: 'test-encryption-key-for-reverse-tunnel-credentials',
CF_API_TOKEN: undefined,
CF_ACCOUNT_ID: undefined,
CF_ZONE_ID: undefined,
})
);
const node = await freshNode();
await expect(provisionNode(node.id, env)).resolves.toEqual({
allocationConfirmed: true,
});

expect(rendered).toHaveLength(1);
const userData = rendered[0]!;
// The provider received exactly the document the real renderer produced.
expect(mocks.createVM).toHaveBeenCalledWith(expect.objectContaining({ userData }));

const lease = sqlite
.prepare('SELECT port FROM node_reverse_tunnel_leases WHERE node_id = ?')
.get(node.id) as { port: number };
// The fixture's capture mock was bypassed: the real renderer produced this document.
expect(mocks.cloudInitVars).toHaveLength(0);

const doc = YAML.parse(userData) as BootDoc;
const frpc = file(doc, '/etc/sam/frpc/frpc.toml');
expect(frpc.content).toMatch(new RegExp(`^remotePort = ${lease.port}$`, 'm'));
expect(frpc.content).toMatch(/^localPort = 8444$/m);
expect(frpc.content).toContain(`user = "${node.id}"`);
expect(frpc.content).toContain(
'metadatas.credential = "{{ .Envs.SAM_REVERSE_TUNNEL_CREDENTIAL }}"'
);

const credentialFile = file(doc, '/etc/sam/frpc/credential.env');
expect(credentialFile.permissions).toBe('0400');
const [, secret] = /^SAM_REVERSE_TUNNEL_CREDENTIAL=([A-Za-z0-9_-]{43})$/m.exec(
credentialFile.content
)!;
// The credential appears in exactly one place in the whole boot document.
expect(userData.split(secret!).length - 1).toBe(1);

file(doc, '/etc/systemd/system/sam-frpc.service');
expect(doc.runcmd.join('\n')).toContain('systemctl enable --now sam-frpc.service');
// No Cloudflare ingress, no Origin CA, no public agent ingress.
expect(userData).not.toMatch(
/sam-cloudflared|cloudflared-linux|origin-ca-certificate|PHASE START: origin-ca/
);
});

it('control: a Cloudflare node never reaches the reverse-tunnel renderer', async () => {
setEnv(tunnelEnv({ VM_AGENT_TRANSPORT: 'cloudflare-tunnel' }));
const node = await freshNode();
await provisionNode(node.id, env);

expect(rendered).toHaveLength(0);
expect(mocks.cloudInitVars).toHaveLength(1);
expect(mocks.cloudInitVars[0]).not.toHaveProperty('reverseTunnelCredential');
// Liveness: this really is the Cloudflare Tunnel provisioning path.
expect(mocks.cloudInitVars[0]).toMatchObject({ cloudflareTunnelToken: expect.any(String) });
});
});
10 changes: 9 additions & 1 deletion apps/www/src/content/docs/docs/architecture/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,21 @@ Forwarded HTTP and WebSocket applications never receive SAM preview cookies, VM

### Tunnel Ingress Nodes

Cloud-init and the VM agent also support a node that is reachable only through an outbound Cloudflare Tunnel connector. A node is in this mode when cloud-init receives `cloudflareTunnelToken` (`isTunnelMode` in `packages/cloud-init/src/tunnel.ts`). With `VM_AGENT_TRANSPORT=cloudflare-tunnel`, the control plane creates one tunnel per managed VM incarnation, workspace and deployment nodes alike, and journals its ownership before provisioning (`resolveManagedNodeTransport` in `apps/api/src/services/node-tunnel-config.ts`). Direct-ingress nodes and instant-container routing retain their existing transports. On a deployment node the tunnel carries only the VM agent connection: its app routes still reach Caddy on ports 80 and 443 over the public IP, so the firewall leaves those ports open while dropping the agent port, the tunnel listener and SSH.
Cloud-init and the VM agent also support a node that is reachable only through an outbound Cloudflare Tunnel connector. A node is in this mode when cloud-init receives `cloudflareTunnelToken`. With `VM_AGENT_TRANSPORT=cloudflare-tunnel`, the control plane creates one tunnel per managed VM incarnation, workspace and deployment nodes alike, and journals its ownership before provisioning (`resolveManagedNodeTransport` in `apps/api/src/services/node-tunnel-config.ts`). Direct-ingress nodes and instant-container routing retain their existing transports. On a deployment node the tunnel carries only the VM agent connection: its app routes still reach Caddy on ports 80 and 443 over the public IP, so the firewall leaves those ports open while dropping the agent port, the tunnel listener and SSH.

- The node receives only its own connector run token, never an account API token. Cloud-init writes it to `/etc/sam/cloudflared/tunnel-token` (mode `0400`, owned by the connector's system user) and skips Origin CA bootstrap entirely (`TUNNEL_BOOTSTRAP_RUNCMD` in `packages/cloud-init/src/template-ingress.ts`).
- Cloud-init installs a pinned `cloudflared` release only after its SHA-256 matches the value recorded for that architecture (`CLOUDFLARED_RELEASES` in `packages/cloud-init/src/tunnel.ts`), then applies the firewall before the VM agent starts. In tunnel mode the firewall drops inbound IPv4 and IPv6 traffic to the agent port, the tunnel listener port and SSH, allows Docker bridges to reach the agent port, and does not allowlist Cloudflare IPs. The rules live in a dedicated `SAM-TUNNEL-INGRESS` chain replaced by one `iptables-restore --noflush` transaction per address family (the existing INPUT jump is checked before the restore starts, because the restore holds the xtables lock), so re-applying (daily cron, provisioning, every VM agent start via `ExecStartPre`) never leaves a window without them, and the VM agent does not start if the firewall fails. It fails closed when the host has a global IPv6 address but `ip6tables` is unusable (`TUNNEL_FIREWALL_WRITE_FILE` in `packages/cloud-init/src/template-ingress.ts`).
- The VM agent serves the connector on a separate listener bound to `127.0.0.1` (`VM_AGENT_TUNNEL_ENABLED`, `VM_AGENT_TUNNEL_PORT`, default `8444`). Every request on it is classified as relayed before routing (`classifyTunnelIngress` in `packages/vm-agent/internal/server/tunnel_ingress.go`). The connector reaches the agent from loopback, so this classification is what refuses the node-local Git credential helper bearer (see Workspace Git credential exchange below) on the tunnel listener. Tunnel requests use the same JWT, session and callback-token checks as before.
- `sam-cloudflared.service` runs as an unprivileged system user and starts only after the tunnel listener answers `/health` (`TUNNEL_WRITE_FILES` in `packages/cloud-init/src/template-ingress.ts`). The tunnel's ingress service must be `http://127.0.0.1:<VM_AGENT_TUNNEL_PORT>`. The main agent port is never a valid tunnel target.

### Reverse-Tunnel Ingress Nodes (Self-Hosted)

A self-hosted control plane boots workspace nodes in a third mode, selected when cloud-init receives a non-empty `reverseTunnelCredential` (`isReverseTunnelMode` in `packages/cloud-init/src/reverse-tunnel.ts`; the Cloudflare deployment never sets it). `isTunnelMode` in `packages/cloud-init/src/tunnel.ts` is true for both tunnel modes, because they share the same firewall, the loopback tunnel listener and its classification as relayed traffic, and both skip Origin CA bootstrap.

- The node receives only its own lease credential, an HMAC derived per lease, node and incarnation (`apps/api/src/selfhost/reverse-tunnel/`). Cloud-init writes it only to `/etc/sam/frpc/credential.env` (mode `0400`, root), which systemd reads into the connector's environment; `frpc.toml` refers to it through frp's environment template and holds no secret. Validation errors never echo it.
- Cloud-init installs a pinned frpc release only after its SHA-256 matches the value recorded for that architecture (`FRPC_RELEASES` in `packages/cloud-init/src/reverse-tunnel.ts`), then applies the tunnel firewall before the VM agent starts. A failed install reports the `frpc_install` boot-failure reason.
- `sam-frpc.service` runs as an unprivileged system user, starts only after the tunnel listener answers, and dials the control-plane host over `wss` on its public HTTPS port, verifying the certificate against the system CA store. It exposes only the tunnel listener, as one TCP proxy on the leased loopback port of the control-plane host (`REVERSE_TUNNEL_WRITE_FILES` in `packages/cloud-init/src/template-reverse-tunnel.ts`).

### Workspace Git credential exchange

Git inside a workspace authenticates through a credential helper that asks the VM agent's local `/git-credential` route for a short-lived repository token; the agent exchanges it with the control plane using the workspace's callback token, which the helper does not carry. A node runs one user's workspaces, which can belong to different projects, so the route must not let one workspace obtain another's token.
Expand Down
15 changes: 14 additions & 1 deletion apps/www/src/content/docs/docs/guides/self-hosting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,20 @@ instance owns session replacement. Its Login plugin must apply the server-select
with `unchange: false`, and every subsequent operation checks that session against the lease.
Credential-key rotation recovery is tracked separately. Changing the root key rejects stale
resume derivation and old session IDs, but a credential matching the stored lease hash can
still log in and obtain the new session ID; root-key rotation alone does not revoke that lease. Cloud-init and installer packaging follow this foundation.
still log in and obtain the new session ID; root-key rotation alone does not revoke that lease. Installer packaging follows this foundation.

The node boot document for this transport comes from `@simple-agent-manager/cloud-init`. A
non-empty `reverseTunnelCredential` selects reverse-tunnel mode (`isReverseTunnelMode` in
`packages/cloud-init/src/reverse-tunnel.ts`). The node then gets the Cloudflare Tunnel firewall
(no public agent or SSH ingress), no Origin CA certificate and no cloudflared. It installs a
pinned frpc release, checked against a per-architecture sha256, and runs it as the unprivileged
`sam-frpc` unit (`packages/cloud-init/src/template-reverse-tunnel.ts`). frpc dials the control
plane host over `wss` on its public HTTPS port, verifies its certificate against the system CA
store, and exposes only the agent's loopback tunnel listener as one TCP proxy on the leased port.
The credential is written only to the root-only `/etc/sam/frpc/credential.env`; `frpc.toml`
reads it through frp's environment template. A failed frpc install reports the
`frpc_install` boot-failure reason. Cloudflare nodes never set these variables and render
exactly as before.

The self-host entry wraps the shared Worker with `withReverseTunnel(worker, render)` from
`apps/api/src/selfhost/reverse-tunnel/entry.ts`. That call installs the transport driver, serves
Expand Down
1 change: 1 addition & 0 deletions packages/cloud-init/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Generates cloud-init YAML templates for VM provisioning. Produces the user-data
| `src/variables.ts` / `src/validate.ts` | `CloudInitVariables` and their validation |
| `src/template-resources.ts` | Slice hierarchy and Docker headroom write_files, interpolated into the template |
| `src/template-ingress.ts` / `src/tunnel.ts` | Ingress-mode blocks (Origin CA direct vs Cloudflare Tunnel) and tunnel validation; each node renders only its own mode |
| `src/reverse-tunnel.ts` / `src/template-reverse-tunnel.ts` | Self-host reverse-tunnel (frpc) mode: validation, pinned release, replacements and connector blocks. Cloudflare nodes never set its variables; `tests/cloudflare-output-snapshot.test.ts` pins their output byte for byte |

## Commands

Expand Down
8 changes: 8 additions & 0 deletions packages/cloud-init/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ export {
validateCloudInitSize,
validateCloudInitVariables,
} from './generate';
export {
DEFAULT_FRPC_VERSION,
FRPC_RELEASES,
isReverseTunnelMode,
REVERSE_TUNNEL_HEARTBEAT_INTERVAL_SECONDS,
REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS,
REVERSE_TUNNEL_PROXY_NAME,
} from './reverse-tunnel';
export { CLOUD_INIT_TEMPLATE } from './template';
export {
CLOUDFLARED_RELEASES,
Expand Down
Loading
Loading