Repository navigation
feat(services/sftp): port from openssh to russh - #7977
Conversation
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.
| } | ||
|
|
||
| /// Validates the remote host key according to [`KnownHostsStrategy`]. | ||
| struct SshHandler { |
There was a problem hiding this comment.
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.
| 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, |
There was a problem hiding this comment.
magical number :) Move to a constant.
There was a problem hiding this comment.
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.
| strategy: self.known_hosts_strategy, | ||
| }; | ||
|
|
||
| let mut handle = client::connect( |
There was a problem hiding this comment.
We could parse lots of config ahead of time in core.
There was a problem hiding this comment.
04c34d6: build() resolves the endpoint, user, root, strategy, and known_hosts paths. Manager::create only connects and authenticates.
This comment is AI assisted.
| } | ||
| } | ||
|
|
||
| /// Resolves an OpenDAL path against the configured root. |
There was a problem hiding this comment.
should use path.rs in raw lib.
There was a problem hiding this comment.
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.
| } | ||
| } | ||
|
|
||
| /// A detachable reference to a live SFTP session. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@Xuanwo @erickguan this is draft right now, I've got something to fix |
|
@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? |
|
@chitralverma no rush at all. Enjoy your vacation 🫡 |
There was a problem hiding this comment.
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_toused the server-sidecopy-dataextension. 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
mainand switch fromfastpooltoasyncband::pool. Could you enableservices-sftpfor Windows inbuild_all_platformsin.github/workflows/ci_core.ymland bring the Windows OpenSSH behavior test into upstream CI? - Migration guide. Could
core/services/sftp/src/docs.mdexplain which OpenSSH features this backend does not support and how to migrate? Please cover~/.ssh/config,ProxyJump, systemknown_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'sknown_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.
|
Cargo cannot resolve the OpenDAL workspace lockfile with that pair. The proposed AI-generated maintenance note. |
|
The dependency blocker from Nov 22 is resolved on You can update the 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>
7901942 to
c079eac
Compare
|
@Xuanwo @erickguan the branch is rewritten on current
This comment is AI assisted. |
erickguan
left a comment
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
Exclusion goes in this function but not here. Exclude them with some filter expressions below
There was a problem hiding this comment.
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.
|
|
||
| /// 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). |
There was a problem hiding this comment.
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?); |
There was a problem hiding this comment.
Curious, does new lib require us using an Arc for client session in general?
I'm not sure if we need to pool clients.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
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>
|
@erickguan thanks. 59c144b, 23e887c, and 45adba8 address the review.
This comment is AI assisted. |
- 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>
|
@Xuanwo thanks for fd03296. With the This comment is AI assisted. |
Which issue does this PR close?
Closes #7968.
Rationale for this change
SFTP ran the system
sshbinary over a Unix control socket, so it needed an OpenSSH client and did not build on Windows (#2963).russhis a pure-Rust SSH client.What changes are included in this PR?
opensshandopenssh-sftp-clientwithrussh0.65.4 (fixes RUSTSEC-2026-0492 and -0495) andrussh-sftp4.0.0.known_hostsfiles OpenSSH reads.strictandaddreject changed keys, changed algorithms,@revokedkeys, and unreadable files.addaccepts a new host only after it records the key. Recorded key types are negotiated first, as in OpenSSH.copy-datacopy, andposix-renameofmain. Writes commit their offset only after the server acknowledges them.MaxStartupsdefault). Deprecatecontrol_directory; it has no effect.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
sshbinary 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:
~/.ssh/config. Setendpoint,user, andkeyexplicitly. The default user comes fromUSERorUSERNAME.known_hosts_strategy = "accept"no longer records host keys. Useaddto record them.keyset, only that key is tried. Without it, the SSH agent (Unix) and~/.ssh/id_rsa,id_ecdsa,id_ed25519are tried.ProxyJump.AI Usage Statement
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
fd032966f1An 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. On3ae6a0b7d2, the immediate retry on the same lister returned a permanentUnexpectedat 10.002 s after cancellation. Onfd032966f1, 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
magpie/codex/gpt-6.2-solandthinking=maximplemented the correction, ran the OpenSSH comparison, and prepared this section.magpie/kimi-code-cn/k3.1-proandthinking=highindependently reviewedfd032966f1and ran the SFTP unit suite.Xuanwo is accountable for this maintainer follow-up.