Files
orca/src/main/ssh/system-ssh-args.ts
T
Neil 278f9ee876 fix(ssh): answer every MFA stage, stop dialling an unclaimed alias, and say where a clone failed (#17946)
* fix(ssh): answer every MFA stage, not just the first

ssh2 walks one flat auth-method list exactly once, so keyboard-interactive
could only ever be offered a single time. A host running
`AuthenticationMethods keyboard-interactive,keyboard-interactive` (or any
ladder ending in a second challenge) partial-succeeds the first stage and
then finds the list exhausted, which the user sees as "All configured
authentication methods failed" — the reports in #8622 and #16820.

Orca's own auth handler now runs for every target instead of only multi-key
ones, and rebuilds its queue on each SSH_MSG_USERAUTH_FAILURE that carries
partial success, narrowed to the methods the host still offers. Narrowing
also stops keys being re-offered after the host has moved past publickey,
which is what exhausts MaxAuthTries before the challenge is ever shown.

Covered by a real ssh2 server fixture that stages partial success.

* fix(git): say where a failing clone ran and why nothing could prompt

Clones go through nonInteractiveGitEnv, so `ssh` runs with BatchMode=yes and an
emptied SSH_ASKPASS. On a remote or paired-runtime clone that produces
`fatal: Could not read from remote repository.` while the same `git clone`
typed by hand on that box succeeds — the divergence in #14533. Nothing in the
message said the clone ran on the other machine, under its keys, with the
prompt deliberately disabled.

getGitCloneFailureMessage now appends that fact, and names the two recognisable
shapes: a publickey refusal (load the key into an agent there) and a host-key
failure (record the key in that machine's known_hosts). Unrecognised SSH
failures still get the where-it-ran note; non-SSH failures are untouched.

One builder, so the SSH-target relay path and the runtime path both get it.

* fix(ssh): stop dialling a bare alias no ssh_config block claims

A wildcard `Host *` block supplies ProxyCommand/ProxyJump for every alias, so
shouldUseSystemSshTransport picks the system transport for an alias whose own
Host block was renamed or deleted, and buildSshArgs then dials that alias
verbatim: no -l, no -p, no Hostname. Orca connects as the wildcard's user to
the wildcard's host and discards the endpoint it stored (#11746).

The signal #11746 assumed (hostBlockMatch, from the still-open #11707) does not
exist, and `ssh -G` cannot supply it — it prints the merged config and answers
for unknown aliases too. The config file is the only source of truth, so:

- parseSshConfigAliasClaims retains raw Host patterns and flags Match blocks,
  which parseSshConfig discards because it mints importable targets.
- sshConfigMayClaimAlias is sound in the negative direction only: an unreadable
  file, any Match block, or any non-catch-all pattern that might match all
  answer "claimed", so absence of evidence is never read as evidence of
  absence. Only a proven-unclaimed alias licenses an override.
- buildSshArgs then states Hostname/Port/User, and only those: the wildcard is
  still the route, and -o Hostname does not change block selection, so the
  proxy keeps applying and %h expands to the host we mean.

The verdict is injected rather than read inside buildSshArgs, so an arg builder
does not answer differently per machine. Default is today's behaviour.

Scoped to the system-SSH transport and the connection's own command/transport
path. Port-forward processes and the ssh2 transport (#11707) are unchanged.

* fix(ssh): read a negated Host group as uncertainty, and gate clone SSH guidance

`Host * !prod` applies to every alias but `prod`, yet skipping both the catch-all
and the `!` pattern answered "unclaimed" for `stage` — which licences overriding
Hostname/Port/User against a block the user wrote. Any negation now makes the
whole group uncertain; the function is only sound in the negative direction.

Also require an ssh(1) diagnostic beside "could not read from remote repository"
before appending the SSH clone note: git prints that same line for the HTTP
remote helper, where advice about keys and agents is simply wrong.

* fix(i18n): restore the activity-options key the rebase dropped

* fix(i18n): union en.json with main so the rebase cannot drop keys
2026-09-02 15:14:53 -07:00

236 lines
8.6 KiB
TypeScript

import type { SshTarget } from '../../shared/ssh-types'
import { getControlSocketPath, type SystemSshResolvedConfig } from './ssh-control-socket'
export type SystemSshBuildArgsOptions = {
configFile?: string
resolvedConfig?: SystemSshResolvedConfig | null
disableControlMaster?: boolean
suppressOrcaControlMaster?: boolean
gssapiOnly?: boolean
nonInteractive?: boolean
/**
* `false` only when the parsed ssh_config proves no `Host`/`Match` block claims `configHost`.
*
* Absent or `true` keeps the config alias fully authoritative, which is right whenever a block
* really does name it — and is the only safe default, since a caller that cannot answer must not
* be read as having answered "nothing claims it". See `sshConfigMayClaimAlias`.
*/
aliasClaimedByConfig?: boolean
}
export function buildSshArgs(target: SshTarget, options?: SystemSshBuildArgsOptions): string[] {
const args: string[] = []
if (options?.configFile) {
args.push('-F', options.configFile)
}
args.push('-o', options?.gssapiOnly || options?.nonInteractive ? 'BatchMode=yes' : 'BatchMode=no')
if (options?.gssapiOnly) {
// Why: the probe must neither authenticate with a key nor open an OpenSSH
// credential prompt; failure belongs to Orca's existing ssh2 prompt path.
args.push('-o', 'GSSAPIAuthentication=yes')
args.push('-o', 'PreferredAuthentications=gssapi-with-mic')
}
// Forward stdin/stdout for relay communication
args.push('-T')
// Why: ControlMaster multiplexes all SSH exec commands over a single connection,
// eliminating the ~9s handshake overhead per command. Without this, each
// spawnSystemSshCommand call opens a new TCP connection.
const controlPath = getOrcaControlSocketPath(target, options)
const forceDisableControlMaster =
options?.disableControlMaster === true ||
target.systemSshConnectionReuse === false ||
(options?.gssapiOnly === true && controlPath === null)
if (forceDisableControlMaster) {
// Why: muxed OpenSSH forwards remain registered on the master after the
// client exits. Also honors the per-target compatibility opt-out even if
// a broad Host * ssh_config block enables multiplexing.
args.push('-S', 'none')
} else if (controlPath) {
args.push('-o', 'ControlMaster=auto')
args.push('-o', `ControlPath=${controlPath}`)
// Why: keep master alive 300s after last command so rapid reconnects
// (e.g. on tab focus) skip re-handshake without holding a process open.
args.push('-o', 'ControlPersist=300')
args.push('-o', 'ServerAliveInterval=15')
args.push('-o', 'ServerAliveCountMax=3')
}
const useConfigHost = shouldUseOpenSshConfigHost(target)
// Why: a wildcard `Host *` block supplies ProxyCommand/ProxyJump for every alias, so an alias
// whose own Host block was renamed or deleted still looks config-backed and gets dialled bare —
// as the wildcard's user, at the wildcard's host, discarding the endpoint Orca stored. Keep the
// system transport (OpenSSH must still apply that proxy) but state the stored endpoint, and only
// where the config proves no block claims the alias.
if (useConfigHost && options?.aliasClaimedByConfig === false) {
appendUnclaimedAliasEndpoint(args, target)
}
if (!useConfigHost && target.port !== 22) {
args.push('-p', String(target.port))
}
if (!useConfigHost && target.identityFile) {
args.push('-i', target.identityFile)
}
if (!useConfigHost && target.identityAgent) {
args.push('-o', `IdentityAgent=${target.identityAgent}`)
}
if (!useConfigHost && target.identitiesOnly) {
args.push('-o', 'IdentitiesOnly=yes')
}
if (!useConfigHost && target.gssapiAuthentication && !options?.gssapiOnly) {
// Why: manual targets bypass ssh_config, so Kerberos auth must be
// requested explicitly; config-backed hosts inherit it from their entry.
args.push('-o', 'GSSAPIAuthentication=yes')
}
if (!useConfigHost && target.jumpHost) {
args.push('-J', target.jumpHost)
}
if (!useConfigHost && target.proxyCommand) {
args.push('-o', `ProxyCommand=${target.proxyCommand}`)
}
const host = target.configHost || target.host
// Why: OpenSSH owns User for config-backed aliases; imported fallback values
// must not override a fresh wildcard, Include, or Match result.
const userHost = useConfigHost ? host : target.username ? `${target.username}@${host}` : host
args.push('--', userHost)
return args
}
export function getOrcaControlSocketPath(
target: SshTarget,
options?: SystemSshBuildArgsOptions
): string | null {
if (shouldDisableOrcaControlMaster(target, options)) {
return null
}
return getControlSocketPath(target, options?.resolvedConfig, options?.gssapiOnly === true)
}
export function getSystemSshBuildArgsFromOperationOptions(
options: SystemSshBuildArgsOptions | undefined
): SystemSshBuildArgsOptions | undefined {
const buildArgsOptions: SystemSshBuildArgsOptions = {}
if (options?.configFile !== undefined) {
buildArgsOptions.configFile = options.configFile
}
if (options?.resolvedConfig !== undefined) {
buildArgsOptions.resolvedConfig = options.resolvedConfig
}
if (options?.disableControlMaster === true) {
buildArgsOptions.disableControlMaster = true
}
if (options?.suppressOrcaControlMaster === true) {
buildArgsOptions.suppressOrcaControlMaster = true
}
if (options?.gssapiOnly === true) {
buildArgsOptions.gssapiOnly = true
}
if (options?.nonInteractive === true) {
buildArgsOptions.nonInteractive = true
}
if (options?.aliasClaimedByConfig === false) {
buildArgsOptions.aliasClaimedByConfig = false
}
return Object.keys(buildArgsOptions).length === 0 ? undefined : buildArgsOptions
}
function shouldDisableOrcaControlMaster(
target: SshTarget,
options?: SystemSshBuildArgsOptions
): boolean {
// Why: unresolved ssh_config aliases could otherwise share one Orca socket
// while OpenSSH routes them through mutable HostName/ProxyJump settings.
const unresolvedConfigBackedTarget =
isOpenSshConfigBackedTarget(target) && options?.resolvedConfig == null
return (
options?.disableControlMaster === true ||
options?.suppressOrcaControlMaster === true ||
target.systemSshConnectionReuse === false ||
unresolvedConfigBackedTarget ||
(hasUserConfiguredControlMaster(options?.resolvedConfig) && options?.gssapiOnly !== true)
)
}
function hasUserConfiguredControlMaster(
resolvedConfig: SystemSshResolvedConfig | null | undefined
): boolean {
if (!resolvedConfig) {
return false
}
// Why: ControlPersist/ControlPath alone can reuse a master someone else
// created, but they do not create the setup-burst master Orca needs.
return (
hasEnabledControlMaster(resolvedConfig.controlMaster) &&
hasEnabledControlPath(resolvedConfig.controlPath)
)
}
function hasEnabledControlMaster(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase()
return (
normalized != null &&
normalized !== '' &&
normalized !== '0' &&
normalized !== 'no' &&
normalized !== 'false'
)
}
function hasEnabledControlPath(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase()
return normalized != null && normalized !== '' && normalized !== 'none'
}
/**
* Restore only Hostname/Port/User, and only where they diverge from the alias.
*
* Not `-i`/`-J`/ProxyCommand: the wildcard block is still the route to this network, and `-o
* Hostname=` does not change which blocks OpenSSH selects (matching uses the original destination),
* so the proxy keeps applying and `%h` now expands to the host we actually mean.
*/
function appendUnclaimedAliasEndpoint(args: string[], target: SshTarget): void {
const alias = target.configHost
const storedHost = target.host.trim()
if (storedHost && alias && storedHost !== alias) {
args.push('-o', `Hostname=${storedHost}`)
}
if (target.port && target.port !== 22) {
args.push('-p', String(target.port))
}
if (target.username) {
args.push('-l', target.username)
}
}
function shouldUseOpenSshConfigHost(target: SshTarget): boolean {
if (!target.configHost) {
return false
}
return isOpenSshConfigBackedTarget(target)
}
export function isOpenSshConfigBackedTarget(
target: Pick<SshTarget, 'source' | 'configHost' | 'host'>
): boolean {
if (target.source === 'ssh-config') {
return true
}
if (target.source === 'manual') {
return false
}
// Why: legacy imported aliases have a distinct configHost; manual targets
// historically stored configHost=host and still need explicit -p/-i args.
return Boolean(target.configHost && target.configHost !== target.host)
}