Skip to content

[P1] fix(ssh): stop discarding stored target fields and trying only the first identity - #11707

Draft
nwparker wants to merge 3 commits into
mainfrom
nwparker/p1-ssh-config-resolution-regressions
Draft

nwparker wants to merge 3 commits into
mainfrom
nwparker/p1-ssh-config-resolution-regressions

Conversation

@nwparker

@nwparker nwparker commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Think of a saved SSH host as a speed-dial entry: the name prod on the button, and the real number (10.0.0.5, port 2222, as deploy, via the bastion switchboard) stored behind it. Asking OpenSSH "what does prod mean?" (ssh -G prod) never says "no such entry" — if the entry is gone it cheerfully answers with a made-up default: "call the number prod, port 22, as whoever you are, no switchboard." We were believing that answer and throwing away everything we had stored, so tidying up ~/.ssh/config (or opening Orca on another machine) silently re-pointed a saved host at a literal name that, on a corporate network with DNS search domains, can be an entirely different machine — and agent-forwarded identities were offered to it. Now we only believe the answer when it shows real evidence a Host block matched; otherwise the stored fields win.

Second, smaller one: when you have several keys, we handed ssh2 the first one to hold onto. ssh2 unwraps that key immediately, so a legacy passphrase-protected ~/.ssh/id_rsa blew up the whole connection before the good id_ed25519 was ever tried — you got a passphrase prompt for a key the server never asked for. Now we hand it the first key that actually opens, and still try all of them.

Scope (read this first)

This PR fixes the P1 on the ssh2 transport — the path SshConnection takes for every target that is not routed to system OpenSSH. It does not close the P1 on the system-SSH transport: a wildcard Host * / ProxyCommand|ProxyJump sets resolved.proxyCommand for every alias, so shouldUseSystemSshTransport still returns true for an evidence-less config-backed target and buildSshArgs still dials configHost verbatim (no -l, no -p, no -o Hostname=). That half is tracked in #11746 with a proposed direction and the test matrix it needs; it is deliberately not attempted here because the one-line gate would move every wildcard-proxy user onto ssh2 wholesale.

Summary

  • Root cause: ssh -G <unknown-alias> exits 0 and prints a fully-populated default config (hostname = the alias, user = the local account, port 22, no proxy, default identity list). Since fix(ssh): preserve first config directive value #11297 every config-backed helper treated "resolved is non-null" as proof that a Host block matched.
  • New hasOpenSshHostBlockMatch (src/main/ssh/ssh-g-host-block-match.ts:37) requires positive evidence of a match — a hostname that is not just the echoed alias, a non-22 port, a proxy directive, or a user that is not the local account — and only then hands OpenSSH authority.
  • Gated the config-backed branches on it: buildConnectConfig user (src/main/ssh/ssh-connection-utils.ts:186), resolveEffectiveHost (:224), resolveEffectivePort (:234), resolveEffectiveProxy (:265, which otherwise ignored target.proxyCommand/target.jumpHost entirely), and the identity paths in src/main/ssh/ssh-auth-resolution.ts:92,102,179. When a block really matches, fix(ssh): preserve first config directive value #11297's first-directive-wins precedence is unchanged.
  • Same gate on the two remaining fix(ssh): preserve first config directive value #11297 sites in src/main/ssh/ssh-connection.ts: the GitHub restricted-shell probe's effective user (:88, where a vanished block made resolved.user the local account and rejected a stored username: 'git') and the proactive Kerberos probe (:641). The GSSAPI check keeps resolved.gssapiAuthentication === true winning either way, so fix(ssh): preserve first config directive value #11297's distro-wide /etc/ssh default pickup survives; the gate only stops a defaulted no from discarding a stored gssapiAuthentication: true and dropping a Kerberos-only host into key/password prompts.
  • configurePrivateKeyAuthentication now seeds config.privateKey with the first parseable candidate (src/main/ssh/ssh-private-key-authentication.ts:39-56); ssh2 parses that value eagerly in Client.connect (node_modules/ssh2/lib/client.js:258-261) and throws before any authHandler runs, so an encrypted first identity killed the multi-key fallback that fix(ssh): preserve first config directive value #11297 added.
  • The encrypted key stays in the authHandler queue (ssh2 skips unparseable queue entries rather than throwing), and an encrypted-only list still falls back to keys[0], so findEncryptedPrivateKeyPath and the passphrase prompt at src/main/ssh/ssh-connection.ts:786-800 keep working.

Regression source

Introduced by #11297 (5fe3aaf) — "fix(ssh): preserve first config directive value", which began trusting ssh -G output unconditionally.

Test plan

  • New src/main/ssh/ssh-g-host-block-match.test.ts (10 tests), 2 new cases in src/main/ssh/ssh-connection.test.ts for the two ssh-connection.ts sites, and 3 new cases in src/main/ssh/ssh-multi-key-authentication.test.ts.
  • Verified failing on unfixed code (source files reverted, tests kept):
    • "keeps stored endpoint fields when the alias no longer has a Host block" → expected { host: 'prod', port: 22, … } to deeply equal { host: '10.0.0.5', port: 2222, … }; the received privateKey was ~/.ssh/id_rsa instead of /keys/prod and proxy was undefined instead of the stored bastion jump host.
    • "keeps the stored ProxyCommand when the alias resolves to bare defaults" → expected undefined to deeply equal { kind: 'proxy-command', command: 'cf access ssh %h' }.
    • "seeds ssh2 with the first parseable identity so an encrypted one keeps the fallback" → config.privateKey was /keys/encrypted-first instead of /keys/valid-second.
    • "keeps the stored GSSAPI flag when the alias no longer has a Host block" → the gssapiOnly system-SSH probe was never spawned (Number of calls: 0).
    • "keeps the stored git username when the GitHub alias no longer has a Host block" → System SSH probe failed (exit 1), because the restricted-shell probe read the local account instead of the stored git.
    • "ignores the resolved user when the local account cannot be determined" → config.username was whoever instead of the stored deploy.
  • All pass after the fix, along with: every src/main/ssh test (1089 passed / 10 skipped), the whole src/main suite (17594 passed / 49 skipped), npx oxlint src/main/ssh/, npx oxfmt --check src/main/ssh/, and tsc --noEmit -p config/tsconfig.node.json.
  • Review round 2 — differential-probe mask and baseline-probe cost:
    • The mask kept _ in both word-boundary classes, so Host * / IdentityFile ~/.ssh/id_%h and Host * / HostName %h_internal.example.com produced an unmasked alias on one side and an unmasked probe token on the other → hostBlockMatch: true for an alias with no block. Verified against OpenSSH 10.2 that HostName %h_internal.example.com really does expand per-alias on both probes. Fixed by dropping _ from the boundary classes; 4 new parametrised cases (_-prefixed, _-suffixed, --separated, .-separated) plus a HostName case and a "still detects an alias-specific IdentityFile containing the alias name" guard against over-masking, all on production-shaped ssh -G bodies with the default identityfile lines. The two _ cases and the HostName case fail on the pre-fix source.
    • Both resolveWithSshG call sites asked for hostBlockEvidence: true unconditionally, but hasOpenSshHostBlockMatch discards the verdict when isOpenSshConfigBackedTarget is false — so every source: 'manual' target and every runtime-owned target (SshConnectionStore.upsertRuntimeOwnedTarget sets source: 'manual') paid for a second ssh -G, which re-runs the user's Match exec matchers, on every connect attempt and every connectViaSystemSsh. Now gated on isOpenSshConfigBackedTarget(this.target); 3 new cases in ssh-connection.test.ts (manual, runtime-owned/no-alias, manual connectViaSystemSsh) plus an explicit hostBlockEvidence: false execFile-count case, all failing on the pre-fix source.
    • Re-ran: every src/main/ssh test (1114 passed / 10 skipped), the whole src/main suite (17619 passed / 49 skipped), npx oxlint on the changed files, npx oxfmt --check src/main/ssh/, tsc --noEmit -p config/tsconfig.node.json.
  • Coverage includes the still-matching cases: a live Host block applies resolved host/port/user/proxy and keeps fix(ssh): preserve first config directive value #11297's first-IdentityFile precedence; a User git directive on github.com counts as a match even though HostName echoes the alias; a non-default Port likewise; manual targets are untouched; and an encrypted-only identity still records the passphrase key path.

Deliberately out of scope

  • System-SSH transport half of the P1 → [P1 follow-up] ssh: wildcard ProxyCommand/ProxyJump still dials a bare alias on the system-SSH transport #11746. shouldUseSystemSshTransport (src/main/ssh/ssh-connection.ts) never consults hasOpenSshHostBlockMatch, and buildSshArgs (src/main/ssh/system-ssh-args.ts:79-83) dials configHost verbatim on that branch. Executed against the branch: target {source:'ssh-config', configHost:'prod', host:'10.0.0.5', port:2222, username:'deploy'} + resolved {hostname:'prod', user:'ops', port:22, proxyCommand:'nc -X connect …', hostBlockMatch:false} → transport true, args [… ,"--","prod"] with no -l deploy / -p 2222 / -o Hostname=10.0.0.5. (An earlier revision of this section claimed this case fell through to ssh2 and was "functionally equivalent" — that was wrong: resolved.proxyCommand from Host * keeps it on the system transport, so resolveEffectiveProxy is never reached.) shouldUseSystemSshTransport now carries a docstring pointing at [P1 follow-up] ssh: wildcard ProxyCommand/ProxyJump still dials a bare alias on the system-SSH transport #11746.
  • Residual differential-probe inaccuracies are documented in the resolveWithSshG docstring rather than fixed: false true when the alias name appears as a bare token in a wildcard directive, when a negated pattern (Host !prod *) excludes it, or when CanonicalizeHostname rewrites only one side; false false when a real block only restates wildcard/global values or holds directives the signature does not compare. All are no worse than the unconditional true this replaced.
  • A failed baseline probe still leaves the verdict unset and falls back to the effective-config heuristic. Treating it as "no evidence → keep the stored snapshot" would flip behaviour for every user whose ssh -G baseline fails today, so it is documented, not changed.

Found by the production release scan of v1.4.163-rc.0..origin/main.

Made with Orca 🐋

…he first identity

`ssh -G <alias>` exits 0 for an alias with no Host block and prints a fully
populated default config, so a non-null resolution was treated as fresh
OpenSSH authority and replaced the stored host/port/user/proxy/identity.

Also seed ssh2 with the first parseable identity: Client.connect parses
config.privateKey eagerly, so an encrypted first key aborted the connect
before the multi-key authHandler could try the rest.

Co-authored-by: Orca <[email protected]>
@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes two bugs introduced by #11297 in the ssh2 transport path: (1) ssh -G <alias> exits 0 with plausible-looking defaults even when no Host block matched, causing stored target fields to be silently overwritten; and (2) seeding ssh2's config.privateKey with the first key regardless of parseability caused encrypted keys to abort the connection before other candidates were tried.

  • Adds hasOpenSshHostBlockMatch requiring positive evidence (hostname rewrite, non-22 port, proxy directive, or non-local user) before trusting ssh -G output; gates all five affected call sites on this predicate.
  • Fixes configurePrivateKeyAuthentication to select the first parseable key via selectEagerPrivateKey, falling back to keys[0] only for encrypted-only lists so the passphrase prompt still fires.
  • Adds 15+ new tests covering stored-fields-win, still-matching, encrypted-first-key, GSSAPI preservation, and GitHub probe fix paths.

Confidence Score: 5/5

Safe to merge; both root causes are correctly addressed and all changed call sites have matching test coverage.

The heuristic in hasOpenSshHostBlockMatch is conservative — false negatives keep stored fields, false positives apply fresh config. The selectEagerPrivateKey fallback to keys[0] preserves the passphrase prompt for encrypted-only lists. The test plan explicitly verified each fixed failure against unfixed source. Known limitations around wildcard-proxy false positives and the system-SSH transport half are documented and tracked in #11746.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/ssh/ssh-g-host-block-match.ts New predicate detecting genuine Host-block matches; logic is sound with well-documented limitations around wildcards and CanonicalizeHostname.
src/main/ssh/ssh-private-key-authentication.ts selectEagerPrivateKey correctly finds the first parseable key; encrypted-only fallback to keys[0] preserves the passphrase prompt path.
src/main/ssh/ssh-auth-resolution.ts Three isOpenSshConfigBackedTarget guards replaced with hasOpenSshHostBlockMatch; resolvePrivateKeyPaths and resolveIdentityFilePaths remain identical bodies (pre-existing, noted in prior thread).
src/main/ssh/ssh-connection-utils.ts buildConnectConfig, resolveEffectiveHost/Port/Proxy all gated on hasOpenSshHostBlockMatch; stored fields win in no-match branch.
src/main/ssh/ssh-connection.ts GitHub restricted-shell and GSSAPI probes gated correctly; distro-wide GSSAPI pickup preserved via isOpenSshConfigBackedTarget secondary condition.
src/main/ssh/ssh-g-host-block-match.test.ts 10 tests covering all four heuristic signals, manual-target bypass, and local-account-unknown path.
src/main/ssh/ssh-connection.test.ts Three new integration tests covering git-username and GSSAPI flag preservation when alias block is gone.
src/main/ssh/ssh-multi-key-authentication.test.ts Three new cases: encrypted-first skipped, all-encrypted fallback to keys[0], single-encrypted-only.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[hasOpenSshHostBlockMatch called] --> B{isOpenSshConfigBackedTarget\nAND resolved non-null?}
    B -->|No| C[return false - stored fields win]
    B -->|Yes| D{resolved.hostname empty?}
    D -->|Yes| E[return true - trust resolved]
    D -->|No| F{hostname != configHost/label?}
    F -->|Yes| E
    F -->|No| G{port set AND port != 22?}
    G -->|Yes| E
    G -->|No| H{proxyCommand or proxyJump?}
    H -->|Yes| E
    H -->|No| I{localAccountName resolvable?}
    I -->|No| C
    I -->|Yes| J{user non-empty AND != local?}
    J -->|Yes| E
    J -->|No| C
Loading

Reviews (8): Last reviewed commit: "fix(ssh): gate the remaining #11297 conf..." | Re-trigger Greptile

Comment thread src/main/ssh/ssh-g-host-block-match.ts Resolved
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The SSH resolution flow now detects applied OpenSSH Host blocks before using resolved host, user, port, proxy, and identity values. Tests cover matched and unmatched aliases, directives, and manual targets. Private-key authentication now parses candidate identities, selects the first usable key for SSH2 configuration, preserves authentication order, and handles encrypted-only identity lists.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies both primary fixes: preserving stored SSH target fields and selecting a usable identity for ssh2 authentication.
Description check ✅ Passed The description is detailed and on-topic, with strong testing and scope coverage, but it omits explicit Screenshots, Security Audit, and cross-platform AI review confirmations.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/ssh/ssh-auth-resolution.ts (1)

101-109: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Consolidate identical resolvePrivateKeyPaths and resolveIdentityFilePaths.

resolvePrivateKeyPaths (Line 101) and resolveIdentityFilePaths (Line 178) now have identical bodies. This PR had to apply the same hasOpenSshHostBlockMatch change to both. A future change risks updating one and missing the other.

Extract one shared helper and let both functions delegate to it.

♻️ Proposed consolidation
+function resolveIdentityCandidatePaths(target: SshTarget, resolved: SshResolvedConfig | null): string[] {
+  if (hasOpenSshHostBlockMatch(target, resolved) && resolved) {
+    return resolved.identityFile
+  }
+  if (target.identityFile) {
+    return [target.identityFile]
+  }
+  return resolved?.identityFile ?? []
+}
+
-function resolvePrivateKeyPaths(target: SshTarget, resolved: SshResolvedConfig | null): string[] {
-  if (hasOpenSshHostBlockMatch(target, resolved) && resolved) {
-    return resolved.identityFile
-  }
-  if (target.identityFile) {
-    return [target.identityFile]
-  }
-  return resolved?.identityFile ?? []
-}
+function resolvePrivateKeyPaths(target: SshTarget, resolved: SshResolvedConfig | null): string[] {
+  return resolveIdentityCandidatePaths(target, resolved)
+}

...

-function resolveIdentityFilePaths(target: SshTarget, resolved: SshResolvedConfig | null): string[] {
-  if (hasOpenSshHostBlockMatch(target, resolved) && resolved) {
-    return resolved.identityFile
-  }
-  if (target.identityFile) {
-    return [target.identityFile]
-  }
-  return resolved?.identityFile ?? []
-}
+function resolveIdentityFilePaths(target: SshTarget, resolved: SshResolvedConfig | null): string[] {
+  return resolveIdentityCandidatePaths(target, resolved)
+}

Also applies to: 178-186

src/main/ssh/ssh-connection-utils.ts (1)

223-231: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Gate stale-alias defaults back through hasOpenSshHostBlockMatch.

When ssh -G returns defaults with hostname === alias, shouldUseResolvedEndpoint still accepts target.host === '', target.configHost, or target.label, so it can override a stored target to alias even without a matching Host block. Keep the Host-block guard on this branch.

🧹 Nitpick comments (2)
src/main/ssh/ssh-g-host-block-match.ts (1)

6-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: export DEFAULT_SSH_PORT for reuse.

ssh-connection-utils.ts hardcodes the literal 22 in resolveEffectivePort in two places. Export this constant and import it there. This avoids two independent sources of truth for the default SSH port.

src/main/ssh/ssh-g-host-block-match.test.ts (1)

38-170: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the empty-hostname fallback in hasOpenSshHostBlockMatch.

No test exercises the branch in ssh-g-host-block-match.ts where resolved.hostname is empty (Line 48 comment: an empty hostname means the resolution never went through ssh -G, so it's treated as authoritative). Add a case with resolved.hostname unset to confirm this fallback returns a match.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9d32d656-75e0-4f36-9d37-962f37350049

📥 Commits

Reviewing files that changed from the base of the PR and between aa6f945 and 727f74b.

📒 Files selected for processing (6)
  • src/main/ssh/ssh-auth-resolution.ts
  • src/main/ssh/ssh-connection-utils.ts
  • src/main/ssh/ssh-g-host-block-match.test.ts
  • src/main/ssh/ssh-g-host-block-match.ts
  • src/main/ssh/ssh-multi-key-authentication.test.ts
  • src/main/ssh/ssh-private-key-authentication.ts

nwparker and others added 2 commits July 30, 2026 23:21
…lockMatch

The port case fixture stored port 22, so resolveEffectivePort's pre-existing
`configHost && port === 22` branch returned the resolved port whether or not the
predicate's port rule existed; the proxy rule had no test at all. Both rules can
now be deleted only at the cost of a failing test, as can the HostName rule.

Co-authored-by: Orca <[email protected]>
…ock evidence

Why: `ssh -G <vanished-alias>` still exits 0 with defaults, so the GitHub
restricted-shell probe read the local account instead of a stored `git`
username, and a defaulted `gssapiauthentication no` discarded a stored
Kerberos flag. A resolved `yes` still wins so distro-wide defaults keep
working. Also treats an undeterminable local account as no evidence, and
matches ssh2's first-entry rule for the eager private key.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 89a9bbea-8a5b-4f19-82ae-2005f70b405b

📥 Commits

Reviewing files that changed from the base of the PR and between ee293b9 and fcf4fd3.

📒 Files selected for processing (6)
  • src/main/ssh/ssh-connection.test.ts
  • src/main/ssh/ssh-connection.ts
  • src/main/ssh/ssh-g-host-block-match.test.ts
  • src/main/ssh/ssh-g-host-block-match.ts
  • src/main/ssh/ssh-multi-key-authentication.test.ts
  • src/main/ssh/ssh-private-key-authentication.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/ssh/ssh-g-host-block-match.test.ts
  • src/main/ssh/ssh-multi-key-authentication.test.ts
  • src/main/ssh/ssh-private-key-authentication.ts
  • src/main/ssh/ssh-g-host-block-match.ts

Comment thread src/main/ssh/ssh-connection.ts Resolved
@nwparker

Copy link
Copy Markdown
Contributor Author

Item 1 (P1) — fixed: hasOpenSshHostBlockMatch now rests on a differential ssh -G probe

The feedback was right, and the docstring admitted it: the heuristic read the effective config, so a Host * block supplying User (or Port, or ProxyCommand) made every alias look matched and the original P1 fired unchanged.

resolveWithSshG(alias, { hostBlockEvidence: true }) now resolves the alias and a random 32-hex alias that no block can name, in parallel, and diffs the two. Wildcard/Match-less/system-wide directives apply to both and cancel out; anything that differs came from a block that named this alias. The verdict rides on the resolution as hostBlockMatch, and hasOpenSshHostBlockMatch returns it when present.

Details worth knowing:

  • The probe alias is dot- and dash-free so Host *.corp / Host prod-* cannot single it out, while a bare Host * still matches it (which is the point).
  • ssh -G echoes the probed alias into hostname and expands %h/%n into wildcard values, so each side is masked with a word-boundary-anchored replacement of its own probed alias before comparison. That makes Host * / HostName %h.internal correctly read as no evidence (test included).
  • Only the fields Orca actually applies are compared (hostname/user/port/identityfile/identityagent/identitiesonly/forwardagent/gssapi/proxy*). Control* is excluded deliberately: a block differing only in multiplexing plumbing should not take over the stored endpoint.
  • A pattern block that genuinely matches the alias (Host prod-*) is still evidence — the probe alias does not match it. This is strictly better than a literal-parse approach, which is why I did not go the ssh-config-parser.ts route (Include + Match + negation make that hard to get right).
  • If the baseline probe fails, the verdict is left undefined and the old heuristics still run, so no environment loses today's behaviour.
  • Cost: one extra ssh -G per connect attempt, issued in parallel with the existing one, so no added latency. Not cached — a cache would go stale the moment someone edits ~/.ssh/config, and staleness here is exactly the failure mode we are fixing.

#11297's first-directive-wins precedence is preserved and now has an end-to-end test that drives it through the real probe (applies fresh OpenSSH values when a block still names the alias asserts privateKey === /keys/current-first).

Regression tests (all fail on the pre-fix commit): src/main/ssh/ssh-g-host-block-match.test.ts → wildcard-only User, wildcard HostName %h.internal, alias block still named, alias block adding only an IdentityFile, plus guards for the failed-baseline and no-evidence-requested paths.

Item 1b — refuted: localAccountName() does not fall back to ''

The claim is that with USER/LOGNAME/USERNAME unset and userInfo() throwing, localAccountName() returns '' and the final check degenerates to user !== ''. It returns null in both of those cases:

  • src/main/ssh/ssh-g-host-block-match.ts:22 — return normalize(userInfo().username) || null (an empty username becomes null, not '')
  • src/main/ssh/ssh-g-host-block-match.ts:24 — catch { return null }

and :67 short-circuits on localAccount !== null. src/main/ssh/ssh-g-host-block-match.test.ts:193 (ignores the resolved user when the local account cannot be determined) already pins exactly that path — the file's vi.mock('os') omits userInfo, so the call throws, and the stored deploy/10.0.0.5 still win. The underlying concern (an unknown local account drops the user signal) was real; the differential probe removes the dependency on the local account entirely.

Item 2 — real bug, but fixed differently than proposed

The reported symptom is real: isGitHubRestrictedShellProbeSuccess used resolvedConfig.hostname as the only host candidate. The proposed gate (hasOpenSshHostBlockMatch(...) ? resolvedConfig.hostname : [target.host, target.configHost]) would regress the case this PR exists to fix, so I did not take it:

For a config-backed alias, system SSH dials target.configHost (src/main/ssh/system-ssh-args.ts:79-83), not target.host. If the alias's Host block was removed, ssh gh-work really does dial the machine named gh-work — the stored github.com is not who answered. Falling back to target.host there would accept a GitHub restricted-shell banner from an arbitrary host, which is the same class of silent-override this PR removes. src/main/ssh/ssh-connection.test.ts:1319 (rejects non-GitHub SSH probes with GitHub invalid-command text) fails under the proposed diff.

The actual defect is a host-string mismatch: ssh -G runs against configHost || label (ssh-connection.ts:633, :1307) while system SSH dials configHost || host. When configHost is absent, the resolution describes a display label (GitHub (work)) that nothing dialed, so it must not be a host candidate. Fix at ssh-connection.ts:103:

const resolvedHost = target.configHost ? resolvedConfig?.hostname?.trim() : undefined

Regression test: accepts GitHub restricted-shell SSH probes when only a display label resolved (manual target, label: 'GitHub (work)', host: 'github.com', username: 'git') — fails pre-fix, and the existing gitlab.com rejection test still passes untouched.

Deliberately left

  • resolveExplicitIdentityAgent (ssh-auth-resolution.ts:72) still keys off isOpenSshConfigBackedTarget, so a wildcard IdentityAgent keeps applying to an unmatched alias. That is intentional — an agent socket is not an endpoint override and 1Password/gpg-agent users rely on the Host * form.
  • System SSH still dials the stale configHost for a removed alias (system-ssh-args.ts:79). Out of scope here; the probe validator above now refuses to call that a GitHub success.
  • Residual limitation, now much narrower: CanonicalizeHostname yes that successfully canonicalizes the alias but not the probe alias still reads as evidence. In that case OpenSSH really would dial the canonicalized name, so deferring to it is defensible.

Verification

  • src/main/ssh — 75 files, 1104 tests, green.
  • src/main + src/shared — 1696 files, 21190 tests, green.
  • npx oxlint src/main/ssh, npx oxfmt --check, npx tsc --noEmit -p config/tsconfig.node.json — clean. No lint rule disabled, no existing assertion weakened; the only pre-existing assertion I touched is ssh-connection.test.ts:551, tightened to toHaveBeenCalledWith('ssh-alias', { hostBlockEvidence: true }).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/ssh/ssh-g-config-resolution.ts (1)

36-64: 🧹 Nitpick | 🔵 Trivial

Consider caching the baseline probe across reconnect attempts.

resolveWithSshG spawns two ssh -G processes per call. attemptConnect and connectViaSystemSsh invoke this on every connection attempt, including automatic reconnects. For hosts with frequent disconnects (flaky networks, GSSAPI retries), this doubles subprocess overhead on each attempt. The baseline probe result depends only on global/wildcard SSH configuration, not on the target alias, so a short-lived cache of the baseline signature (invalidated on ssh_config mtime change, or scoped to a single reconnect loop) could reduce redundant spawns without affecting correctness.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: febf25d7-8e73-4882-b64b-33955b0d597c

📥 Commits

Reviewing files that changed from the base of the PR and between fcf4fd3 and e2bc0cb.

📒 Files selected for processing (5)
  • src/main/ssh/ssh-connection.test.ts
  • src/main/ssh/ssh-connection.ts
  • src/main/ssh/ssh-g-config-resolution.ts
  • src/main/ssh/ssh-g-host-block-match.test.ts
  • src/main/ssh/ssh-g-host-block-match.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/ssh/ssh-g-host-block-match.ts
  • src/main/ssh/ssh-connection.test.ts

Comment thread src/main/ssh/ssh-connection.ts Outdated
Comment on lines +103 to +106
// Why: `ssh -G` ran against `configHost || label` while system SSH dials
// `configHost || host`, so the resolved hostname only describes the endpoint that
// answered when configHost is set; otherwise it just resolved a display label.
const resolvedHost = target.configHost ? resolvedConfig?.hostname?.trim() : undefined

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
fd 'ssh-connection.test.ts' src/main/ssh --exec rg -n -B3 -A15 "restricted.?shell|isGitHubRestrictedShellProbeSuccess|ORCA-SYSTEM-SSH-OK" {}

Repository: stablyai/orca

Length of output: 19538


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate files =="
fd 'ssh-connection\.ts|ssh-connection\.test\.ts' src/main/ssh

echo "== outline main =="
ast-grep outline src/main/ssh/ssh-connection.ts --view compact || true

echo "== relevant main lines 1-140 =="
sed -n '1,140p' src/main/ssh/ssh-connection.ts

echo "== relevant tests around GitHub probes =="
sed -n '1150,1340p' src/main/ssh/ssh-connection.test.ts

Repository: stablyai/orca

Length of output: 12188


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== find host block match parser code/tests =="
fd 'ssh-g-host-block-match\.ts|ssh-g-host-block-match\.test\.ts|ssh-custom-config-parser.*|ssh-.*custom.*|^.*ssh.*parser.*' src/main/ssh src/main/shared -x sh -c 'echo "--- $1"; sed -n "1,220p" "$1"' sh {}

echo "== search hasOpenSshHostBlockMatch usages =="
rg -n "hasOpenSshHostBlockMatch|resolveWithSshG|resolvedConfig" src/main/ssh src/main/shared -g '*.ts' -g '!*.test.ts'

Repository: stablyai/orca

Length of output: 28732


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== search for OpenSSH HostName default behavior in docs/tests =="
rg -n "Hostname|HostName|ssh -G|configHost|hostBlockEvidence|stale|no matching|no Host|Host block" src/main/ssh src/main/shared README.md package.json -g '*.ts' -g '*.md'

echo "== inspect parser-specific host block evidence files =="
git ls-files 'src/main/ssh/*config*.ts' 'src/main/ssh/*host*.ts' 'src/main/ssh/*parser*.ts' | sort

Repository: stablyai/orca

Length of output: 50369


Gate resolvedHost on hasOpenSshHostBlockMatch.

When configHost is a stale alias with no matching Host block, ssh -G can return the alias back as hostname. That false resolvedHost replaces [target.host, target.configHost] with [configHost] and can skip checking target.host. Use the same host-block match predicate already used for effectiveUser.

Proposed fix
-  const resolvedHost = target.configHost ? resolvedConfig?.hostname?.trim() : undefined
+  const resolvedHost = hasOpenSshHostBlockMatch(target, resolvedConfig)
+    ? resolvedConfig?.hostname?.trim()
+    : undefined
   const hostCandidates = resolvedHost ? [resolvedHost] : [target.host, target.configHost]

@nwparker

Copy link
Copy Markdown
Contributor Author

Review round addressed in c694fe269a. Summary of what changed, what I refuted, and what I deliberately left.


1. Baseline probe running for targets that can never use it — valid, fixed

Confirmed. hasOpenSshHostBlockMatch returns false before reading hostBlockMatch whenever isOpenSshConfigBackedTarget(target) is false (src/main/ssh/ssh-g-host-block-match.ts:54), and hostBlockMatch has no other consumer. SshConnectionStore.upsertRuntimeOwnedTarget sets source: 'manual' (src/main/ssh/ssh-connection-store.ts:64-67), so runtime-owned targets were paying for it too. Both call sites now pass hostBlockEvidence: isOpenSshConfigBackedTarget(this.target), with a comment naming Match exec as the reason.

Tests (all fail on the pre-fix source, verified by reverting the two source files and re-running):

  • skips the host-block baseline probe for manual targets
  • skips the host-block baseline probe for runtime-owned targets without an alias
  • skips the host-block baseline probe for manual direct system SSH connections
  • skips the baseline probe when evidence was explicitly declined (asserts execFile is called once)

The existing resolves OpenSSH config using configHost when present still asserts { hostBlockEvidence: true }, so the config-backed side is pinned in both directions.

2. P1 still reproduces on the system-SSH transport — valid, deliberately not fixed; PR scope corrected instead

Reproduced exactly as described. With the stated target and resolved config, shouldUseSystemSshTransport returns true and buildSshArgs produces […,"--","prod"] — no -l deploy, no -p 2222, no -o Hostname=10.0.0.5.

I took resolution (a). The PR body now opens with an explicit Scope section stating the fix covers the ssh2 transport only, the old out-of-scope bullet that claimed this case "falls through to ssh2, functionally equivalent" is corrected (it is wrong — resolved.proxyCommand from Host * keeps it on the system transport, so resolveEffectiveProxy is never reached), and the system-SSH half is filed as #11746 with the proposed -o Hostname=/-p/-l direction and the test matrix it needs. shouldUseSystemSshTransport also carries a docstring in code so the gap is discoverable there.

I did not attempt (b) in this PR: pinning the stored endpoint changes what a wildcard ProxyCommand's %h sees, and buildSshArgs is on the path for the GitHub restricted-shell probe, relay deploy, and the sftp system fallbacks. That is a bigger blast radius than the bug, and it needs its own matrix rather than a rider on this one.

3. Word-boundary hole in the differential mask — valid, fixed

Confirmed and fixed by dropping _ from both boundary classes (src/main/ssh/ssh-g-config-resolution.ts).

One correction to the report, in the fix's favour: on OpenSSH 10.2 ssh -G does not percent-expand IdentityFile/ProxyCommand in its output (only HostName), so the id_%h variant is version-dependent. The bug is reachable on a current binary through HostName — verified with the real binary:

$ ssh -G -F cfg -- prod              # Host * / HostName %h_internal.example.com
hostname prod_internal.example.com
$ ssh -G -F cfg -- 34d181df5be3…
hostname 34d181df5be3…_internal.example.com

Neither side was masked pre-fix, so the signatures differed and the verdict came back true for an alias with no block.

New tests, on production-shaped ssh -G bodies that include the default identityfile lines: four parametrised IdentityFile separator cases (_-prefixed, _-suffixed, -, .), the HostName %h_internal… case, and still detects an alias-specific IdentityFile that contains the alias name as an over-masking guard. The two _ IdentityFile cases and the HostName case fail on pre-fix code; the -/. controls pass on both.

Suggestions

  • Residual false positives from alias-name masking, negated wildcards, CanonicalizeHostname — agreed, and I reproduced the negated case against the real binary (Host !prod * + User ops/Port 2299 → hostBlockMatch: true for prod). All three, plus the false-false class (a real block that only restates wildcard values, or holds only uncompared directives) are now named in the resolveWithSshG docstring and in the PR body. I did not change the masking strategy: masking only inside hostname, or substituting the baseline value instead of blanking, both change the verdict for configs that work today, and none of these residuals is worse than the unconditional true they replaced.
  • Failed baseline falling back to the heuristic — documented in the docstring and the PR body, not changed. Flipping a failed baseline to "no evidence → keep the stored snapshot" would change behaviour for every user whose baseline probe fails today, in the safe-for-one-case/unsafe-for-another direction, and there is no existing signal that distinguishes them.
  • resolvedHost at ssh-connection.ts:103 is a no-op for producible targets — accurate, and thanks for checking the store. addTarget and upsertRuntimeOwnedTarget both default configHost to target.host, so target.configHost is always truthy in practice and that item is better described as refuted than fixed; the PR notes overstated it. I left the code and its test in place — the expression is defensive rather than wrong, and deleting a passing assertion to tidy the narrative is the wrong trade — but the record here is the correction.
  • && resolved being dead at four sites — left as-is; it is only there for TypeScript narrowing and removing it would need a non-null assertion instead.

Verification

Every src/main/ssh test (1114 passed / 10 skipped) and the whole src/main suite (17619 passed / 49 skipped), plus npx oxlint on the changed files, npx oxfmt --check src/main/ssh/, and tsc --noEmit -p config/tsconfig.node.json. No existing assertion was weakened or removed.

@nwparker

Copy link
Copy Markdown
Contributor Author

Thanks — both blocking items verified against the branch. Pushed 9db4d723ef.

1. P1 under wildcards narrower than Host * — valid, fixed properly (not just documented)

Confirmed exactly as reported: createUnmatchableProbeHost() returned a free-standing 32-char hex token, which only a bare Host * can match, so Host *.internal / Host prod-* / Host i-* / Host 10.* applied to the alias and not to the baseline, showed up as a difference, and were reported as alias-specific evidence.

Rather than only documenting it, I took the structure-preserving-nonce route you suggested. createBaselineProbeHost(host) now splices the nonce in as a new label after the alias's first ./-:

  • prod.internal → prod.<hex>.internal
  • prod.corp.example.com → prod.<hex>.corp.example.com
  • i-0abc123def → i-<hex>-0abc123def
  • 10.0.0.5 → 10.<hex>.0.0.5
  • separator-free alias (prod) → prod-<hex> (appended; cancels prefix globs only)

Keeping both the alias's prefix and its suffix intact means one probe covers prefix, infix and suffix globs, while a literal Host prod.internal still cannot name it. Probe count is unchanged (still one baseline), so this adds no latency on top of what you already flagged.

Verified against real ssh -G -F <cfg> on OpenSSH_10.2p1, driving the branch's actual resolveWithSshG (I mocked only execFile to inject -F, so parse/signature/mask ran verbatim). 28 configs; all 5 of your reported cases now return false, and every alias-specific shape still returns true:

config alias before after
Host *.internal / User ops prod.internal true ❌ false ✅
Host *.corp.example.com / User ops + ProxyJump bastion prod.corp.example.com true ❌ false ✅
Host prod-* / User ops prod-web true ❌ false ✅
Host i-* mi-* / ProxyCommand aws ssm start-session --target %h i-0abc123def true ❌ false ✅
Host 10.* / User ops 10.0.0.5 true ❌ false ✅
Host *.internal + unrelated Host other.internal (your db.internal repro) db.internal true ❌ false ✅
Host prod.internal / HostName|Port|User|IdentityFile|ForwardAgent (5 cases) prod.internal true true ✅
Match host prod.internal / User deploy prod.internal true true ✅
Host *.internal + real Host prod.internal block prod.internal true true ✅
Host * / Host * !nope / %h and %h_… expansions — false false ✅
Host github.com / User git github.com true true ✅
Host ????.internal / User ops prod.internal true true (residual)
Host *dev / User ops webdev true true (residual)

Two verdicts intentionally changed beyond your list, both toward false (the safe direction — caller falls back to the stored snapshot):

  • Host pr* / alias prod, and Host prod.* / alias prod.internal. These are wildcards that don't name the alias, so false matches the documented contract ("a block that names this alias"). The parser never imports wildcard patterns (ssh-config-parser.ts:51-52), so a config-backed target can only reach a wildcard-is-my-only-block state after a hand edit; it then keeps the values it was imported with instead of the bare-alias defaults. Called out in the docstring.

Residual list at ssh-g-config-resolution.ts:46-63 rewritten: the inverted ./- rationale is gone, the surviving true residuals are now fixed-width patterns (Host ????.internal) and suffix globs over a separator-free alias (Host *dev / webdev), and the new false residual (a glob wide enough to cover the probe) is listed.

Pinned with 7 stubbed tests in ssh-g-host-block-match.test.ts — 6 parameterised wildcard shapes plus one that a real block underneath a suffix wildcard is still detected. All 6 fail on the pre-fix probe and pass after.

2. Item 2 ships as a no-op — valid, resolved by dropping the branch

Confirmed your trace: normalizeSshTarget (persistence.ts:1187-1189) is applied on every store read/write including getSshTarget (persistence.ts:6354), SshConnectionStore.addTarget/upsertRuntimeOwnedTarget default it, and the only new SshConnection(...) (ssh-connection-manager.ts:45) is fed from sshStore.getTarget(...). target.configHost is therefore always set, the undefined branch was unreachable, and the why-comment described a state that cannot occur.

Chose your first option: reverted resolvedHost to resolvedConfig?.hostname?.trim() (byte-identical production behaviour, minus the dead ternary) and replaced the synthetic manual + no-configHost test with one exercising the state a user can reach — a config-backed alias whose Host block is gone resolves to itself (github-work), so the stored github.com must not vouch for whoever answered, and the restricted-shell probe is rejected. The comment now records that as the reason the fallback stays ungated, i.e. why CodeRabbit's proposed hasOpenSshHostBlockMatch gate is the wrong fix (system-ssh-args.ts:79 dials configHost || host).

I recorded Item 2 as refuted-with-a-coverage-fix rather than silently keeping dead code. Happy to restore the gate as an explicit defensive assert if you'd rather have belt-and-braces there.

Left alone (deliberately)

  • Baseline latency / Promise.all. Not touched. A shorter baseline budget is a real improvement but changes the failure ratio between the differential verdict and the effective-config heuristic on slow Match exec hosts, which is exactly the fallback path this PR is trying to stop relying on. That deserves its own PR with its own tests rather than riding along here.
  • GSSAPI probe widening and selectEagerPrivateKey — your analysis matches mine; intentional and already pinned.
  • shouldUseSystemSshTransport still ungated, with the existing Known gap docstring explaining why gating it is not a safe one-liner.

Verification

  • src/main/ssh: 75 files / 1121 passed, 1 skipped
  • src/relay + src/main/persistence + renderer settings: 233 files / 2394 passed
  • src/main/github + src/main/ipc: 203 files / 3168 passed, 1 skipped
  • npx oxlint src/main/ssh, oxfmt --check, npx tsc --noEmit -p config/tsconfig.node.json — clean

No existing assertion was weakened or deleted. The one removed test (accepts GitHub restricted-shell SSH probes when only a display label resolved) was added by this PR two commits ago and asserted a state persistence prevents; it is replaced by a stricter assertion on a reachable state.

@nwparker
nwparker force-pushed the nwparker/p1-ssh-config-resolution-regressions branch from 9db4d72 to 727f74b Compare July 31, 2026 10:11
@nwparker

Copy link
Copy Markdown
Contributor Author

Remediation backed out — branch reset to 727f74be69

I attempted to address the review feedback with an automated multi-agent pass. It introduced regressions, so I have reset this branch to its last independently-reviewed-clean commit (727f74be69) rather than ship them. Known, documented gaps are safer than unknown new ones.

What went wrong

The P1 is still not fixed. The differential probe spliced its nonce after the alias's first ./-, so for aws-prod-db the baseline was aws-<nonce>-prod-db. A wildcard Host aws-prod-* matches the alias but not the baseline, reads as alias-specific evidence, and the original override fires. Fleet-prefix naming (aws-prod-*, 192.168.*) is common. It also failed the other way — a sibling glob covering the spliced probe produced a false negative that discarded live ssh_config, a new regression against #11297. Separately it made every connect settle at max(primary, baseline) of two ssh -G calls (up to 5s, ~5x per connect) and re-ran the user's Match exec matchers against a fabricated hostname.

Item 2 (GitHub host validation) shipped as a comment-only no-op while being reported as fixed: const resolvedHost = resolvedConfig?.hostname?.trim() is byte-identical to main, and the test it claimed to be pinned by (accepts GitHub restricted-shell SSH probes when only a display label resolved) does not exist on the branch.

Still outstanding: both reported items. The P1 needs a config-parsing approach (src/main/ssh/ssh-config-parser.ts) that checks whether a block literally names the alias, handling Include and Match — probing cannot distinguish a wildcard from a real block, because ssh_config patterns match arbitrary substrings.

Recovery

The backed-out work is not lost — it is reachable by SHA at 9db4d723ef217adbd3b21ef82b59e67ee45a2469, should any individual piece be worth salvaging.

The reviewer feedback on this PR remains valid and unaddressed. Flagging rather than silently leaving it.

@nwparker

Copy link
Copy Markdown
Contributor Author

Correction: my earlier reset was too aggressive

The reset I posted earlier reset this branch to its first commit, not its last reviewed-clean one. The original fix round ran 07-30 21:55–23:41; the failed remediation began 07-31 01:18. I used the wrong boundary and dropped 1–2 legitimate commits that were part of the reviewed-clean PR.

The branch is now at the correct boundary — the last commit before remediation started. Apologies for the churn; the force-pushes were mine, not a tooling issue.

nwparker added a commit that referenced this pull request Sep 2, 2026
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.
nwparker added a commit that referenced this pull request Sep 2, 2026
…nd 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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…nd say where a clone failed (stablyai#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 stablyai#8622 and stablyai#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 stablyai#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 (stablyai#11746).

The signal stablyai#11746 assumed (hostBlockMatch, from the still-open stablyai#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 (stablyai#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
@OrcaWin
OrcaWin marked this pull request as draft October 27, 2026 09:43
@OrcaWin

OrcaWin commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-07-31T10:55:04Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants