Skip to content

feat(services/sftp): port from openssh to russh - #7977

Merged
Xuanwo merged 13 commits into
apache:mainfrom
chitralverma:feat/sftp-russh
Dec 1, 2026
Merged

Xuanwo merged 13 commits into
apache:mainfrom
chitralverma:feat/sftp-russh

Conversation

@chitralverma

@chitralverma chitralverma commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Closes #7968.

Rationale for this change

SFTP ran the system ssh binary over a Unix control socket, so it needed an OpenSSH client and did not build on Windows (#2963). russh is a pure-Rust SSH client.

What changes are included in this PR?

  • Replace openssh and openssh-sftp-client with russh 0.65.4 (fixes RUSTSEC-2026-0492 and -0495) and russh-sftp 4.0.0.
  • Check host keys in-process against the known_hosts files OpenSSH reads. strict and add reject changed keys, changed algorithms, @revoked keys, and unreadable files. add accepts a new host only after it records the key. Recorded key types are negotiated first, as in OpenSSH.
  • Keep the pool, timeouts, error stages, copy-data copy, and posix-rename of main. Writes commit their offset only after the server acknowledges them.
  • Limit each pool to 4 concurrent handshakes (below the MaxStartups default). Deprecate control_directory; it has no effect.
  • Enable SFTP on Windows in core, Java, and .NET, and in every Python wheel including ARMv7. Run the behavior suite against Windows OpenSSH.

Verified: 49 sftp unit tests, including retry, close, cancellation, listing, and version cases against an in-process russh server; 10/10 fixture tests and 130/130 behavior cases with and without a root on atmoz/sftp; 130/130 on Windows OpenSSH in CI; each new test fails when its rule is removed; clippy, fmt, generators (no diff).

Not verified: SFTP at runtime on ARMv7 (CI only builds those wheels); non-OpenSSH servers.

Are there any user-facing changes?

SFTP needs no ssh binary and works on Windows. The service docs cover unsupported OpenSSH client features and migration. Password login (#2966) is out of scope.

Breaking changes

Affected packages: core, bindings/java, bindings/python, bindings/dotnet

Migration:

  • The service no longer reads ~/.ssh/config. Set endpoint, user, and key explicitly. The default user comes from USER or USERNAME.
  • known_hosts_strategy = "accept" no longer records host keys. Use add to record them.
  • With key set, only that key is tried. Without it, the SSH agent (Unix) and ~/.ssh/id_rsa, id_ecdsa, id_ed25519 are tried.
  • Load passphrase-protected keys into the SSH agent. Use a plain key instead of a user certificate, and a forwarded local port instead of ProxyJump.

AI Usage Statement

  • Harness: Claude Code via T3 Code | Model: Claude Opus 5.5 | Effort: xhigh
  • Role: Rewrote the port on main, addressed the review, ran the checks, drafted this text. The July draft used OpenCode with Claude Opus 4.6. The author reviews every change and claim.

Maintainer follow-up in fd032966f1

An active directory-read retry now clears the idle deadline. A later cancellation starts a fresh 10-second idle period.

With loopback OpenSSH 9.2p1 paused after opening a directory, the first next() timed out after 250 ms. On 3ae6a0b7d2, the immediate retry on the same lister returned a permanent Unexpected at 10.002 s after cancellation. On fd032966f1, the retry was still waiting when OpenSSH resumed at 11.022 s. It returned the directory and file entries, then EOF. Paused-clock tests also verify checkout release during continuous abandonment and a fresh idle period after a second cancellation.

Maintainer AI usage

  • Pi via T3 Code with magpie/codex/gpt-6.2-sol and thinking=max implemented the correction, ran the OpenSSH comparison, and prepared this section.
  • Pi via T3 Code with magpie/kimi-code-cn/k3.1-pro and thinking=high independently reviewed fd032966f1 and ran the SFTP unit suite.

Xuanwo is accountable for this maintainer follow-up.

chitralverma added a commit to chitralverma/opendal that referenced this pull request Jul 28, 2026
Follow-up to review on apache#7977.

- Release open/opendir handles on drop. The old client closed them in
  OwnedHandle::drop; without it a ranged read or a truncated listing
  leaked a server-side handle per call.
- Resync copy on a short read instead of treating it as EOF, matching
  the reader. A mid-file short read silently truncated the target.
- Try rename before removing the destination. The pre-delete destroyed
  the target when the source was missing or unreadable.
- Clamp read and write payloads against packet_len, which the server
  applies to the serialized packet, not the payload.
- Reject unbracketed IPv6 endpoints; "::1" parsed as host ":" port 1.
- Warn when a host key cannot be recorded, since add then behaves as
  accept for every later connection.
- Cap agent identity attempts to stay under MaxAuthTries.
Comment thread core/services/sftp/src/backend.rs Resolved
Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/lister.rs Resolved
Comment thread core/services/sftp/src/reader.rs Resolved
Comment thread core/services/sftp/src/core.rs Outdated
}

/// Validates the remote host key according to [`KnownHostsStrategy`].
struct SshHandler {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe SshEndpoint?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

04c34d6 adds SshEndpoint { user, host, port }, parsed once in build(). The handler now holds only the known_hosts name and the verifier.

This comment is AI assisted.

Comment thread core/services/sftp/src/core.rs Outdated
let config = russh_sftp::client::Config {
// Every request is a single round trip, so allow slow servers more
// room than the crate default of 10 seconds.
request_timeout_secs: 60,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

magical number :) Move to a constant.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

04c34d6 removes the 60 s request timeout. A per-request limit would abort a server-side copy-data of a large file, and TimeoutLayer already bounds operations; a comment says so. The other limits are named constants.

This comment is AI assisted.

Comment thread core/services/sftp/src/core.rs Outdated
strategy: self.known_hosts_strategy,
};

let mut handle = client::connect(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We could parse lots of config ahead of time in core.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

04c34d6: build() resolves the endpoint, user, root, strategy, and known_hosts paths. Manager::create only connects and authenticates.

This comment is AI assisted.

Comment thread core/services/sftp/src/core.rs Outdated
}
}

/// Resolves an OpenDAL path against the configured root.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

should use path.rs in raw lib.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

04c34d6: remote_path uses build_rooted_absolute_path / build_absolute_path from raw::path. It only trims the trailing /, which OpenSSH for Windows rejects.

This comment is AI assisted.

Comment thread core/services/sftp/src/core.rs Outdated
}
}

/// A detachable reference to a live SFTP session.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I understand your intention is to keep reference to hold Handle so that you can receive session. But it's a bit hard to see how russh process or manage client/channel/handle lifetime and event from the documentation.

The documentation also explains more but we are building connections in readers, writers and listers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

04c34d6 removes SftpSessionRef. Readers, writers, and listers hold the pooled connection until their handle closes, as on main (#8959). OpenHandle owns the handle and an Arc of the connection. Dropping it without close() closes the handle on the connection's runtime, then returns the connection to the pool.

This comment is AI assisted.

@chitralverma

Copy link
Copy Markdown
Contributor Author

@Xuanwo @erickguan this is draft right now, I've got something to fix

@erickguan

erickguan commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

@chitralverma Do you have time and token to continue working on this PR? I am curious on how it will go! Also, you can use a branch in opendal repo to trigger a test in your next PR and merge PR.

@chitralverma

Copy link
Copy Markdown
Contributor Author

@chitralverma Do you have time and token to continue working on this PR? I am curious on how it will go! Also, you can use a branch in opendal repo to trigger a test in your next PR and merge PR.

Hi erik, I'm on a vacation Rn, gimme sometime?

@erickguan

Copy link
Copy Markdown
Member

@chitralverma no rush at all. Enjoy your vacation 🫡

@Xuanwo Xuanwo left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @chitralverma for moving SFTP to russh and verifying the OpenSSH behavior suite on Linux, macOS, and Windows. Cross-platform CI run

I recommend keeping this PR in Draft while we address the host-key checks, write retries, rename fallback, and directory-handle cleanup in the inline comments, along with these follow-ups.

  • Existing review threads. Could you remove the backend-emulated copy as requested in the existing thread? The legacy copy_all_to used the server-side copy-data extension. The current streamed copy can leave handles open on a pooled session if it is cancelled before cleanup. Please also address the other open threads. Copy · Endpoint parser · Reader concurrency
  • Rebase and Windows CI. Please rebase onto main and switch from fastpool to asyncband::pool. Could you enable services-sftp for Windows in build_all_platforms in .github/workflows/ci_core.yml and bring the Windows OpenSSH behavior test into upstream CI?
  • Migration guide. Could core/services/sftp/src/docs.md explain which OpenSSH features this backend does not support and how to migrate? Please cover ~/.ssh/config, ProxyJump, system known_hosts, passphrase-protected keys, and SSH agents on non-Unix platforms. Where applicable, show how to use explicit connection settings, a verified key in the user's known_hosts, and a preloaded key via the Unix SSH agent. Please update #7968 to reflect that the login feature requested in #2966 is outside this PR’s scope.

Note: This review was generated with AI assistance.

Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/writer.rs Resolved
Comment thread core/services/sftp/src/backend.rs Resolved
Comment thread core/services/sftp/src/lister.rs Resolved
@Xuanwo

Xuanwo commented Nov 22, 2026

Copy link
Copy Markdown
Member

russh needs to be at least 0.63.1 to address RUSTSEC-2026-0492. russh 0.65.4 and russh-sftp 2.3.0 compile together in isolation on Rust 1.91.1.

Cargo cannot resolve the OpenDAL workspace lockfile with that pair. opendal-service-smb uses smb 0.12.1, which pins sspi =0.21.3. On Apple targets, that release pins curve25519-dalek =5.0.0-rc.1, which conflicts with the ^5 requirement in patched russh releases. afiffon/smb-rs#186

The proposed sspi 0.23.1 update raises the smb MSRV to Rust 1.93. This PR can stay in Draft pending an upstream smb/sspi resolution compatible with OpenDAL’s Rust 1.91 MSRV. afiffon/smb-rs#189

AI-generated maintenance note.

@Xuanwo

Xuanwo commented Nov 28, 2026

Copy link
Copy Markdown
Member

The dependency blocker from Nov 22 is resolved on main. #9152 raised the MSRV to Rust 1.95, and #9153 removed the SMB dependency chain. On 809b764725, cargo metadata resolved russh 0.65.4 and russh-sftp 2.3.0 together for aarch64-apple-darwin. That check covered dependency resolution only.

You can update the russh requirement and lockfile on current main and continue addressing the existing review. The draft’s ^0.62.4 excludes 0.63.1, the minimum noted in that review.

AI-generated.

The openssh crate drives the system ssh executable over a Unix control
socket, so the service needed an ssh client on PATH and did not build
on Windows. russh is a pure-Rust SSH client.

- Verify host keys in-process against the known_hosts files that
  OpenSSH reads. strict and add reject changed keys, changed
  algorithms, @Revoked keys, and unreadable files, and add accepts a
  new host only after it records the key. Recorded key types are
  negotiated first, like OpenSSH.
- Authenticate with key, else with the Unix SSH agent and the default
  identity files.
- Keep the pool, timeouts, error stages, copy-data copy, and
  posix-rename of the openssh implementation. Writes commit their
  offset only after the server acknowledges them.
- Open handles and send readdir in tasks, so that cancellation leaks
  no handle and skips no entries.
- Deprecate control_directory, which configured the control socket.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
The Unix-only gates existed because openssh could not build on Windows. SFTP is not built or tested for ARMv7, so ARMv7 Python wheels still exclude it.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
- Build services-sftp in the cross-platform core build.
- Run the behavior suite against the OpenSSH server of Windows. The
  planner runs Windows-only setups only on the Windows core runner.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
@chitralverma

Copy link
Copy Markdown
Contributor Author

@Xuanwo @erickguan the branch is rewritten on current main (04c34d6, 798e4ef, c079eac). The July code was 1,100 commits behind, so I ported again rather than rebased. Replies are in each thread; this covers the rest of the review summary.

  • Pool: it uses main's asyncband pool, timeouts, and error stages. russh is 0.65.4, because RUSTSEC-2026-0495 needs 0.65.0 or later.
  • Windows CI: services-sftp is in build_all_platforms. The new windows_openssh setup runs the behavior suite against OpenSSH for Windows, and the planner sends it only to the Windows core runner. This is its first run.
  • Migration guide: src/docs.md has "Differences from the OpenSSH client": ~/.ssh/config, ProxyJump, passphrase keys, user certificates, and agents on Windows. The service now also reads the system known_hosts files, so they need no migration. upgrade.md has the summary, and the PR declares the breaking change.
  • sftp: Port the SFTP transport from openssh to russh #7968: it now says password login (feature request: support password login for sftp service #2966) is out of scope, and its copy and pool criteria match this PR.

This comment is AI assisted.

@github-actions github-actions Bot added bindings/dotnet bindings/java bindings/python core releases-note/feat The PR implements a new feature or has a title that begins with "feat" services/sftp size:XXL This PR changes 1000+ lines, ignoring generated files. website labels Dec 1, 2026

@erickguan erickguan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We can follow some more conventions in CI.

I'm for sure having some gaps in understanding new lib data structures so I would ask for some information like do we need to hold client or handles.

Some error processes are silent. Don't know if we want to log and continue or shout like crazy.

Comment thread .github/scripts/test_behavior/plan.py Outdated
def _filter_binding_cases(
cases: list[dict[str, str]], language: str
) -> list[dict[str, str]]:
cases = [v for v in cases if (v["service"], v["setup"]) not in WINDOWS_SETUPS]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Exclusion goes in this function but not here. Exclude them with some filter expressions below

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

45adba8 moves it below, next to the remotestorage filter. It stays before unique_cases, which keeps one setup per service: if a Windows setup sorted first, a later filter would drop the whole service from the binding jobs.

This comment is AI assisted.

Comment thread core/services/sftp/src/backend.rs Outdated

/// set endpoint for sftp backend.
/// The format is same as `openssh`, using either `[user@]hostname` or `ssh://[user@]hostname[:port]`. A username or port that is specified in the endpoint overrides the one set in the builder (but does not change the builder).
/// The format is either `[user@]hostname[:port]` or `ssh://[user@]hostname[:port]`, and the port defaults to 22. A username that is specified in the endpoint overrides the one set in the builder (but does not change the builder).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Mulit-line please.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 23e887c.

This comment is AI assisted.

to: String,
source_content_length_hint: Option<u64>,
) -> Result<Metadata> {
let client = Arc::new(core.connect().await?);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Curious, does new lib require us using an Arc for client session in general?

I'm not sure if we need to pool clients.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The library doesn't need it. RawSftpSession takes &self for every request, so stat, rename, and delete use the checkout directly. The Arc wraps only the pool checkout (SftpConnection), so that several OpenHandles can share one connection: copy opens the source and destination on it, and a handle dropped without close() closes itself in a task that needs its own reference. The connection returns to the pool when the last handle is closed.

The pool is main's (64 connections). Since #8959 a reader, writer, or lister keeps its connection until it closes. SFTP handles belong to one session, so a stream can't move to another connection. One session can carry many requests, so a shared session is possible, but that changes the capacity contract and is better as a separate change.

This comment is AI assisted.

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

AI-generated review of c079eac70b39.

The hosted Windows OpenSSH fixture passed all 130 behavior tests. Before marking the draft ready, please address the cancellation and close paths and the compatibility findings below. The home-relative key path was reproduced against OpenSSH with the same key and server on both versions. Windows job

Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/core.rs Resolved
Comment thread core/services/sftp/src/writer.rs Resolved
Comment thread core/services/sftp/src/writer.rs Resolved
An encrypted default identity file, an unreachable SSH agent, or an agent that refuses to sign was skipped without a trace. The PermissionDenied error now lists them in its skipped context.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
Signed-off-by: Chitral Verma <chitralverma@gmail.com>
- Move the PowerShell that starts sshd into setup.ps1, as hf3fs does
  with setup.sh, and export the environment like the other sftp setups.
- Filter Windows setups for bindings next to the other filters.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
@chitralverma

Copy link
Copy Markdown
Contributor Author

@erickguan thanks. 59c144b, 23e887c, and 45adba8 address the review.

  • CI conventions: the PowerShell that starts sshd is now windows_openssh/setup.ps1, as hf3fs does with setup.sh. The action exports the environment like the other sftp setups. If you meant other conventions, please point me to them.

  • Client or handles: each reader, writer, and lister holds one open SFTP handle and the pooled connection it was opened on. Handles belong to one session, so the stream can't let go of the connection until it closes the handle; this also keeps the pool capacity from fix(services/sftp): fix lister panics, rename pool deadlock, writer/copy close, create_dir errors, and URI port #8959. Copy holds two handles on one connection.

  • Silent errors: an authentication failure now lists the keys it skipped, such as an encrypted ~/.ssh/id_ed25519, an unreachable agent, or an agent that refused to sign. Before, these were silent. The others stay at debug because no caller can act on them:

    • a failed close after the data is fully read, or of a dropped handle (the server frees it with the connection, and the health check replaces a dead connection);
    • known_hosts lines that don't parse (OpenSSH skips them too).

    Write failures and close failures of a writer are returned as errors.

This comment is AI assisted.

chitralverma and others added 6 commits December 1, 2026 22:11
- Retire a connection when a request or handle on it is left in an
  unknown state: a cancelled open or readdir, or a dropped handle whose
  close fails or does not finish within 10 seconds. Retiring closes the
  SFTP session and keeps the pool from reusing the connection.
- Shut the socket down when connect_timeout expires, because russh
  keeps running the session task after the setup future is dropped.
- Keep a failed or cancelled close of a writer visible: a later close
  returns an error instead of success.
- Reject SFTP protocol versions other than 3, as openssh-sftp-client did.
- Expand a leading ~ in key, as ssh -i does, and ask for the RSA hash
  extension only for RSA keys.
- Leave the endpoint, which can hold a password, out of parse errors.
- Test these against an in-process russh server, and retry the partial
  write through the same SftpWriter.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
russh adds no native dependency beyond aws-lc-sys, which ARMv7 wheels already build through rustls, so SFTP moves into services-all.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
Base64 key text tripped typos, so the test keys move to files that .typos.toml excludes, like fixtures/sftp/test_ssh_key.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
Resolve the conflict with apache#9484 for the russh client:

- Keep this branch's core.rs. The openssh stderr filter does not apply,
  SftpCore prints no endpoint, and endpoint parse errors omit it.
- Authentication errors no longer name the user, which can come from
  the endpoint.
- endpoint_is_omitted_from_debug keeps its assertions. The build now
  rejects a password in the endpoint, so the test also checks that error
  and builds the service from an endpoint with only a user.
- sshd_connection_error_omits_endpoint_userinfo puts the marker in the
  user, because a password fails the build before any connection.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
…lled reads

- Retire the connection when a close fails or nobody waits for its
  reply, so the pool does not reuse a connection whose handle can still
  be open.
- Let a pending readdir own the directory handle. A retried next()
  waits for the same reply. Once no caller waits, the request has 10
  seconds; then it retires the connection and releases the checkout
  even if the lister stays alive, and next() returns an error instead
  of ending the listing.
- Consume repeated separators after ~ in key, so ~//.ssh/id stays under
  the home directory.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
Keep the assertions of fd03296's probe test and remove its eprintln output and the elapsed-time check that the paused clock makes always true.

Signed-off-by: Chitral Verma <chitralverma@gmail.com>
@chitralverma

Copy link
Copy Markdown
Contributor Author

@Xuanwo thanks for fd03296. With the Notify design, a retry that resumed waiting could still hit the deadline that the cancelled call started. Clearing the idle deadline while a caller waits fixes that. 9ae4767 only removes the eprintln! output and the elapsed-time check from the new retry test, and keeps its other assertions. All 126 checks passed on fd03296, and I'm marking the PR ready for review.

This comment is AI assisted.

@chitralverma
chitralverma marked this pull request as ready for review December 1, 2026 21:20
@Xuanwo
Xuanwo merged commit c2e721e into apache:main Dec 1, 2026
126 of 127 checks passed
@chitralverma
chitralverma deleted the feat/sftp-russh branch December 2, 2026 04:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bindings/dotnet bindings/java bindings/python breaking-changes core releases-note/feat The PR implements a new feature or has a title that begins with "feat" services/sftp size:XXL This PR changes 1000+ lines, ignoring generated files. website

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sftp: Port the SFTP transport from openssh to russh

3 participants