Skip to content

fix(ssh): preserve first config directive value - #11297

Merged
Jinwoo-H merged 4 commits into
stablyai:mainfrom
hsusul:fix/ssh-config-first-value
Jul 30, 2026
Merged

Jinwoo-H merged 4 commits into
stablyai:mainfrom
hsusul:fix/ssh-config-first-value

Conversation

@hsusul

@hsusul hsusul commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Problem

Orca's SSH config parser replaced previously parsed values when a single-valued option appeared more than once. OpenSSH instead uses the first obtained value for each single-valued parameter, so Orca could display or use a different host, user, port, agent, or proxy route than ssh itself.

Deterministic reproduction with OpenSSH:

$ ssh -G -o HostName=first.example -o HostName=second.example \
    -o User=first-user -o User=second-user \
    -o Port=2201 -o Port=2202 demo
user first-user
hostname first.example
port 2201

Before this fix, the equivalent parseSshConfig input returned second.example.com, second-user, and 2202.

Root cause

parseSshConfig used unconditional assignment for most supported scalar directives. The existing GSSAPIAuthentication path already used first-value semantics, but the other single-valued paths did not.

Solution

Use nullish assignment for the supported single-valued directives:

  • HostName
  • Port
  • User
  • IdentityAgent
  • IdentitiesOnly
  • ProxyCommand
  • ProxyUseFdpass
  • ProxyJump

IdentityFile remains additive because OpenSSH permits multiple identity files.

Screenshots

Not applicable; this is SSH configuration parsing behavior with no visual change.

Testing checklist

  • Added a regression test covering repeated single-valued directives.
  • Confirmed the new test fails on the pre-fix implementation because the second values are returned.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-config-parser.test.ts — 48 passed after the fix.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/ssh-config-parser.test.ts src/main/ssh/ssh-config-parser-host-patterns.test.ts src/main/ssh/ssh-config-loader.test.ts src/main/ssh/ssh-config-loader-regression.test.ts — 4 files, 66 tests passed.
  • pnpm exec vitest run --config config/vitest.config.ts src/main/ssh — 61 files passed, 1 skipped; 975 tests passed, 11 skipped.
  • pnpm test — passed.
  • pnpm run typecheck — passed for node, CLI, and web projects.
  • pnpm run lint — passed, including 52 reliability gates, max-lines ratchet, and localization checks.
  • pnpm run build — passed. The build reported a non-fatal local permission warning while attempting to update /usr/local/bin/orca-dev; compilation completed successfully.
  • git diff --check upstream/main...HEAD — passed.

Compatibility and non-goals

The change is platform-neutral and does not alter shell invocation, filesystem paths, Git commands, provider behavior, IPC, or public APIs. SSH remote configuration receives the OpenSSH-compatible precedence behavior; folder workspaces and local workspaces are unaffected. Repeatable directives such as IdentityFile are intentionally outside this change.

AI Review Report

Reviewed every changed line against upstream/main. The diff is limited to the SSH parser and its focused unit test. The regression covers false-valued booleans as first values as well as strings and numbers, ensuring nullish assignment preserves a first false value.

Security Audit

No new input source, command execution, interpolation, authentication flow, secret handling, IPC surface, or dependency is introduced. ProxyCommand remains stored as its original trimmed text; only duplicate precedence changes.

Notes

  • Targeted searches across open and closed issues and PRs for parseSshConfig, duplicate directives, first/last value behavior, affected option names, and expected OpenSSH behavior found no same-root-cause report.
  • Active PR fix(ssh): bound SSH config include expansion and globbing #10887 touches SSH config include loading for bounded expansion, not scalar option precedence.
  • No issue was created because this focused fix has a deterministic regression test and the contribution policy does not require a preceding issue.
  • X handle: not provided.

Comment on lines +210 to +232
IdentityAgent ~/.ssh/second-agent.sock
IdentitiesOnly yes
IdentitiesOnly no
ProxyCommand ssh -W %h:%p first-bastion
ProxyCommand ssh -W %h:%p second-bastion
ProxyUseFdpass yes
ProxyUseFdpass no
ProxyJump first-jump
ProxyJump second-jump
`)

expect(hosts[0]).toEqual({
host: 'repeated',
hostname: 'first.example.com',
user: 'first-user',
port: 2201,
identityAgent: testHomePath('.ssh', 'first-agent.sock'),
identitiesOnly: true,
proxyCommand: 'ssh -W %h:%p first-bastion',
proxyUseFdpass: true,
proxyJump: 'first-jump'
})
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Boolean false-first case not covered for new directives

The existing GSSAPIAuthentication test (lines 185–198) covers both orderings — true-first and false-first — validating that ??= correctly preserves an initial false. The new test only checks true-first (yes before no) for IdentitiesOnly and ProxyUseFdpass. If a regression ever broke ??= for the false/falsy branch (e.g., accidental revert to a truthy guard), the new test would still pass while the false-first case silently regressed. Adding a second Host block (e.g., IdentitiesOnly no first, IdentitiesOnly yes second) would mirror the GSSAPIAuthentication pattern and close this gap.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes OpenSSH first-value precedence semantics in the SSH config parser and, in doing so, extends the "fresh resolved config wins" principle across host, port, user, proxy, GSSAPI, and identity-file resolution for OpenSSH config-backed targets. It also introduces ordered multi-key authentication so that all identity files returned by ssh -G are tried in sequence rather than only the first.

  • Parser fix (ssh-config-parser.ts): Changes unconditional = to ??= for all single-valued directives (HostName, Port, User, IdentityAgent, IdentitiesOnly, ProxyCommand, ProxyUseFdpass, ProxyJump), preserving the first-obtained value as OpenSSH does. IdentityFile is intentionally left additive.
  • Fresh-config authority (ssh-connection-utils.ts, ssh-auth-resolution.ts, ssh-connection.ts): Adds isOpenSshConfigBackedTarget gating so that when a fresh ssh -G result is available, it is authoritative for effective host, port, user, proxy, GSSAPI flag, and agent socket — stale imported snapshot values become fallbacks only.
  • Multi-key authentication (ssh-private-key-authentication.ts): New module implementing a stateful authHandler queue that offers every resolved identity file to ssh2 in order; the queue correctly rebuilds on each connection attempt so passphrase/password retries pick up mutated config values. system-ssh-args.ts also stops prepending user@ for OpenSSH config-backed targets so the SSH config's User directive is not overridden.

Confidence Score: 5/5

Safe to merge; changes are confined to SSH config parsing, key resolution, and connection setup, with no alterations to public APIs, IPC surfaces, or data persistence paths.

The parser change is a mechanical and well-bounded operator substitution. The surrounding changes — fresh-resolved-config authority, multi-key auth handler, and username-stripping from SSH args — are each independently tested by focused unit and integration tests covering both the happy path and the pre/post-fix comparison. All 975 existing SSH-suite tests pass. The one observation (port NaN || 22 + ??= sentinel lock-in) only affects malformed configs that OpenSSH itself rejects.

Files Needing Attention: No files require special attention; ssh-auth-resolution.ts and ssh-connection.ts carry the most logic surface area and are the natural places to focus if edge cases surface post-merge.

Important Files Changed

Filename Overview
src/main/ssh/ssh-config-parser.ts Core parser fix: changes unconditional assignment to ??= for all single-valued directives except IdentityFile, correctly preserving first-obtained value per OpenSSH semantics.
src/main/ssh/ssh-config-parser.test.ts Adds a comprehensive regression test for repeated single-valued options, including a second Host block verifying that an initial false value for IdentitiesOnly and ProxyUseFdpass is preserved.
src/main/ssh/ssh-auth-resolution.ts Significant refactor from single-key to multi-key identity resolution; adds resolvePrivateKeys, readPrivateKeys, findEncryptedPrivateKeyPath, and refactors resolveAgentSocket to use isOpenSshConfigBackedTarget instead of a bare target.configHost check.
src/main/ssh/ssh-connection-utils.ts Adds isOpenSshConfigBackedTarget gating to resolveEffectiveHost, resolveEffectivePort, resolveEffectiveProxy, and user resolution in buildConnectConfig, making the fresh ssh -G result authoritative for all connection parameters when available.
src/main/ssh/ssh-connection.ts Updates GSSAPI proactive-probe logic to use fresh resolved config for config-backed targets, refactors passphrase-prompt path to use getPassphrasePrivateKeyPath (supports multiple keys), and adds a vi.unstubAllEnvs() cleanup fix in one test.
src/main/ssh/ssh-private-key-authentication.ts New module implementing ordered multi-key authentication via a stateful authHandler queue; correctly rebuilds the queue at each connection attempt start so mutated config.password/config.passphrase are picked up on retry.
src/main/ssh/system-ssh-args.ts Stops prepending user@ to the host argument for OpenSSH config-backed targets; widens isOpenSshConfigBackedTarget signature to accept a Pick type.
src/main/ssh/ssh-multi-key-authentication.test.ts New test file covering ordered multi-key auth: offering all resolved keys in order, credential-retry queue reset, encrypted-key path attribution, and system-SSH argument shape for config-backed targets.

Sequence Diagram

sequenceDiagram
    participant App
    participant SshConnection
    participant resolveWithSshG
    participant buildConnectConfig
    participant configurePrivateKeyAuth
    participant ssh2

    App->>SshConnection: connect()
    SshConnection->>resolveWithSshG: ssh -G configHost
    resolveWithSshG-->>SshConnection: resolved (hostname, port, user, identityFile[], proxyCommand)

    alt isOpenSshConfigBackedTarget and resolved has proxy
        SshConnection->>SshConnection: shouldUseSystemSshTransport true
        SshConnection->>SshConnection: doSystemSshProbeWithControlMasterRetry()
    else direct ssh2 path
        alt isOpenSshConfigBackedTarget and resolved.gssapiAuthentication
            SshConnection->>SshConnection: GSSAPI probe via system SSH
        end
        SshConnection->>buildConnectConfig: target + resolved
        Note over buildConnectConfig: effectiveHost=resolved.hostname, effectivePort=resolved.port, effectiveUser=resolved.user
        buildConnectConfig->>buildConnectConfig: resolvePrivateKeys
        buildConnectConfig->>configurePrivateKeyAuth: config, keys[], encryptedKeyPath
        alt "keys.length == 1"
            configurePrivateKeyAuth-->>buildConnectConfig: "config.privateKey = key"
        else "keys.length > 1"
            configurePrivateKeyAuth-->>buildConnectConfig: "config.privateKey=keys[0] + authHandler queue"
        end
        buildConnectConfig-->>SshConnection: ConnectConfig
        SshConnection->>ssh2: connect(config)
        ssh2->>SshConnection: "authHandler(authsLeft=null)"
        SshConnection-->>ssh2: none to publickey[0] to publickey[N] to agent
        alt passphrase needed
            SshConnection->>App: onCredentialRequest passphrase
            App-->>SshConnection: passphrase
            SshConnection->>ssh2: retry
        end
    end
Loading

Reviews (2): Last reviewed commit: "fix(ssh): preserve ordered config identi..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e61a8b9-ac33-4281-900f-3bf191fc5ee7

📥 Commits

Reviewing files that changed from the base of the PR and between 1df8aa5 and 0d4f69105f6da5a7aabb4e8b3b26db5ad6573f64.

📒 Files selected for processing (2)
  • src/main/ssh/ssh-config-parser.test.ts
  • src/main/ssh/ssh-config-parser.ts

📝 Walkthrough

Walkthrough

Updated parseSshConfig so repeated single-valued directives retain their first values instead of being overwritten. This applies to host, port, user, identity, authentication, and proxy options. Added a test covering repeated directives, including IdentityAgent path expansion, and asserting the first values are returned.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is mostly complete, but the AI Review Report does not explicitly confirm cross-platform review for macOS, Linux, and Windows. Add an explicit AI Review Report note confirming cross-platform compatibility review for macOS, Linux, and Windows, including shortcuts, paths, shell behavior, and Electron differences.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: preserving the first SSH config directive value.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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.

@Jinwoo-H
Jinwoo-H force-pushed the fix/ssh-config-first-value branch from 0d4f691 to 0ea2060 Compare July 30, 2026 21:17
@Jinwoo-H
Jinwoo-H merged commit 5fe3aaf into stablyai:main Jul 30, 2026
41 checks passed
nwparker added a commit that referenced this pull request Jul 31, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(ssh): preserve first config directive value

* test(ssh): cover false-first config booleans

* fix(ssh): trust fresh OpenSSH config authority

* fix(ssh): preserve ordered config identities

---------

Co-authored-by: OrcaWin <[email protected]>
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.

3 participants