Skip to content

feat(sftp): SFTP v3 subsystem in a re-exec helper; exec.finished byte counts (ADR-0041, ADR-0042) - #196

Merged
gonzafg2 merged 13 commits into
mainfrom
feat/sftp-subsystem
Oct 29, 2026
Merged

gonzafg2 merged 13 commits into
mainfrom
feat/sftp-subsystem

Conversation

@gonzafg2

Copy link
Copy Markdown
Owner

Summary

This PR implements RFC-0013 through ADR-0041 and ADR-0042. sftp and scp from a stock OpenSSH 10.x client now work through QuantumSSH's own SFTP version 3 server. It runs in a re-exec helper mode of the quantumssh binary, written in Rust with no first-party unsafe.

Draft and stacked on #195 (ADRs), which is stacked on #194 (the RFC's Draft). It stays Draft until RFC-0013's comment period closes on 2026-10-26. The merge order is #194, then #195, then this PR.

Refs #109

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that changes existing behaviour)
  • Documentation only
  • Refactor / chore / CI / build

Changes

  • crates/quantumssh-core/src/sftp.rs (new): the SFTP v3 server, as ADR-0041 specifies.
    • Helper: the --quantumssh-internal-sftp-server mode is dispatched in main after the PTY helper. It is single-threaded and synchronous over fds 0 and 1, and starts in $HOME.
    • Bounds:
      • packets ≤ 256 KiB, and READ and WRITE ≤ 256 KiB − 1024;
      • at most 256 handles, which are 4-byte indices;
      • at most 100 names per READDIR reply, and never a reply over the packet bound.
    • Protocol behaviour: every request gets exactly one response. Malformed input exits 2. STATUS messages are fixed text.
    • Operations: std::fs, plus rustix::fs::utimensat for times on a path.
      • APPEND writes are sequential (pwrite ignores O_APPEND on macOS).
      • CLOSE syncs a written file, so a deferred write error reaches the client.
      • RENAME and SYMLINK follow OpenSSH: no overwrite, the link fallback and spare-link cleanup, and reversed SYMLINK arguments.
    • Extensions: posix-rename, fsync, limits and expand-path (~ only).
    • Longname: numeric owner and group, UTC date.
  • channel.rs: subsystem "sftp" is honoured in Idle with no pending PTY and a helper configured; everything else is refused, and a malformed name disconnects.
    • Audit: exec.* carry request_type = "subsystem" and command = "sftp". exec.finished gains bytes_received and bytes_sent for every request type, counted at the driver (ADR-0042).
  • exec.rs: spawn_sftp gives the SFTP helper the ordinary pipe-child treatment shared with exec (spawn_piped).
  • server::Config::pty_helper is renamed Config::helper: one binary hosts both helpers.
  • Docs:
    • ADR-0041 and ADR-0042 become Accepted. Their date assumes 2026-10-26.
    • ADR-0038 and ADR-0024 get Status pointers and errata: "SFTP brings multiplexing" is corrected, and command is added to ADR-0024's exec.finished row, because the code emitted it at acceptance (a3921d5).
    • The threat model gains RFC-0013's §5.4.5 entry verbatim, and §5.4.4 now names the byte counts.
    • CHANGELOG, README and CLAUDE.md are updated.

Checklist

  • My commits are signed off under the Developer Certificate of Origin (git commit -s).
  • My commit messages follow Conventional Commits.
  • I have run cargo fmt --all and cargo clippy --workspace --all-targets -- -D warnings locally.
  • I have added or updated tests where appropriate.
  • I have updated documentation (rustdoc, docs/, or README.md) where appropriate.
  • I have added a CHANGELOG.md entry under ## [Unreleased] if this change is user-visible.
  • If this change introduces a new dependency, I have justified it in the PR description and verified it passes cargo deny check. (No new dependency. Cargo.lock is unchanged.)

Security considerations

  • Exposure: this is post-authentication, but the SFTP parser and handlers are attacker-reachable. That is threat model §5.4.5, which comes from RFC-0013.
  • Memory safety and bounds:
    • There is no first-party unsafe.
    • Every length is bounded before allocation (read_packet checks the frame, then reads at most 256 KiB), and a malformed frame ends the session.
  • Isolation and access:
    • The helper runs outside the server process, as the service account.
    • It grants the same reach a shell session already has (§8.12). Confinement is Phase 3.
  • Data exposure:
    • STATUS sends no OS error detail.
    • No paths, names or content are logged.

Tests

  • Unit tests in sftp.rs (14):
    • VERSION and its extensions;
    • malformed input: not INIT first, an oversized length, a truncated field, a cut stream;
    • OP_UNSUPPORTED;
    • write, read-back and EOF;
    • APPEND ignoring the offset;
    • invalid handles and the handle cap;
    • READDIR then EOF;
    • REALPATH with a missing last component;
    • RENAME no-overwrite and posix-rename;
    • spare-link cleanup;
    • expand-path, limits, the status texts, civil dates and mode strings.
  • Core integration test: subsystem_without_a_helper_is_refused.
  • Binary-crate tests (tests/sftp.rs), re-executing the real binary:
    • a 100 KB round trip with OPEN/WRITE/CLOSE/READ, REALPATH, and exit-status 0 at EOF;
    • refusal of other subsystem names and after a pty-req.
  • Audit test: exec.finished carries bytes_received and bytes_sent.
  • Interop gate (OpenSSH 10.3p1 locally):
    • openssh_sftp: sftp -b with mkdir, put, rename, get, ls -l, rm and rmdir;
    • openssh_scp: both directions, with 300 KB files compared byte for byte.
  • Manual check: pwd shows $HOME, ls -l shows numeric owners and UTC dates, and df reports "Server does not support [email protected] extension". The audit record reads "request_type":"subsystem","command":"sftp",…,"bytes_received":322,"bytes_sent":1387.
  • macOS: clippy is clean. 136 unit tests, 41 integration tests, 6 PTY tests, 2 SFTP tests and the binary's 34 tests pass.
  • Linux, rust:1.99.0-bookworm in Docker: clippy is clean, and the same counts pass. As root, the spare-link cleanup test skips its assertion, because root ignores directory permissions.

Automated reviews

PRs authored by dependabot[bot] (and other bots) do not trigger opencode or Claude Code Review. Codex reviews through the Codex cloud GitHub App (ADR-0037).
They are covered by CI (commit-lint, build (ubuntu-latest) and build (macos-latest) — fmt, clippy, tests, release build —, cargo deny, openssh-interop; cargo audit runs weekly, not per PR) and manual review when needed.

https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW

@gonzafg2 gonzafg2 added enhancement New feature or request security Security-sensitive issue or change rust Rust ecosystem update labels Oct 13, 2026
@opencode-agent

Copy link
Copy Markdown

APIError: Insufficient Balance (request_id: d6a0ec0e-d032-4d46-8f6c-9a8cb573eb1e)

github run

gonzafg2 added a commit that referenced this pull request Oct 13, 2026
Codex on #198: SFTP is not on main yet, so the guide must not present it
as available. Sessions start in the home; ProtectSystem=strict's row
names every write instead of SFTP uploads.

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
gonzafg2 added a commit that referenced this pull request Oct 13, 2026
…de (ADR-0043) (#198)

* docs(adr): ADR-0043 — systemd Type=notify service, first-party readiness protocol, reference unit (Proposed)

- The binary sends READY=1 once listening and STOPPING=1 with
  EXTEND_TIMEOUT_USEC (drain + 5 s) at the first SIGTERM/SIGINT, as one
  AF_UNIX datagram over std's UnixDatagram: no libsystemd, no crate, no
  unsafe (as OpenSSH 9.8p1 did after CVE-2024-3094).
- Reference unit contrib/systemd/quantumssh.service: Type=notify,
  NotifyAccess=main, User=quantumssh, KillMode=mixed (ADR-0028's drain
  unchanged; cgroup leftovers killed at stop), Restart=on-failure,
  NoNewPrivileges=yes; no capability for port 22 and no sandboxing that
  would also confine sessions.
- docs/deployment.md is the operator guide; CI runs the unit under real
  systemd on the Ubuntu runner.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* feat(systemd): Type=notify readiness, reference unit and operator guide (ADR-0043)

- notify.rs (binary): the sd_notify datagram protocol on std's
  UnixDatagram, path and Linux abstract addresses; no libsystemd, no
  crate, no unsafe. READY=1 after the listener is bound and the
  SIGTERM/SIGINT handlers are installed; STOPPING=1 with
  EXTEND_TIMEOUT_USEC (drain + 5 s) at the first signal.
- The signal handlers are now installed before the listener task is
  spawned, so a stop that follows READY=1 always drains.
- contrib/systemd/quantumssh.service: Type=notify, NotifyAccess=main,
  User=quantumssh, KillMode=mixed, Restart=on-failure,
  NoNewPrivileges=yes.
- docs/deployment.md: service account, StrictModes file layout, config,
  port 22 (nftables redirect, or the capability and its cost), logs,
  stop/restart/reload, and what each sandboxing directive does to
  sessions.
- tests/systemd: the reference unit under a real systemd, in a
  container built from the interop gate's pinned Debian image; run by a
  new step in build (ubuntu-latest).
- Unit tests for the sender and an integration test that runs the
  binary with NOTIFY_SOCKET.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(adr): accept ADR-0043 with its implementation; README and Phase-2 scoping mark systemd landed

- ADR-0043 flips to Accepted with this implementing PR (#198); the date
  assumes a merge on 2026-10-13 (adjust if merged another day). Links
  name the implementing files.
- README's Phase-2 roadmap and the scoping note's workstream row and
  ordering mark systemd integration as landed.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* fix(exec): start session children in the service account's $HOME (RFC-0002)

RFC-0002's execution contract sets the child's cwd to the service
account's $HOME, but spawn and spawn_pty never set a working directory:
every exec and shell inherited the directory the server was started
from — `/` under systemd, the crate directory in the tests.

Both now call current_dir with the server's own HOME (the value the
sanitised environment passes on), falling back to `/` when HOME is
unset, relative or not a directory.

Tests: `pwd -P` on pipes (accept.rs) and on a PTY (pty.rs) returns the
canonical HOME; both fail without the fix (they print the crate
directory).

Found by Codex on #197.

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(adr): ADR-0043 — no WorkingDirectory=; the server starts sessions in $HOME (RFC-0002, #199)

Codex on #197: under the unit the working directory is `/`, and the
server did not set the children's. #199 fixes that in the server, for
every deployment; the unit needs no WorkingDirectory=.

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* test(systemd): the reference-unit check asserts the session runs in $HOME

systemd starts the server in `/`; with #199 merged in, a session's
`pwd -P` is the account's home. The check fails with the pre-#199
binary and passes with it.

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* fix(server): the accept loop's shutdown receiver exists before any signal

Codex on #198: serve subscribed its receiver when its future first ran,
and the binary dropped the channel's initial receiver. A broadcast only
reaches receivers that exist when it is sent, so a SIGTERM delivered
right after READY=1 — a stop job systemd queued during the start — could
be broadcast before serve subscribed, and the drain deadline was lost.

Server::serve now takes the loop's receiver: the one broadcast::channel
returns, alive from the channel's creation. The binary and the test
support pass it instead of dropping it.

Test: shutdown_sent_before_serve_first_runs_is_not_lost sends the
deadline before the spawned serve is first polled; with the old
subscribe-on-first-run it fails (SendError: no receiver).

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(deployment): no SFTP in the guide until it lands (#196)

Codex on #198: SFTP is not on main yet, so the guide must not present it
as available. Sessions start in the home; ProtectSystem=strict's row
names every write instead of SFTP uploads.

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(adr): ADR-0043 §4 — ProtectSystem=strict example without SFTP, which is not on main yet

Codex on #198 (the same text is in the guide).

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

---------

Signed-off-by: Gonzalo Fleming <[email protected]>
@gonzafg2
gonzafg2 marked this pull request as ready for review October 17, 2026 15:25
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-29T01:33:53.800611Z 720d23d Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@gonzafg2
gonzafg2 marked this pull request as draft October 17, 2026 15:26

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3d6659a15e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/channel.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
@opencode-agent

Copy link
Copy Markdown

PR Review: feat(sftp): SFTP v3 subsystem in a re-exec helper; exec.finished byte counts (ADR-0041, ADR-0042) (#196)

Decision: 🟡 Minor changes
Iteration: Review #2 (0 resolved, 7 open) — the first workflow comment was an API-error notice, not a review; Codex reviewed the same HEAD (3d6659a) with seven inline findings, all still present.
Lenses applied: Rust under crates/ (sftp.rs, channel.rs, exec.rs, server.rs, main.rs), design (ADR-0041/0042, RFC-0013, threat-model §5.4), CI (interop script).

Executive summary

The PR implements RFC-0013 as ADR-0041 describes: a bounded, first-party SFTP v3 server in a re-exec helper, reached only through subsystem "sftp" on a pipe child, with ADR-0042's byte counts added to exec.finished. The architecture respects the five commitments — no first-party unsafe, no new dependency, post-auth service-account access, and no KEX/legacy changes — and the framing bounds and handle table hold up. The remaining risk is audit accounting and the seven open Codex findings; none is a helper escape or transport regression, but the PR should not leave Draft until they are triaged and RFC-0013 is accepted.

Previous issues

# Issue Status Notes
1 ADRs accepted while RFC-0013 is still Draft (dated 2026-10-26) ❌ RFC-0013 still says Status: Draft / Implementation PR: TBD. PR body says it stays Draft until 2026-10-26 and merges after #194; keep it Draft and let RFC-0013 accept before flipping the ADRs. Merge gate, not a code change.
2 INIT version/extensions are not parsed before replying ❌ sftp.rs:146-151 checks only packet[0]; a 1-byte INIT gets VERSION. Impact is small (version is ignored by design) but it contradicts ADR-0041 §3's "truncated field ends the session".
3 RENAME overwrites an existing dangling destination symlink ❌ rename_if_absent uses fs::metadata(new) (sftp.rs:714-718), which follows the link. ADR-0041 §4 adopts OpenSSH's stat-then-rename and its Consequences document the check-then-act; confirm this is intended, otherwise use symlink_metadata.
4 Successful partial stdin writes are not counted ❌ exec.rs:839-847 acks only after write_all/flush; a partial write before EPIPE gets no acknowledgement, so bytes_received can undercount.
5 READ | CREAT cannot create a readable file ❌ Confirmed: std::fs::OpenOptions rejects it with InvalidInput ("creating or truncating a file requires write or append access"), so sftp.rs:304-312 returns FAILURE. ADR-0041 §4 promises the independent flag mapping.
6 Future mtime always loses the year in the longname ❌ sftp.rs:786-800 compares now.saturating_sub(mtime) < half-year; any future mtime is negative, so it always picks HH:MM. ADR-0041 §5 says the time-only form is only "within six months of now".
7 READDIR metadata is resolved through the stale stored path ❌ sftp.rs:479 re-resolves path.join(entry.file_name()); if the directory is renamed or replaced after OPENDIR, entries are skipped or get another directory's attributes.

New findings

🟡 Important (should be resolved)

crates/quantumssh-core/src/channel.rs:369-371 — audit byte count (confidence: 82)

Problem: exec.finished is emitted before the driver drains consumption acks that are already queued. bytes_received is updated only in the recv_opt_consumed arm (channel.rs:436-442), but ready_to_close (channel.rs:573-574) only checks child output, and the biased select! gives an inbound packet priority over the ack arm. On either the normal ServerClosed -> Closed handshake (channel.rs:1087-1090) or the early-close path, the loop can reach the emit below with acks still unread, so a transfer that crossed the channel is reported smaller than it was — up to the in-flight window (~2 MiB), and potentially 100% for a small transfer.

if d.state == ChannelState::Closed {
    d.emit_finished();
    return Ok(());
}

This is a separate mechanism from the open partial-write finding (#4): here every write was fully acknowledged, but the acknowledgement had not been consumed when the event was emitted. Nothing drains consumed_rx before emit_finished, including the Drop guard.
Fix: Drain queued acks before logging, so the count matches ADR-0042's "handed to the child" definition:

fn emit_finished(&mut self) {
    if let Some(child) = self.child.as_mut() {
        while let Ok(n) = child.consumed_rx.try_recv() {
            self.bytes_received = self.bytes_received.saturating_add(u64::from(n));
        }
    }
    if let Some(command) = self.command.clone()
        && !self.finished_emitted
    {
        // ... existing event
    }
}

Anchor: ADR-0042 (bytes_received: "CHANNEL_DATA payload bytes from the client that were handed to the child"), threat-model §5.4.4.

💡 Suggestions (nice to have)

  • [docs/adr/0041-sftp-v3-server-in-a-re-exec-helper.md:201-205]: §7, being accepted in this PR, says the unit tests cover "each handler", "CLOSE reporting a sync failure" and "the link-failure fallback"; the 14 tests in sftp.rs:869-1233 and the integration tests contain none of those (and no SETSTAT/FSETSTAT/STAT/LSTAT/READLINK/SYMLINK test either). Correct §7 before acceptance, or add the tests. Anchor: ADR-0041 §7, ADR-0015 (fix before acceptance; afterwards it would need an erratum).

github run

@gonzafg2
gonzafg2 marked this pull request as ready for review October 17, 2026 21:43

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3d6659a15e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/quantumssh-core/src/channel.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
gonzafg2 added a commit that referenced this pull request Oct 17, 2026
…ks; future mtimes show the year

Codex on #196:
- every RENAME existence check uses symlink_metadata, so a dangling
  symlink at the destination is never replaced (stricter than OpenSSH's
  stat, in the direction of the no-overwrite invariant);
- the longname uses the time form only for an mtime in the six months
  up to now; a future mtime gets the year (OpenSSH's sftp-common.c rule).

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
Comment thread crates/quantumssh-core/src/sftp.rs Resolved
@opencode-agent

Copy link
Copy Markdown

PR Review: feat(sftp): SFTP v3 subsystem in a re-exec helper; exec.finished byte counts (ADR-0041, ADR-0042) (#196)

Decision: 🔴 Blocked
Iteration: Review #3 (2 withdrawn as intended, 7 open) — HEAD unchanged at 3d6659a; the first workflow comment was an API-error notice, and Codex reviewed the same HEAD with seven inline findings.
Lenses applied: Rust under crates/ (sftp.rs, channel.rs, exec.rs, server.rs, main.rs), design (ADR-0041/0042, RFC-0013, threat model §5.4), CI/interop.

Executive summary

The PR implements RFC-0013 as ADR-0041 describes: a bounded, first-party SFTP v3 server in a re-exec helper, reached only through subsystem "sftp" on a pipe child, with ADR-0042's byte counts added to exec.finished. The architecture respects the five commitments — no first-party unsafe, no new dependency, no KEX/legacy change, post-auth service-account access — and the framing bounds and handle table hold up. The residual risk is not a helper escape: it is the ADR/RFC sequencing plus five confirmed SFTP/accounting defects. Two earlier findings (RENAME and READDIR) are withdrawn after checking them against ADR-0041's OpenSSH-parity mapping.

Previous issues

# Issue Status Notes
1 ADR-0041/0042 marked Accepted while RFC-0013 is Draft / Implementation PR: TBD, dated 2026-10-26 ❌ open docs/rfcs/0013-sftp-subsystem.md:3,7; docs/adr/0041-...:3-4, docs/adr/0042-...:3-4. RFC #194 and ADR #195 are still open, so the stated merge order is not satisfied. Violates the CLAUDE.md RFC-vs-ADR lane; the future date is also not an actual acceptance date. Merge gate (Codex P1).
2 INIT version/extensions are not parsed before replying ❌ open sftp.rs:146-151 checks only packet.first() == FXP_INIT; a 1-byte INIT gets VERSION instead of exit 2. ADR-0041 §3 requires the version to be read and a truncated field to end the session. Confidence 86.
3 RENAME overwrites an existing dangling destination symlink ✅ withdrawn sftp.rs:714-718 uses fs::metadata(new), the stat-equivalent OpenSSH uses in sftp-server.c:1274-1314; ADR-0041 §4 mandates OpenSSH semantics and its Negative section accepts check-then-act. Not a defect.
4 Successful partial stdin writes are not counted ❌ open exec.rs:834-848 acks only after write_all/flush; a prefix written before EPIPE was handed to the child but never counted. ADR-0042 defines bytes_received as bytes "handed to the child". Confidence 85.
5 READ | CREAT cannot create a readable file ❌ open sftp.rs:300-313: std::fs::OpenOptions rejects create without write/append (InvalidInput), so a valid SFTP v3 combination returns FAILURE. ADR-0041 §4 maps READ and CREAT independently. Blocking (confidence 90).
6 Future mtime always loses the year in the longname ❌ open sftp.rs:788: now.saturating_sub(mtime) is negative for any future mtime, so it always selects HH:MM. ADR-0041 §5 allows the time-only form only "within six months of now". Confidence 82.
7 READDIR metadata is resolved through the stale stored path ✅ withdrawn sftp.rs:479-484 re-resolves the stored path, which is exactly ADR-0041 §4's prescribed read_dir + per-entry symlink_metadata; the rename/replace race stays within the service account. Not a defect.
8 exec.finished is emitted before draining queued consumption acks ❌ open channel.rs:366-371,435-443,610-629: bytes_received grows only in the consumed-ack arm, but the Closed path and Drop emit without draining consumed_rx; the biased select lets the client's CLOSE win. ADR-0042's handed-byte count can undercount, worst on early close. Confidence 85.
9 ADR-0041 §7 overstates test coverage ❌ open docs/adr/0041-...:201-205 claims "each handler", CLOSE sync failure, and the link-failure fallback; the tests cover none of SETSTAT/FSETSTAT/SYMLINK/READLINK/FSTAT and neither failure path. Fix §7 before acceptance or add the tests. Suggestion (confidence 70); ADR-0041 §7 / ADR-0015.

New findings

No new finding reaches the ≥80 threshold. The open items above are the remaining work; #3 and #7 are withdrawn, not fixed.

Blocking: #1 (accept RFC-0013 before or in the same stack as ADR-0041/0042) and #5 (support READ | CREAT without granting the returned handle write access — e.g. rustix::fs::open with O_RDONLY | O_CREAT and File::from(OwnedFd), or create-then-reopen). The remaining open items are Important and should be fixed before the PR leaves Draft.

github run

gonzafg2 added a commit that referenced this pull request Oct 17, 2026
…ME; INIT, CLOSE, READDIR and stdin credit fixes

Codex on #195 and #196, each checked against openssh-portable V_10_6_P1:
- OPEN uses rustix::fs::open with flags_from_portable's flags:
  READ|CREAT creates a read-only handle, READ|APPEND grants no write;
- REALPATH ports sftp-realpath.c: every symlink is followed, the final
  one included (32 links), and only a missing last component is
  accepted, so a dangling final symlink resolves to its target;
- expand-path takes ~ from the working directory ($HOME or /) that the
  helper passes in, as OpenSSH's getcwd; relative REALPATHs use it too;
- RENAME's existence checks use symlink_metadata (a dangling symlink at
  the destination is never replaced) and the link fallback covers Linux
  EPERM (LINK_OPNOTSUPP_ERRNO);
- CLOSE syncs only written regular files (fdatasync fails with EINVAL on
  devices, FIFOs and sockets);
- INIT must carry its version; a truncated INIT ends the session;
- READDIR reads each entry's metadata through the open directory
  (DirEntry::metadata), not a rebuilt path;
- the longname uses the year for a future mtime (sftp-common.c rule),
  via a pure ls_date;
- pump_stdin credits each successful partial write, so a child that
  reads a prefix and exits is counted in bytes_received (ADR-0042).

Tests: init_without_a_version_ends_the_session,
open_maps_flags_independently, close_of_a_written_device_succeeds,
realpath_follows_symlinks_the_final_one_included, the extended
realpath_resolves_a_missing_last_component,
rename_does_not_replace_a_dangling_symlink, ls_dates_follow_openssh,
pump_stdin_credits_partial_writes (fails with the old write_all).
macOS and Linux (rust:1.99.0-bookworm) suites pass; local interop with
OpenSSH 10.3 passes openssh_sftp and openssh_scp.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
gonzafg2 added a commit that referenced this pull request Oct 17, 2026
…ize; READDIR errors and metadata

Second review round on #196:
- the handle cap is checked before the open: a refused OPEN has no side
  effect;
- SETSTAT's size on a path uses a write-only, non-blocking open and
  ftruncate, so a FIFO with no reader fails at once (OpenSSH: truncate(2));
- READDIR's metadata comes through the open directory without following
  symlinks; unreadable entries are skipped (as OpenSSH's failed lstat);
  a failed directory read is the reply's status, EOF only when exhausted.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
gonzafg2 added a commit that referenced this pull request Oct 17, 2026
…ize; partial-write latch; READDIR errors; drain stdin credits

Second review round on #196 (Codex and claude-review):
- the handle cap is checked before the open, so an OPEN refused at the
  cap has not created or truncated the file (claude-review);
- SETSTAT's size opens the path write-only and non-blocking, then
  ftruncate: a FIFO with no reader fails at once instead of hanging the
  single-threaded helper, matching OpenSSH's truncate(2) (claude-review);
- WRITE sets the handle's written latch as soon as any byte reaches the
  file, so CLOSE syncs after a write that failed part-way (Codex);
- a failed directory read is reported as the READDIR status, after any
  names already gathered, instead of looking like EOF (Codex);
- exec.finished drains the stdin credits still queued when the channel
  closes, so bytes the child received are counted (Codex, ADR-0042).

Tests: a_refused_open_leaves_the_file_untouched,
setstat_size_on_a_fifo_does_not_block. macOS and Linux suites pass;
local interop with OpenSSH 10.3 passes openssh_sftp and openssh_scp.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
@opencode-agent

Copy link
Copy Markdown

APIError: Insufficient Balance (request_id: 92ab2bcf-9d59-442e-9903-ce0df35e7989)

github run

@opencode-agent

Copy link
Copy Markdown

APIError: Insufficient Balance (request_id: 88ba74a9-a773-425a-b7db-cb7ce7b452b5)

github run

@gonzafg2

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1040a42a01

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/quantumssh-core/src/sftp.rs Resolved
@gonzafg2

Copy link
Copy Markdown
Owner Author

@codex review

… errata and threat model §5.4.5

- ADR-0041 and ADR-0042 flip to Accepted with this implementing PR, on
  RFC-0013's acceptance (2026-10-26; adjust if merged another day).
- ADR-0038's Status records the partial supersession of §1 (subsystem
  now honoured) and §9 (request_type "subsystem"); an erratum corrects
  "SFTP brings multiplexing".
- ADR-0024's Status adds ADR-0042's fields; an erratum adds `command`
  to the exec.finished row, which the code emitted at acceptance
  (a3921d5).
- The threat model gains RFC-0013's §5.4.5 entry verbatim, and §5.4.4
  names the byte counts as its record.
- CHANGELOG, README and CLAUDE.md list SFTP as landed.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
…ME; INIT, CLOSE, READDIR and stdin credit fixes

Codex on #195 and #196, each checked against openssh-portable V_10_6_P1:
- OPEN uses rustix::fs::open with flags_from_portable's flags:
  READ|CREAT creates a read-only handle, READ|APPEND grants no write;
- REALPATH ports sftp-realpath.c: every symlink is followed, the final
  one included (32 links), and only a missing last component is
  accepted, so a dangling final symlink resolves to its target;
- expand-path takes ~ from the working directory ($HOME or /) that the
  helper passes in, as OpenSSH's getcwd; relative REALPATHs use it too;
- RENAME's existence checks use symlink_metadata (a dangling symlink at
  the destination is never replaced) and the link fallback covers Linux
  EPERM (LINK_OPNOTSUPP_ERRNO);
- CLOSE syncs only written regular files (fdatasync fails with EINVAL on
  devices, FIFOs and sockets);
- INIT must carry its version; a truncated INIT ends the session;
- READDIR reads each entry's metadata through the open directory
  (DirEntry::metadata), not a rebuilt path;
- the longname uses the year for a future mtime (sftp-common.c rule),
  via a pure ls_date;
- pump_stdin credits each successful partial write, so a child that
  reads a prefix and exits is counted in bytes_received (ADR-0042).

Tests: init_without_a_version_ends_the_session,
open_maps_flags_independently, close_of_a_written_device_succeeds,
realpath_follows_symlinks_the_final_one_included, the extended
realpath_resolves_a_missing_last_component,
rename_does_not_replace_a_dangling_symlink, ls_dates_follow_openssh,
pump_stdin_credits_partial_writes (fails with the old write_all).
macOS and Linux (rust:1.99.0-bookworm) suites pass; local interop with
OpenSSH 10.3 passes openssh_sftp and openssh_scp.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
…ize; partial-write latch; READDIR errors; drain stdin credits

Second review round on #196 (Codex and claude-review):
- the handle cap is checked before the open, so an OPEN refused at the
  cap has not created or truncated the file (claude-review);
- SETSTAT's size opens the path write-only and non-blocking, then
  ftruncate: a FIFO with no reader fails at once instead of hanging the
  single-threaded helper, matching OpenSSH's truncate(2) (claude-review);
- WRITE sets the handle's written latch as soon as any byte reaches the
  file, so CLOSE syncs after a write that failed part-way (Codex);
- a failed directory read is reported as the READDIR status, after any
  names already gathered, instead of looking like EOF (Codex);
- exec.finished drains the stdin credits still queued when the channel
  closes, so bytes the child received are counted (Codex, ADR-0042).

Tests: a_refused_open_leaves_the_file_untouched,
setstat_size_on_a_fifo_does_not_block. macOS and Linux suites pass;
local interop with OpenSSH 10.3 passes openssh_sftp and openssh_scp.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
…, verbatim from the RFC

RFC-0013 now carries the root-relative link (Codex on #194); the entry
stays a verbatim copy.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>
SFTP v3 (draft-ietf-secsh-filexfer-02 §6.2) defines an empty path as the
user's default directory, but path arguments went to std::fs unchanged,
so STAT, OPENDIR and the other path requests answered NO_SUCH_FILE for
"". path_arg now reads it as ".". SYMLINK's target is link content and
stays as sent.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>
PathBuf::join drops the base when the suffix is absolute, so ~//upload
resolved to /upload. The helper now concatenates the working directory,
a slash and the suffix, as OpenSSH's "%s/%s" does
(sftp-server.c:1569-1572), and REALPATH collapses the repeated slash.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>
@gonzafg2
gonzafg2 force-pushed the feat/sftp-subsystem branch from 1de7454 to 967a073 Compare October 29, 2026 01:04
@gonzafg2
gonzafg2 changed the base branch from docs/adr-0041-0042-sftp to main October 29, 2026 01:04
@gonzafg2
gonzafg2 marked this pull request as ready for review October 29, 2026 01:05
The rebuilt branch was pushed while the PR still targeted the ADR
branch, so the main-only workflows did not run on 967a073.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>
@gonzafg2

Copy link
Copy Markdown
Owner Author

@claude review this PR (SFTP v3 subsystem, ADR-0041 and ADR-0042, now Accepted with this implementing PR). The branch was rebuilt on main with signed commits; the code matches the earlier head plus main. Focus on crates/quantumssh-core/src/sftp.rs (the attacker-reachable parser and handlers), the channel/exec wiring for subsystem, the exec.finished byte counts, and the docs/threat-model.md §5.4.5 entry. Earlier review rounds are on this PR.

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @gonzafg2's task in 1m 3s —— View job


Review of #196: SFTP v3 subsystem (ADR-0041 / ADR-0042)

Verdict: no blocking findings. I have two minor suggestions and two notes.

I read sftp.rs from the handlers through the end of the file, the channel.rs and exec.rs diffs, and the threat-model §5.4.5 entry. I did not re-read the first ~440 lines of sftp.rs (framing, INIT, open, close, read), since earlier rounds covered them. I did not run cargo in this job, so the build, clippy and test results are the ones in the PR description. The fixes from the earlier rounds are all present:

  • INIT version parse
  • symlink_metadata in RENAME
  • rustix::fs::open with OpenSSH's flag mapping
  • the handle-cap check before any side effect
  • DirEntry::metadata
  • the READDIR error status
  • the non-blocking SETSTAT size change
  • the partial-write latch
  • ~//x

Parser and handlers (sftp.rs)

  • Bounds hold.
    • Every string() call is capped at MAX_PACKET.
    • Extended attribute pairs run out of data before a huge count can spin.
    • READ is clamped to MAX_DATA.
    • READDIR accumulates entry sizes against MAX_PACKET.
    • No reply can exceed the packet bound: NAME replies from REALPATH and READLINK are limited by PATH_MAX.
  • No first-party unsafe, no new dependency. The rustix uses are open, ftruncate and utimensat.
  • Minor: realpath is quadratic on a long path (sftp.rs:793-799). left.drain(..=i) shifts the whole remaining buffer for every token. A 256 KiB path made of ./ or a/ repeated is about 128K tokens, which is a few GB of memmove per request. The a/ form also costs about 128K lstat calls.
    • This is post-auth and only affects the caller's own helper, so it is not a security boundary. It is still an easy CPU amplifier that the "bounded before allocation" framing doesn't cover.
    • Suggestion: keep a read cursor into left instead of draining, or reject a REALPATH/expand-path input over PATH_MAX. OpenSSH's realpath would simply fail with ENAMETOOLONG here.
  • Note: OPEN of a FIFO with no writer blocks the helper. This is the same as OpenSSH's sftp-server, and SETSTAT already avoids it with O_NONBLOCK. It only stalls the caller's own session, and the channel close should kill the process group. I'd keep the OpenSSH behaviour and say so in ADR-0041 §4. I did not check that a blocked open(2) is actually interrupted by that kill.

Channel / exec wiring

  • on_subsystem fails closed. It honours only sftp, in Idle, with no pending PTY and a helper configured. A name that can't be parsed within the 64-byte bound disconnects.
  • (Start::Sftp, _) ignores pending, which is safe because on_subsystem already rejects a pending PTY.
  • spawn_sftp reuses spawn_piped, so the environment sanitising, $HOME as working directory and process-group supervision match exec.
  • Byte counts:
    • bytes_sent is counted only after write_packet succeeds.
    • bytes_received is counted from the per-write credits in pump_stdin.
    • emit_finished drains consumed_rx under the finished_emitted guard, so both the normal close and the drop guard are covered.
    • The pump_stdin_credits_partial_writes test pins the partial-write case.
  • Note: bytes that have been accepted from the client but are still queued in the stdin channel or mid-write at close are not counted. That is consistent with ADR-0042's "handed to the child" definition and its "input the child never received" exclusion, so I'm not asking for a change.

Threat model §5.4.5

  • Mechanism, actors and ATT&CK mapping are consistent with the code.
  • Minor: "The parser is a pure function" overstates it. Reader, read_attrs and read_packet are pure. Server::handle dispatches straight into filesystem effects in the same call. It is "shaped for" a fuzzing harness only if the harness runs against a temp directory. Since the text is verbatim from RFC-0013, I'd either reword it in both places, for example "the framing and field parsers are pure functions; handle is driven against a scratch directory", or leave it and fix it when the Phase-3 harness lands.

Docs

ADR-0041/0042 status, the dates and the ADR-0038/0024 errata read consistently with the code.

left.drain(..=i) shifted the rest of the buffer for every component, so
a 256 KiB path of ./ cost quadratic time: about 280 ms against 8 ms with
the cursor on a debug build. A test pins a packet-sized path.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>
….4.5

ADR-0041 §4 says that opening a FIFO with no peer blocks the helper, as
it blocks OpenSSH's sftp-server, and that closing the channel kills the
process group. Threat model §5.4.5 no longer calls the whole parser a
pure function: the framing and field parsers are, and the handlers act
on the filesystem, so the Phase-3 harness drives them in a scratch
directory. RFC-0013, now accepted, keeps its original wording.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>
@gonzafg2

Copy link
Copy Markdown
Owner Author

Thanks. Point by point (e331792, 720d23d):

  1. realpath is quadratic: confirmed and fixed. The components are now read through a cursor into left, with no drain. After a followed symlink, left becomes the target plus left[pos..], and the cursor resets, so that rebuild is bounded by SYMLOOP_MAX. On a debug build, a 256 KiB path of ./ took about 280 ms before and 8 ms now. realpath_of_a_packet_sized_path_is_linear pins it with a 150 ms bound. The cost was smaller than the estimate, but it was real.
  2. FIFO OPEN blocks: kept as OpenSSH does it, and now written in ADR-0041 §4's OPEN row. Only the caller's session stalls, and closing the channel sends SIGKILL to the process group (exec.rs, ADR-0038 §6). SIGKILL ends a process blocked in a FIFO open(2).
  3. "The parser is a pure function": reworded in docs/threat-model.md §5.4.5. The framing and field parsers are pure functions; the request handlers act on the filesystem, so the Phase-3 harness drives them in a scratch directory. RFC-0013 is now accepted and is not edited in place, so it keeps its original wording, and the threat model, which is authoritative, carries the precise one.
  4. Uncounted queued stdin bytes: no change, since this matches ADR-0042's "handed to the child" definition, as you note.

Workspace: clippy is clean on macOS and Linux, and 245 tests pass.

@gonzafg2

Copy link
Copy Markdown
Owner Author

@codex review

@gonzafg2

Copy link
Copy Markdown
Owner Author

@claude review the two new commits on top of your last review: e331792 (REALPATH cursor instead of drain, plus the linear-time test) and 720d23d (ADR-0041 §4 FIFO note, threat model §5.4.5 parser wording).

@claude

claude Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @gonzafg2's task in 27s —— View job


Review of e331792 and 720d23d

No blocking findings. Two minor notes. I read both diffs and the full realpath function in context (sftp.rs:780-860). I did not run cargo in this job, so the linear-time test result is the one you reported.

e331792: REALPATH cursor (sftp.rs)

The change is correct. I traced these cases:

  • Cursor bookkeeping. pos always points at the first unread byte. A non-final token advances it past the /. The final token sets pos = left.len(), which ends the loop.
  • Symlink splice. The rebuilt left is the target, then /, then left[pos..], and pos resets to 0. It is built from the unread tail only. The old code appended all of left, so this is equivalent and does not re-read consumed components.
  • Last-component link. When last is true, the tail is not appended. The target replaces left and is resolved from pos = 0. This matches the previous behaviour, including the dangling-final-symlink case.
  • Empty and . tokens. These continue after pos has already advanced, so // and ./ runs cannot loop.
  • Cost.
    • The splice happens once per followed link, and SYMLOOP_MAX is 32, so the rebuild is bounded.
    • pop_component is O(len) per .., but resolved stays short in the ../ case.
    • A long a/a/a/… path can't pile up lstat calls, because it either hits a missing non-last component and errors or reaches ENAMETOOLONG first.

Minor:

  • The 150 ms wall-clock bound in realpath_of_a_packet_sized_path_is_linear leaves roughly 19× headroom over the 8 ms you measured. That is comfortable, but a heavily loaded shared CI runner could still hit it. If it ever flakes, compare against a half-size input (expect about 2× versus about 4× when quadratic) instead of using an absolute time. I'd leave it as is for now.
  • A cheap hard bound is still available. Rejecting REALPATH and expand-path input over PATH_MAX would give OpenSSH's ENAMETOOLONG, and it would make the linear-time test unnecessary. This is optional. The cursor already removes the amplification.

720d23d: docs

  • ADR-0041 §4, OPEN row. The FIFO note is accurate and consistent with the SETSTAT O_NONBLOCK handling described elsewhere in the ADR. It names the mitigation (SIGKILL to the process group, ADR-0038 §6). As you said, SIGKILL interrupts a process blocked in a FIFO open(2).
  • Threat model §5.4.5. The new wording is precise: the framing and field parsers are pure, and the handlers are driven in a scratch directory. It is also consistent with RFC-0013 staying unedited, since the threat model is the authoritative text.

Overall these two commits fix the quadratic cost, document the FIFO behaviour, and tighten the threat-model wording. Nothing remains open from my earlier review.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 720d23dd46

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@gonzafg2
gonzafg2 merged commit 14befc0 into main Oct 29, 2026
11 checks passed
@gonzafg2
gonzafg2 deleted the feat/sftp-subsystem branch October 29, 2026 01:35
gonzafg2 added a commit that referenced this pull request Oct 29, 2026
… up to date

#196 landed the SFTP stack before the freeze, so request_type subsystem
and exec.finished's bytes_received and bytes_sent move from the planned
additive changes into the version-1 catalogue (§3, §4), with command
"sftp" for the subsystem. RFC-0012 is cited as accepted, the two audit
gaps as fixed (#202, #204), and ADR-0024's command erratum as landed
with #196.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>
@claude

claude Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

@claude

claude Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

PR Review: feat(sftp): SFTP v3 subsystem in a re-exec helper; exec.finished byte counts (ADR-0041, ADR-0042) (#196)

Decision: 🟢 Approved
Iteration: Review #4 (9 resolved, 0 open) — three opencode runs (one API-error, two substantive), Codex reviews. HEAD is 720d23dd (13 commits since first review at 3d6659a).
Lenses applied: Rust under crates/ (sftp.rs, channel.rs, exec.rs, server.rs, main.rs), design (ADR-0041/0042, RFC-0013, threat model §5.4), CI/interop, governance (ADR-0015, RFC lane).

Executive summary

The PR implements RFC-0013 as ADR-0041 describes: a bounded, first-party SFTP v3 server in a re-exec helper, reached only through subsystem "sftp" on a pipe child, with ADR-0042's byte counts added to exec.finished. All nine issues from the previous iterations are resolved or withdrawn — including the RFC-0013 acceptance (merged in #194 on 2026-10-28), INIT version enforcement, READ|CREAT flag mapping, partial stdin write crediting, future mtime in longnames, and the emit_finished drain. Four further commits add an empty-path fix, ~//x expand-path correctness, a linear-time REALPATH, and a FIFO-OPEN documentation note. No new finding reaches the ≥80 threshold.

Previous issues

# Issue Status Notes
1 ADR-0041/0042 marked Accepted while RFC-0013 still Draft ✅ resolved RFC-0013 merged in PR #194 (2026-10-28); ADR dates updated in commit 967a073
2 INIT version not parsed; a 1-byte INIT gets VERSION ✅ resolved Commit 75d275c: r.byte()? != FXP_INIT || r.uint32().is_err() returns exit 2; init_without_a_version_ends_the_session
3 RENAME overwrites an existing dangling destination symlink ✅ withdrawn rename_if_absent uses symlink_metadata per commit 75d275c; OpenSSH parity confirmed
4 Successful partial stdin writes not counted in bytes_received ✅ resolved Commit 75d275c: pump_stdin loop credits each partial write; pump_stdin_credits_partial_writes
5 READ|CREAT cannot create a readable file ✅ resolved Commit 75d275c: rustix::fs::open with flags_from_portable flags; open_maps_flags_independently
6 Future mtime always loses the year in the longname ✅ resolved Commit 75d275c: ls_date checks mtime > now; ls_dates_follow_openssh
7 READDIR metadata resolved through stale stored path ✅ withdrawn DirEntry::metadata() per ADR-0041 §4; confirmed OpenSSH parity
8 exec.finished emitted before draining queued consumption acks ✅ resolved Commit e68f6ae: emit_finished drains consumed_rx before logging bytes_received; channel.rs:612-619
9 ADR-0041 §7 overstates test coverage 🔄 partly resolved Tests added for SETSTAT, link-fallback, CLOSE on devices, RENAME; LSTAT/FSTAT/FSETSTAT/READLINK/SYMLINK/MKDIR/RMDIR still have no dedicated unit tests, and CLOSE sync-failure has no explicit test. Confidence 70 — below threshold

New findings

No finding in the new commits (7e37f625 through 720d23dd) reaches the ≥80 threshold.

  • fix(sftp): an empty path names the working directory (7e37f625): path_arg returning . for an empty byte slice is correct per draft-02 §6.2. SYMLINK's raw_path_arg correctly bypasses this.
  • fix(sftp): ~//x in expand-path stays under the working directory (30ae89e): byte-concatenation of cwd + "/" + rest produces {cwd}//x; Path::eq compares by components so {cwd}//x == {cwd}/x in Rust, and REALPATH collapses repeated slashes before any I/O. The fix and test are sound.
  • fix(sftp): REALPATH reads components through a cursor, not drain (e331792): cursor-based linear scan, confirmed by realpath_of_a_packet_sized_path_is_linear (<150 ms on a packet-sized path on debug builds).
  • ADR-0038/0024 errata (accepted ADRs): dated annotated notes with in-place corrections, as ADR-0015 requires.
  • ADR-0041 accepted from Proposed: OPEN row clarification added before acceptance; immutability binds only after acceptance.

Decision: 🟢 Approved

github run

gonzafg2 added a commit that referenced this pull request Oct 29, 2026
…sioned JSON contract (#203)

* docs(adr): ADR-0044 — freeze the audit-log schema as version 1 in a project-owned JSON envelope (Proposed)

The first item of the 0.1.0 freeze checklist. The JSON log becomes a
project-owned, versioned contract:

- envelope: one flat object per line — schema_version (1), timestamp,
  level, event (catalogue) or message (diagnostics), peer_addr, then the
  event's fields; no target, span name or span list; a FormatEvent in
  the binary encoding with serde_json (already in the build);
- the version-1 catalogue: ADR-0024's events plus rekey.completed,
  connection.refused and ADR-0038's fields, all on the non-suppressible
  audit tier (six events move there);
- server.config_error's `message` field becomes `error` (today it
  duplicates the JSON key that holds the event name);
- compatibility: additive changes (new event, field or open-enumeration
  value) keep version 1; anything else bumps it with an ADR and a
  CHANGELOG migration note.

The inventory also found audit events without peer_addr — fixed in #202.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — audit-log schema version 1 (was ADR-0044; RFC lane per review)

Codex on #203: the frozen audit log is a new public compatibility
contract, an RFC under CLAUDE.md; and the freeze refines two accepted
RFCs (RFC-0010's error classes, RFC-0008's authenticated_identity), which
an ADR cannot. ADR-0044 becomes RFC-0014 (Draft, 14-day window).

Review findings folded in:
- server.config_error splits into `class` (RFC-0010's four classes plus
  the startup ones) and `error`, keeping RFC-0010's stable classes
  machine-readable (Codex);
- successful configuration load is recorded: server.started gains
  config_file, server.config_override joins the catalogue (Codex, §2.7);
- connection.refused keeps `limit`, superseding ADR-0028's `reason`
  explicitly (Codex);
- RFC-0008: authenticated_identity stays the proven key's fingerprint;
  certificate fields arrive additively, conditional on certificate
  authentication (Codex);
- exec.finished's `command` listed as a change against ADR-0024
  (claude-review);
- every failed attempt, the budget-exhausting one included, emits
  auth.failed — fixed in #204 (claude-review);
- failure_count is per connection; aggregate by IP (claude-review);
- all enumerations are open; changing an event's level is breaking
  (claude-review);
- the SFTP additions cite #194/#195 as proposed, not as existing ADRs
  (both reviewers).

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — config_file on server.config_error too

Codex on #203: a startup failure after a successful config load (host
key, authorized_keys, runtime, bind) returns before server.started, so
the error record could not name the configuration that produced it.
config_file is now on every server.config_error as well (the canonical
path once resolved, the path as given if that failed, "" without
--config), so each error record stands on its own.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — no edits to accepted RFCs; fingerprint and override-key formats

Codex on #203:
- accepted RFCs are not edited in place (docs/rfcs/README.md, "After
  acceptance"): only ADR-0024 and ADR-0028 gain Status pointers;
  RFC-0010 and RFC-0008 keep their text and this RFC states what it
  supersedes;
- host_key_fingerprint's representation is frozen: `SHA256:` + unpadded
  standard base64 of SHA-256 over the public-key blob (OpenSSH's format);
- server.config_override's `key` values are the TOML paths
  (server.listen, server.host_key, auth.authorized_keys,
  server.handshake_timeout, logging.format); new keys use the same form.

Refs #109

Claude-Session: https://claude.ai/code/session_01HxXXh6HEpJBs7tbuz3NmtW
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — a superseding ADR, not Status pointers, changes ADR-0024/0028/0029

docs/adr/README.md allows an accepted ADR to change only through a
superseding ADR, so the implementing PR adds one that supersedes the
listed parts of ADR-0024, ADR-0028 and ADR-0029, as ADR-0031 does for
ADR-0008. ADR-0029's info-level override diagnostic and RFC-0010's
"no new audit event names" clause join §6, since server.config_override
changes both. RFC-0012 is cited as proposed (#172, TBD).

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — SFTP's fields are version 1; references brought up to date

#196 landed the SFTP stack before the freeze, so request_type subsystem
and exec.finished's bytes_received and bytes_sent move from the planned
additive changes into the version-1 catalogue (§3, §4), with command
"sftp" for the subsystem. RFC-0012 is cited as accepted, the two audit
gaps as fixed (#202, #204), and ADR-0024's command erratum as landed
with #196.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — pin kex.failed's reason tokens; summary count; SFTP wording

kex.failed's reason was "no-hybrid-kex, no-strict-kex, …". §4 now lists
the eleven tokens the transport emits with disconnect code 3 and keeps
the enumeration open, as for the override keys. The Summary counts five
documents, not three decisions, and the SFTP note moves out of the
planned-change list.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>

* docs(rfc): RFC-0014 — exit_status sentinels, full control-character escape, threat-model qualifiers

From claude-review on 4a9b58f:
- §4 pins exit_status: the exit code, 128 + n for a signal (also with
  exit-signal on the wire), and 127 when the child could not be started
  or waited on or no status was recorded.
- §2 and §7: the JSON encoder escapes every char::is_control character
  (C0, DEL, C1) as \u00XX, the set the human formatter escapes;
  serde_json alone covers only C0.
- Three threat-model citations (§2.7, §8.12) carry the qualifier.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp
Signed-off-by: Gonzalo Fleming <[email protected]>

---------

Signed-off-by: Gonzalo Fleming <[email protected]>
gonzafg2 added a commit that referenced this pull request Oct 29, 2026
…ates (#219)

CLAUDE.md's status paragraph listed "no config file" among the missing
production features, but the config file landed with #128 (ADR-0029). The
remaining gap it names is per-user privilege separation, until Phase 3
(threat model §8.12). The ADR-0024 and ADR-0038 errata entries added by
#196 were dated 2026-10-26, from the draft, while #196 merged on
2026-10-28.

Claude-Session: https://claude.ai/code/session_01QpBZ4qUr3ypV22CvmVwwHp

Signed-off-by: Gonzalo Fleming <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request rust Rust ecosystem update security Security-sensitive issue or change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant