Files
orca/src/shared/git-clone-failure-message.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

115 lines
4.7 KiB
TypeScript

import { stripCredentialsFromMessage } from './git-remote-error'
// Why: clones run under nonInteractiveGitEnv (GIT_TERMINAL_PROMPT=0, empty SSH_ASKPASS,
// `ssh -o BatchMode=yes`) so a background clone cannot hang on a prompt nobody sees. The cost is
// that git's own SSH errors read identically to an ordinary permission problem, and on a remote
// or paired-runtime clone the user is looking at their own working local `git clone` while Orca
// fails — with nothing in the message saying the clone ran somewhere else, without their agent.
const CLONE_HOST_NOTE =
'The clone runs non-interactively (BatchMode=yes) on the machine that will hold the repository, using the SSH keys and agent on that machine rather than the ones on this computer.'
const CLONE_KEY_HINT = `${CLONE_HOST_NOTE} A passphrase-protected key cannot prompt there, so load it into an agent on that machine (ssh-add) and retry.`
const CLONE_HOST_KEY_HINT = `${CLONE_HOST_NOTE} It has not trusted this host key yet — connect once from a shell on that machine to record it in its known_hosts.`
/** An ssh(1) diagnostic, i.e. a line only the SSH transport can have produced. */
const SSH_TRANSPORT_DIAGNOSTIC =
/\bssh|permission denied \(|connection (?:closed|reset|refused|timed out) by/i
export function getGitCloneFailureMessage(
stderr: string,
options: { clonePath?: string | null } = {}
): string {
return appendCloneTransportGuidance(
getGitCloneFailureLine(stderr, options),
stripCredentialsFromMessage(stderr)
)
}
/** Guidance the raw git error omits: where the clone ran, and why nothing could prompt there. */
function appendCloneTransportGuidance(message: string, scrubbedStderr: string): string {
// Re-entrant: remote-repo-clone re-parses a message the relay already built.
if (message.includes(CLONE_HOST_NOTE)) {
return message
}
if (/host key verification failed/i.test(scrubbedStderr)) {
return `${message} ${CLONE_HOST_KEY_HINT}`
}
if (/permission denied \(([^)]*publickey[^)]*)\)/i.test(scrubbedStderr)) {
return `${message} ${CLONE_KEY_HINT}`
}
// Every other SSH-transport failure still needs the one fact the reporter was missing — but only
// once something proves the transport was SSH: git prints this same line for the HTTP remote
// helper, where a note about keys and agents is simply wrong.
return /could not read from remote repository/i.test(scrubbedStderr) &&
SSH_TRANSPORT_DIAGNOSTIC.test(scrubbedStderr)
? `${message} ${CLONE_HOST_NOTE}`
: message
}
function getGitCloneFailureLine(
stderr: string,
options: { clonePath?: string | null } = {}
): string {
let fallbackLine: string | null = null
// Why: clone errors echo the URL the user typed, which is the most likely
// git error to embed a live token (`https://user:ghp_…@host/repo.git`).
// Scrub up-front so every return branch operates on already-redacted text,
// matching normalizeGitErrorMessage.
const scrubbedStderr = stripCredentialsFromMessage(stderr)
for (const rawLine of iterateLinesFromEnd(scrubbedStderr)) {
const line = stripAnsi(rawLine).trim()
if (!line) {
continue
}
fallbackLine ??= line
const fatalIndex = line.indexOf('fatal:')
if (fatalIndex !== -1) {
return formatGitCloneFailureLine(line.slice(fatalIndex), options)
}
const errorIndex = line.indexOf('error:')
if (errorIndex !== -1) {
return formatGitCloneFailureLine(line.slice(errorIndex), options)
}
}
return formatGitCloneFailureLine(fallbackLine ?? 'unknown error', options)
}
function* iterateLinesFromEnd(value: string): Generator<string> {
let lineEnd = value.length
let index = value.length - 1
while (index >= 0) {
const code = value.charCodeAt(index)
if (code !== 10 && code !== 13) {
index--
continue
}
const delimiterStart =
code === 10 && index > 0 && value.charCodeAt(index - 1) === 13 ? index - 1 : index
yield value.slice(index + 1, lineEnd)
lineEnd = delimiterStart
index = delimiterStart - 1
}
yield value.slice(0, lineEnd)
}
function stripAnsi(value: string): string {
return value.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'), '')
}
function formatGitCloneFailureLine(line: string, options: { clonePath?: string | null }): string {
const destinationMatch = line.match(
/^fatal:\s+destination path '([^']+)' already exists and is not an empty directory\.$/
)
if (destinationMatch || /repository exists/i.test(line)) {
const destination = options.clonePath?.trim() || destinationMatch?.[1] || null
const target = destination ? `: ${destination}` : ''
return `Destination already exists and is not empty${target}. Choose a different parent folder, delete the existing folder, or add the existing repository instead.`
}
return line
}