Skip to content

feat(ssh): support ordered multi-host commands and constrained connection options - #84

Merged
abruption merged 6 commits into
mainfrom
feat/20-multi-host-ssh
Oct 3, 2026
Merged

abruption merged 6 commits into
mainfrom
feat/20-multi-host-ssh

Conversation

@abruption

@abruption abruption commented Oct 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #87. Refs #20. Not a full close: typed jump routing is now implemented for POSIX clients (--ssh-jump). On Windows clients it is refused (ssh_jump_unsupported_platform) until Win32-OpenSSH ProxyCommand handling is verified, so the jump-routing item is not fully met on every supported client platform. PARITY keeps SSH as Partial.

Adds ordered multi-host SSH for list, send and doctor, an allowlisted --ssh-opt, IPv6 destinations and sshUser/sshUserSource metadata. The existing guarded local/SSH contract is unchanged: exact-version preflight, JSON stdin request, owner verification, ambiguity refusal, pre-submit revalidation, and no retry after unknown.

Acceptance criteria

Criterion Status Implementation
Flat result for one host, ordered per-host results for repeated hosts, partial failure and exit semantics for list/send/doctor Done With one --host, output is the same flat object as before. When --host is repeated, output is a JSON array in request order (Python one_or_many), and every element has schemaVersion/ok/host (as requested)/command. If any host fails, the overall exit code is 1 (Python EXIT_ERROR). A single host keeps its verified 0/1/2 code. Text output prints one Host: <host> block per host.
Validate all routes/options before dispatch; at most one submission attempt per destination; unknown stays unknown, no failover/resend Done parse() validates every host, --ssh-opt, remote option and the message before any ssh process starts, including ssh -G. Refusal contract: every --host VALUE/--host=VALUE before -- is collected before any other check. With two or more of them, every pre-dispatch refusal is an array with one submitted:false element per host; this includes syntax errors such as an unknown option or a missing value. With fewer, it is one flat object. Python's argparse syntax errors print usage to stderr without JSON; TS always answers in JSON. Repeating the same destination gives duplicate_ssh_host. This check is syntactic (user, case-insensitive host, canonical IPv6); aliases or addresses of the same physical host are not detected. Each host gets one preflight and at most one request. A refused or unknown host is reported in place, and later hosts still get their single attempt.
Constrained --ssh-opt interface; reject local-command vectors and anything weakening batch/host-key requirements Done for POSIX clients; partial overall (jump refused on Windows clients) Allowlist only: -p, -l, -i, -o Port=/User=/IdentityFile=/IdentitiesOnly=, -4, -6. Values can be separate or attached tokens, as in Python's --ssh-opt=-p --ssh-opt=2222. All other options give unsupported_ssh_option. A bad, duplicate or dash-leading value gives invalid_ssh_option. Identity paths refuse % and $ (OpenSSH token/env expansion). Options are re-emitted canonically after the fixed BatchMode=yes, StrictHostKeyChecking=yes, ConnectTimeout=10 (OpenSSH keeps the first value).
Safe IPv6 parsing, sshUser/sshUserSource; keep Windows quoting and --ssh-control-path Done 2001:db8::1, [2001:db8::1] and user@[2001:db8::1] are accepted. Brackets are stripped for ssh and sshHost shows the destination actually used. Zone IDs and bracketed IPv4 are refused. sshUserSource is explicit (USER@HOST or -l), ssh_config_or_local_default (one local ssh -G per host without an explicit user, 5 s limit; it does not connect, but it evaluates the user's ssh_config, including Match exec, as Python's lookup does) or unknown, as in Python. -l together with USER@HOST gives conflicting_ssh_user because -l silently wins. The PowerShell -EncodedCommand path is unchanged and applies to every host. --ssh-control-path now requires exactly one --host, because one socket multiplexes one destination.
Fake-SSH tests: ordering, argv, validation-before-send, partial errors, IPv6, POSIX/Windows paths, no body in shell strings Done New test/ssh-hosts.test.ts, plus a two-host case in the Windows native fixture.

Option interface design

  • Allowlist, not blocklist. OpenSSH has many spellings that run local commands: ProxyCommand, LocalCommand/PermitLocalCommand, KnownHostsCommand, Match exec, Include, -F, PKCS11Provider/-I, SecurityKeyProvider, RemoteCommand, ProxyUseFdpass, among others. None of them can pass because only these keys are recognized: port, user, identityfile, identitiesonly and address family. -o accepts only Key=Value without whitespace, so OpenSSH's own -o tokenizer cannot split a value into a second option.
  • Typed jump routing (--ssh-jump USER@HOST[:PORT]). One hop with an explicit user; IPv6 needs brackets. Only shell- and %-inert characters are accepted (invalid_ssh_jump). -J/ProxyJump/ProxyCommand stay refused in --ssh-opt, because OpenSSH's own -J hop (exec ssh -l u -W '[target]:22' jump) receives no command-line BatchMode/StrictHostKeyChecking. Instead the CLI places one fixed option with the other fixed options:
    -o ProxyCommand='<ssh path>' -T -o BatchMode=yes -o StrictHostKeyChecking=yes -o UpdateHostKeys=no -o ConnectTimeout=10 -o ConnectionAttempts=1 -o ProxyCommand=none -o ProxyJump=none -o ControlPath=none -o ForwardAgent=no -o ClearAllForwardings=yes -o PermitLocalCommand=no [-p PORT] -l USER -W '[%h]:%p' -- HOST.
    The path is single-quoted for the shell and every % in it is doubled. The option is refused with --ssh-control-path (conflicting_ssh_jump) and on Windows clients (ssh_jump_unsupported_platform). Results add sshJump. There is no multi-hop and no Tailscale lookup for the hop (v1).
  • Bounded timeouts (fix(process): bound timeouts by reaping the owned SSH process group #87, cbe29df). run() used to kill only the direct child and then wait for close, so a pipe-holding descendant such as the jump ProxyCommand delayed completion and outlived the timeout.
    • On POSIX every external command now runs in its own process group (detached). A timeout or output overflow kills that group only (process.kill(-pid, 'SIGKILL'), ESRCH ignored, no PID scans) and destroys the streams. Completion is the exit plus a fixed 100 ms grace, not the pipes closing.
    • SIGINT, SIGTERM and SIGHUP to the CLI kill the active groups and are then re-raised with default handling, so Ctrl-C still ends the ssh group.
    • On Windows only the child is killed, streams are destroyed and the call returns at the deadline; descendants may linger there, and --ssh-jump is refused on Windows clients.
    • Timeout classification and values are unchanged: a preflight timeout is ssh_preflight_timeout (refusal) and a request timeout is unknown with no retry.
    • Regressions (test/process.test.ts, POSIX):
      • a helper whose grandchild inherits stdout, both staying and with the child exiting at once: a 300 ms timeout returns in about 0.6 s with interrupted/spawned true, and both PIDs are gone;
      • SIGTERM to a runner process: it exits by SIGTERM within 1.5 s and the group is gone.
    • With the previous run(), the first regression never returned (stopped after 200 s).
  • Follow-up (8cbad61, non-blocking review). The process group is registered synchronously as soon as spawn() returns a PID, with the spawn event as the fallback, so a signal that arrives before that event still reaps the group. The docs now state that POSIX detached starts a new session and process group with no controlling terminal, and that cleanup covers that group only: a descendant that leaves it with setsid() is out of scope, and there is no PID scanning. Narrow validation: test/process.test.ts, test/ssh-hosts.test.ts and test/transport.test.ts gave 26 tests, 25 pass, 0 fail, 1 skipped (Windows-only); the repository check is OK.
  • Shell scope and hop options. The generated ProxyCommand was verified through sh, bash and zsh (exec <command> with an ssh path containing spaces, a quote and %, run as ssh -G). Other login shells (for example fish or csh) are unverified. --ssh-opt values, including -4/-6, apply to the target only and are not passed to the hop.
  • Outer control-master hardening (0692293). With --ssh-jump, the outer ssh also gets -o ControlMaster=no -o ControlPath=none -o ProxyUseFdpass=no, placed before the ProxyCommand and the user options. A configured ControlMaster auto/ControlPath, which could reuse an existing master and bypass the hop, and a configured ProxyUseFdpass yes are therefore overridden. Verified with local ssh -G -F <fixture> (no connection): before, controlmaster auto, a control path and proxyusefdpass yes; after, controlmaster false, no control path and proxyusefdpass no. The regression test runs this same ssh -G check when an ssh binary is present, and also checks that a configured ProxyJump is replaced. The --ssh-control-path conflict refusal stays. Unverified boundaries: Win32-OpenSSH clients (refused) and ProxyCommand parsing by a non-POSIX login $SHELL.
  • Pre-implementation checks (local ssh -G -F <fixture config> only, OpenSSH 10.3p1, no connection):
    • (a) pass: a command-line ProxyCommand overrides both a configured ProxyJump and a configured ProxyCommand for the target, without error. Without the override, the configured ProxyJump stays.
    • (b) pass: ssh_config(5) lists ${ENV} expansion only for CertificateFile, ControlPath, IdentityAgent, IdentityFile, Include, KnownHostsCommand and UserKnownHostsFile, not ProxyCommand. ProxyCommand accepts only the %%, %h, %n, %p, %r tokens and runs through the user's shell; hence the single quoting, %% escaping and charset limits. -G preserves the option text verbatim.
    • (c) pass: the hop's command-line ProxyCommand=none/ProxyJump=none override a jump host's configured ProxyCommand or ProxyJump.
    • An extra sanity check ran the constructed hop command through sh -c as ssh -G. It resolved to user/port from --ssh-jump, batchmode yes, stricthostkeychecking true, updatehostkeys false, connectionattempts 1, connecttimeout 10, forwardagent no, clearallforwardings yes, permitlocalcommand no, with no proxy.
  • Two trust boundaries. The allowlist governs only options this CLI puts on the ssh command line. The user's and system ssh_config are trusted user configuration (ssh(1), ssh_config(5)): ProxyCommand, ProxyJump, Match exec, Include and similar settings there apply to every ssh this CLI starts, including ssh -G, exactly as for the user's own ssh. The PARITY and guide texts state this in all four languages.
  • Hardening. The sshUser lookup now runs inside per-host handling. A lookup failure gives unknown for that host only, and that host's dispatch and all earlier and later results are kept.
  • ConnectTimeout is not exposed, because a user value could never override the fixed first one.

Files

  • src/ssh.ts (new): sshOptions() allowlist/canonicalizer, sshUser() metadata (ssh -G, 5 s bound).
  • src/protocol.ts: host() accepts IPv6 literals and returns the OpenSSH destination.
  • src/cli.ts: repeated --host/--ssh-opt, pre-dispatch validation, duplicate/conflict checks, ordered remotes() loop, shared failure() envelope, per-host attribution of command-wide refusals.
  • src/output.ts: array rendering (JSON array; text Host: blocks). src/help.ts: usage.
  • Docs: docs/guide{,.ko,.ja,.zh-CN}.md new "Several hosts and connection options" section, and the old "no --ssh-opt/IPv6" sentence is removed. PARITY.md SSH rows and a new section describing unreleased source behavior.
  • Packaging lists: scripts/release.mjs, test/package-smoke.ts include dist/ssh.{js,d.ts}.
  • Tests: test/ssh-hosts.test.ts (new). Existing POSIX fake ssh scripts and test/fixtures/windows-native.cs answer ssh -G without logging it as a dispatch. The Windows contract also covers two hosts.

Type

  • feat
  • fix
  • docs
  • chore / refactor / test / perf

Validation

  • npm ci --ignore-scripts and npm run build
  • SESSION_PEER_PYTHON_ROOT=/path/to/pinned/reference npm test: 89 tests, 84 pass, 0 fail, 5 skipped (Windows-only, including the Windows --ssh-jump refusal test). Baseline was 77/73/0/4.
  • npm run test:package: packageSmoke: pass, clean install/uninstall. npm audit: 0 vulnerabilities.
  • node scripts/check-repository.mjs: OK. node scripts/release.mjs pack: file list includes dist/ssh.*.
  • Latest CI release gate passes with an up-to-date base (run 36970169560 on 8cbad61: contract macOS/Ubuntu × Node 22/24, windows-native 22/24, repository-policy, release gate pass. windows-native (24) first failed on the known PowerShell cold-start inspection timeout (ETIMEDOUT at 8.1 s in an unrelated Unicode-collision test; Windows does not use the changed POSIX process-group path) and passed on one rerun of the failed job. CodeQL run 36970166058 pass)
  • Behavior changes include relevant tests; refused/unknown/queued/ACK remain distinct
  • README changes are synchronized in EN/KO/JA/zh-CN (README entry pages unchanged; the four guides are updated together)
  • No credentials, real messages, session IDs, agent homes or local evidence in the diff

New test coverage (test/ssh-hosts.test.ts):

  • host() IPv6 acceptance and 17 refused forms. sshOptions() canonical argv plus 43 unsupported and 21 invalid token sequences, covering the vectors listed above and bypass spellings (-oproxycommand=, -o 'Proxy Command=…', -oPort=22 -oProxyCommand=…, -F/x, -Jjump, -46).
  • 19 invalid multi-host invocations each produce a per-host refusal array, exit 2, and zero ssh invocations (including no ssh -G). This includes the syntax counterexamples --host alpha --host beta --bogus, --host=alpha --host beta --all=x and a missing --remote-bin value. Two counterexamples stay flat: a single --host, and --host text after --.
  • Ordering, call sequence and partial failure for list (exit 1), doctor and text output. A single host stays flat, and ssh -G failure gives sshUser:null/unknown. A -G failure for the middle of three hosts keeps all three dispatches and results.
  • Four-host send: posted / request exit 255 (unknown, submitted:null, no resend) / preflight refusal / posted. The unknown case is a classification fixture: the fake exits without running the remote CLI, so it shows unknown is never retried, not that a delivered message's response was lost. Exactly two inbox deliveries. A shell-metacharacter and Unicode body is absent from every ssh argv and present only in the stdin JSON.
  • --ssh-jump: strict parser (24 refused values) and exact ProxyCommand text for a path with spaces, a quote and %. A fake ssh under such a path expands %h/%p/%%, runs the ProxyCommand via /bin/sh -c exec and records the hop argv. Checked:
    • two hosts (one IPv6) with -p 2222 give 4 outer calls and 4 hops, with exact hop argv -W [target]:2222 -- jump;
    • the body is absent from both argv levels;
    • 7 injection values (;, $(…), %h, -o…, missing user, bare IPv6 with a port, newline) give a per-host invalid_ssh_jump and zero ssh;
    • conflicts with --ssh-control-path, a missing --host, a repeated --ssh-jump, and --ssh-opt -J/ProxyCommand are refused;
    • a Windows-client refusal test runs on Windows CI.
  • Exact argv: fixed hardening options first, then the canonical user options, --, destination. POSIX quoted --remote-bin with spaces. Windows --remote-platform win32 decodes to the expected PowerShell command for each host.

Tested environments / limitations

  • Local: macOS (darwin arm64), Node 24.16.0, OpenSSH 10.3p1 (used only for ssh -G and a -J proxy-command inspection against a TEST-NET address). All transport tests use fake ssh executables. No real SSH destination or agent session was contacted.
  • Windows behavior (native fixture ssh.exe with -G handling, two-host PowerShell path) is verified only by CI. It has not been run locally.
  • No real-host evidence for IPv6 destinations, -i/-p against a live server, or Windows OpenSSH ssh -G output.

Release impact

No release or deployment. Additive JSON fields (sshUser, sshUserSource, sshHost on single-host SSH failures; version/referenceVersion now also on single-host SSH-stage failures) and a new array shape only when --host is repeated. Stricter: --ssh-control-path with several hosts is refused. Both SSH endpoints still require the same version. No native dependency changes.

…tion options

Accept repeated --host for list, send and doctor. One host keeps the flat
result; several return an ordered array whose elements keep schemaVersion,
ok, host and command. Each destination gets one preflight and at most one
request, and a refused or unknown host never triggers a retry or failover.

Validate every host, option and message before any ssh process starts and
refuse duplicate destinations. Add an allowlisted --ssh-opt (-p, -l, -i,
-o Port/User/IdentityFile/IdentitiesOnly, -4, -6) re-emitted after the fixed
BatchMode/StrictHostKeyChecking options; ProxyJump and every other option
are refused. Accept bare and bracketed IPv6 literals and report
sshUser/sshUserSource like Python.

Closes #20
…ust boundaries

Collect --host values before other validation so any pre-dispatch refusal
with two or more hosts, including unknown options and missing values, is a
per-host array; fewer hosts stay one flat object. Keep the user lookup inside
per-host handling so a lookup failure leaves other results intact.

Document that sshUser runs a bounded local ssh -G which evaluates the user's
ssh configuration, separate the command-line allowlist from trusted user
configuration, state that duplicate detection is syntactic, keep typed jump
routing visible as open, and describe the lost-response fixture as an
unknown classification case.
…oxyCommand

Route every SSH call for every --host through one jump host given as
USER@HOST[:PORT]. Instead of -J, whose hop receives no command-line
BatchMode or StrictHostKeyChecking, build a fixed ProxyCommand: the
shell-quoted and %-escaped ssh path with batch mode, strict host keys, no
host-key updates, bounded connection attempts, no further proxy, control
socket, agent or port forwarding, and no local command, then -W to the
target. Validate the hop strictly, refuse it with --ssh-control-path and on
Windows clients, report sshJump, and keep -J/ProxyJump/ProxyCommand refused
in --ssh-opt.
With --ssh-jump, also fix ControlMaster=no, ControlPath=none and
ProxyUseFdpass=no on the outer ssh before user options, so an existing master
or fd-passing setting in ssh_config cannot skip or alter the hop. Verified
with ssh -G against a fixture configuration.
On POSIX, start every external command in its own process group. A timeout,
an output overflow or SIGINT/SIGTERM/SIGHUP to the CLI kills that group,
including a jump ProxyCommand that keeps the pipes open, and the call
completes after the exit plus a short grace instead of waiting for the pipes.
On Windows only the child is killed and the call returns at the deadline.
Timeout classification is unchanged. Document the verified ProxyCommand
shells and that --ssh-opt values are not passed to the jump hop.

Closes #87
Register a detached child's group synchronously when spawn() returns a PID,
keeping the spawn event as a fallback, so a signal that arrives before that
event still reaps the group. Document that detached children run in a new
session without a controlling terminal and that cleanup covers that group
only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(process): bound timeouts by reaping the owned SSH process group

1 participant