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
31 changes: 22 additions & 9 deletions packages/cloud-init/src/reverse-tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,30 +90,43 @@ 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;
}
}

/** Template replacements for reverse-tunnel mode; other nodes get inert values. */
export function reverseTunnelReplacements(variables: CloudInitVariables): Record<string, string> {
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,
Expand Down
13 changes: 10 additions & 3 deletions packages/cloud-init/src/template-reverse-tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}

Expand Down Expand Up @@ -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
Expand Down
33 changes: 20 additions & 13 deletions packages/cloud-init/src/tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,11 @@ export function ingressFragments(variables: CloudInitVariables): Record<string,
export function tunnelReplacements(variables: CloudInitVariables): Record<string, string> {
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 {
Expand All @@ -213,23 +218,25 @@ export function tunnelReplacements(variables: CloudInitVariables): Record<string
'{{ vm_agent_exec_start_pre }}': tunnel
? 'ExecStartPre=/etc/sam/firewall/setup-firewall.sh'
: '',
'{{ tunnel_port }}': tunnelListenerPort(variables),
'{{ tunnel_port }}': num(tunnelListenerPort(variables)),
'{{ tunnel_token }}': cloudflare ? (variables.cloudflareTunnelToken ?? '') : '',
'{{ tunnel_listener_wait_seconds }}': orDefault(
variables.tunnelListenerWaitSeconds,
DEFAULT_TUNNEL_LISTENER_WAIT_SECONDS
'{{ tunnel_listener_wait_seconds }}': num(
orDefault(variables.tunnelListenerWaitSeconds, DEFAULT_TUNNEL_LISTENER_WAIT_SECONDS)
),
'{{ tunnel_listener_probe_timeout_seconds }}': orDefault(
variables.tunnelListenerProbeTimeoutSeconds,
DEFAULT_TUNNEL_LISTENER_PROBE_TIMEOUT_SECONDS
'{{ tunnel_listener_probe_timeout_seconds }}': num(
orDefault(
variables.tunnelListenerProbeTimeoutSeconds,
DEFAULT_TUNNEL_LISTENER_PROBE_TIMEOUT_SECONDS
)
),
'{{ tunnel_listener_probe_interval_seconds }}': orDefault(
variables.tunnelListenerProbeIntervalSeconds,
DEFAULT_TUNNEL_LISTENER_PROBE_INTERVAL_SECONDS
'{{ tunnel_listener_probe_interval_seconds }}': num(
orDefault(
variables.tunnelListenerProbeIntervalSeconds,
DEFAULT_TUNNEL_LISTENER_PROBE_INTERVAL_SECONDS
)
),
'{{ tunnel_connector_restart_seconds }}': orDefault(
variables.tunnelConnectorRestartSeconds,
DEFAULT_TUNNEL_CONNECTOR_RESTART_SECONDS
'{{ tunnel_connector_restart_seconds }}': num(
orDefault(variables.tunnelConnectorRestartSeconds, DEFAULT_TUNNEL_CONNECTOR_RESTART_SECONDS)
),
'{{ cloudflared_url }}': `${CLOUDFLARED_DOWNLOAD_BASE_URL}/${version}/cloudflared-linux`,
'{{ cloudflared_sha256_amd64 }}': release?.amd64 ?? '',
Expand Down
76 changes: 75 additions & 1 deletion packages/cloud-init/tests/reverse-tunnel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,49 @@ describe('reverse-tunnel variable validation', () => {
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 {
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -254,7 +298,7 @@ function runBootScript(vars: CloudInitVariables, env: Record<string, string> = {
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',
Expand Down Expand Up @@ -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);
Expand Down