diff --git a/packages/cloud-init/src/reverse-tunnel.ts b/packages/cloud-init/src/reverse-tunnel.ts index 7b34c966b6..6ad2aaf809 100644 --- a/packages/cloud-init/src/reverse-tunnel.ts +++ b/packages/cloud-init/src/reverse-tunnel.ts @@ -90,19 +90,28 @@ export function validateReverseTunnelVariables( if (!validPort(remote)) { errors.push(`reverseTunnelRemotePort: must be numeric 1-65535 (got ${JSON.stringify(remote)})`); } + // frpc dials the control plane's host. The shared URL check is a character allowlist, so an + // unparseable URL (for example port 65536) would otherwise render an empty serverAddr. + if (!reverseTunnelServerAddress(variables.controlPlaneUrl)) { + errors.push( + 'controlPlaneUrl: must be an HTTPS URL with a host and a valid port in reverse-tunnel mode' + ); + } } -/** Host and port frpc dials: the control plane's own public HTTPS endpoint. */ -export function reverseTunnelServerAddress(controlPlaneUrl: string): { - host: string; - port: string; -} { +/** + * Host and port frpc dials: the control plane's own public HTTPS endpoint. Null when the URL is + * not an HTTPS URL with a host; validateReverseTunnelVariables rejects that case in reverse mode. + */ +export function reverseTunnelServerAddress( + controlPlaneUrl: string +): { host: string; port: string } | null { try { const url = new URL(controlPlaneUrl); + if (url.protocol !== 'https:' || !url.hostname) return null; return { host: url.hostname, port: url.port || '443' }; } catch { - // validateCloudInitVariables already rejected an unparseable control plane URL. - return { host: '', port: '443' }; + return null; } } @@ -110,10 +119,14 @@ export function reverseTunnelServerAddress(controlPlaneUrl: string): { export function reverseTunnelReplacements(variables: CloudInitVariables): Record { const reverse = isReverseTunnelMode(variables); const release = FRPC_RELEASES[DEFAULT_FRPC_VERSION]; - const server = reverseTunnelServerAddress(variables.controlPlaneUrl); + // Inert for non-reverse nodes, whose controlPlaneUrl this mode does not validate. + const server = reverseTunnelServerAddress(variables.controlPlaneUrl) ?? { host: '', port: '443' }; return { '{{ reverse_tunnel_credential }}': reverse ? (variables.reverseTunnelCredential ?? '') : '', - '{{ reverse_tunnel_remote_port }}': reverse ? (variables.reverseTunnelRemotePort ?? '') : '', + // Canonical decimal: frpc's TOML rejects a leading zero (validated numeric before render). + '{{ reverse_tunnel_remote_port }}': reverse + ? String(Number(variables.reverseTunnelRemotePort ?? '')) + : '', '{{ reverse_tunnel_server_addr }}': server.host, '{{ reverse_tunnel_server_port }}': server.port, '{{ reverse_tunnel_proxy_name }}': REVERSE_TUNNEL_PROXY_NAME, diff --git a/packages/cloud-init/src/template-reverse-tunnel.ts b/packages/cloud-init/src/template-reverse-tunnel.ts index 3307a644ab..dfdfeafcfa 100644 --- a/packages/cloud-init/src/template-reverse-tunnel.ts +++ b/packages/cloud-init/src/template-reverse-tunnel.ts @@ -28,7 +28,11 @@ export const REVERSE_TUNNEL_BOOTSTRAP_RUNCMD = ` - 'logger -t sam-boot "PHASE S /usr/local/sbin/sam-boot-failure frpc_install exit 1 fi - install -m 0755 "$FRP_DIR/$FRP_NAME/frpc" /usr/local/bin/frpc + if ! install -m 0755 "$FRP_DIR/$FRP_NAME/frpc" /usr/local/bin/frpc; then + rm -rf "$FRP_TMP" "$FRP_DIR" + /usr/local/sbin/sam-boot-failure frpc_install + exit 1 + fi rm -rf "$FRP_TMP" "$FRP_DIR" id sam-frpc >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin sam-frpc if ! /etc/sam/firewall/setup-firewall.sh; then @@ -53,8 +57,10 @@ export const REVERSE_TUNNEL_CONNECTOR_RUNCMD = ` - 'logger -t sam-boot "PHASE S * when the pool refills, not on the path of each proxied connection. * loginFailExit=false + Restart=always: frpc keeps * retrying (an frps restart, a Caddy restart, an authz rejection while the lease is being - * fixed) instead of exiting. useSystemCa: frpc verifies the box's public certificate; without - * it frpc would accept any certificate. + * fixed) instead of exiting. Type=exec makes `systemctl enable --now` fail when the binary + * cannot be executed, so the connector runcmd reports tunnel_connector rather than booting + * without a connector. useSystemCa: frpc verifies the box's public certificate; without it + * frpc would accept any certificate. */ export const REVERSE_TUNNEL_WRITE_FILES = `${TUNNEL_LISTENER_WAIT_WRITE_FILE} @@ -100,6 +106,7 @@ export const REVERSE_TUNNEL_WRITE_FILES = `${TUNNEL_LISTENER_WAIT_WRITE_FILE} StartLimitIntervalSec=0 [Service] + Type=exec User=sam-frpc EnvironmentFile=/etc/sam/frpc/credential.env ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener diff --git a/packages/cloud-init/src/tunnel.ts b/packages/cloud-init/src/tunnel.ts index 4b137a8127..0c1d57b454 100644 --- a/packages/cloud-init/src/tunnel.ts +++ b/packages/cloud-init/src/tunnel.ts @@ -204,6 +204,11 @@ export function ingressFragments(variables: CloudInitVariables): Record { const tunnel = isTunnelMode(variables); const cloudflare = isCloudflareTunnelMode(variables); + // Reverse mode renders validated numbers in canonical decimal: frpc's TOML rejects leading + // zeros and dash arithmetic reads them as octal. Cloudflare output stays byte-identical to + // before the reverse mode existed (tests/cloudflare-output-snapshot.test.ts); its own + // leading-zero handling is tracked in tasks/backlog/2026-11-18-reverse-tunnel-cloud-init-hardening.md. + const num = (value: string) => (isReverseTunnelMode(variables) ? String(Number(value)) : value); const version = orDefault(variables.cloudflaredVersion, DEFAULT_CLOUDFLARED_VERSION); const release = CLOUDFLARED_RELEASES[version]; return { @@ -213,23 +218,25 @@ export function tunnelReplacements(variables: CloudInitVariables): Record { expect(() => validateCloudInitVariables(reverse(overrides))).toThrow(/validation failed/); }); + it('rejects a control plane URL that frpc could not dial (no empty serverAddr)', () => { + const url = 'https://api.box.example.org:65536'; + expect(() => validateCloudInitVariables(reverse({ controlPlaneUrl: url }))).toThrow( + 'controlPlaneUrl: must be an HTTPS URL with a host and a valid port in reverse-tunnel mode' + ); + // Control: the same URL is not this mode's concern on other nodes. + let message = ''; + try { + validateCloudInitVariables(variables({ controlPlaneUrl: url })); + } catch (error) { + message = (error as Error).message; + } + expect(message).not.toContain('reverse-tunnel mode'); + }); + + it('keeps an explicit control plane port and defaults to 443', () => { + const toml = (url: string) => + file( + parse(reverse({ controlPlaneUrl: url, jwksUrl: `${url}/jwks` })), + '/etc/sam/frpc/frpc.toml' + ).content; + expect(toml('https://api.box.example.org:8443')).toMatch(/^serverPort = 8443$/m); + expect(toml('https://api.box.example.org')).toMatch(/^serverPort = 443$/m); + }); + + it('renders leading-zero numbers in canonical decimal (TOML and dash arithmetic)', () => { + const parsed = parse( + reverse({ + reverseTunnelRemotePort: '020007', + reverseTunnelLocalPort: '08444', + tunnelListenerWaitSeconds: '08', + tunnelListenerProbeIntervalSeconds: '09', + }) + ); + const toml = file(parsed, '/etc/sam/frpc/frpc.toml').content; + expect(toml).toMatch(/^remotePort = 20007$/m); + expect(toml).toMatch(/^localPort = 8444$/m); + const wait = file(parsed, '/usr/local/sbin/sam-wait-tunnel-listener').content; + expect(wait).toContain('+ 8))'); + expect(wait).toContain('sleep 9'); + expect(wait).toContain('http://127.0.0.1:8444/health'); + }); + it('never echoes the credential in validation errors', () => { let message = ''; try { @@ -166,6 +209,7 @@ describe('rendered reverse-tunnel user-data', () => { it('supervises frpc as an unprivileged, restart-always unit gated on the agent listener', () => { const parsed = parse(reverse()); const unit = file(parsed, '/etc/systemd/system/sam-frpc.service').content; + expect(unit).toContain('Type=exec\n'); expect(unit).toContain('User=sam-frpc\n'); expect(unit).toContain('EnvironmentFile=/etc/sam/frpc/credential.env\n'); expect(unit).toContain('ExecStartPre=/usr/local/sbin/sam-wait-tunnel-listener\n'); @@ -254,7 +298,7 @@ function runBootScript(vars: CloudInitVariables, env: Record = { while [ "$#" -gt 0 ]; do if [ "$1" = -fsSLo ]; then shift; cp "$TEST_DIR/frp.tar.gz" "$1"; fi; shift; done; exit 0 ;; esac while [ "$#" -gt 0 ]; do if [ "$1" = -fLo ] || [ "$1" = -fsSLo ]; then shift; printf 'binary' > "$1"; fi; shift; done`, sha256sum: `echo "\${FAKE_SHA:-${RELEASE.amd64}} $1"`, - install: 'true', + install: 'case "$*" in *frpc*) exit "${FRPC_INSTALL_EXIT:-0}" ;; esac', id: 'exit 1', useradd: 'true', chown: 'true', @@ -321,6 +365,36 @@ describe('executed reverse-tunnel boot sequence', () => { if (reason === 'frpc_install') expect(calls).not.toMatch(/^install /m); }); + it('fails closed when the verified frpc cannot be installed', () => { + const { result, calls } = runBootScript(reverse(), { FRPC_INSTALL_EXIT: '1' }); + expect(result.status).toBe(1); + expect(calls).toMatch(/^install -m 0755 \S+\/frpc /m); + expect(calls).toContain('sam-boot-failure frpc_install'); + expect(calls).not.toContain('systemctl start vm-agent'); + expect(calls).not.toContain('sam-frpc.service'); + }); + + it('runs the rendered listener wait script under /bin/sh with a leading-zero wait', () => { + const dir = mkdtempSync(join(tmpdir(), 'sam-reverse-wait-test-')); + tempDirs.push(dir); + const bin = join(dir, 'bin'); + mkdirSync(bin); + for (const [name, body] of Object.entries({ curl: 'exit 0', logger: 'true', sleep: 'true' })) { + writeFileSync(join(bin, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 }); + } + const script = file( + parse(reverse({ tunnelListenerWaitSeconds: '08' })), + '/usr/local/sbin/sam-wait-tunnel-listener' + ).content; + const result = spawnSync('/bin/sh', ['-c', script], { + env: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, + encoding: 'utf8', + timeout: 10_000, + }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + }); + it('reports a connector that cannot start', () => { const { result, calls } = runBootScript(reverse(), { FRPC_UNIT_EXIT: '1' }); expect(result.status).toBe(1);