Skip to content

fix(ssh): bound remote directory listing and folder transfer - #10878

Closed
nwparker wants to merge 5 commits into
oom-slice-6-stream-ingressfrom
oom-slice-7-ssh-fs
Closed

nwparker wants to merge 5 commits into
oom-slice-6-stream-ingressfrom
oom-slice-7-ssh-fs

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Slice 7 of the re-landed OOM work. Base is oom-slice-6-stream-ingress (#10854) — review only the top commit.

ELI5

When you browse a remote folder over SSH, the app used to ask for everything in it and hold the whole answer in memory. On a folder with a million files — node_modules, a build output directory, a log dump — that answer alone can be hundreds of megabytes, and it arrives before anyone checks how big it is.

Same story for downloading a folder: the code walked the whole tree, collected every path first, and only then started transferring.

Now listings are capped and checked, the walk streams entries a chunk at a time instead of collecting them, and folder transfers run against an explicit budget.

What changed

Directory listing (ssh-filesystem-directory-reader.ts)

  • readDir routes through the relay's bounded fs.readDirBounded and then validates the response against the same ceilings it requested. A relay that ignores the limits can't hand back an oversized listing and have it trusted.
  • An older relay lacking the bounded method is refused with a reconnect prompt instead of falling back — the fallback is exactly the unbounded enumeration being removed.

SFTP enumeration (ssh-filesystem-provider-sftp.ts)

  • readDirViaSftp materialized an entire directory before returning. It's now readDirectoryEntriesViaSftp, an async generator over opendir/readdir chunks, so a caller that stops early — at a budget ceiling, or on cancel — never holds the whole listing. The handle closes on every exit path.

Folder transfer budget (ssh-directory-transfer-budget.ts)

  • Bounds entries, depth, per-path bytes, retained path bytes, per-file bytes, and total file bytes for recursive transfers.
  • Upload and download deliberately get different limit sets — see below.

Windows folder upload (system-ssh-file-transfer.ts) — see the follow-up section; this is the code that actually applies the budget.

Proof the OOM fix works

Every bound was mutation-tested: the bound is removed and the suite re-run. All nine fail at least one test.

Removed bound Result
maximumDepth 1 test fails
maximumEntries 2 tests fail
maximumPathBytes 1 test fails
maximumRetainedPathBytes 1 test fails
maximumTotalFileBytes 1 test fails
WINDOWS_SSH_UPLOAD_PACKAGE_MAX_BYTES 3 tests fail (see the follow-up below)
Bounded-listing response validation 1 test fails
Reconnect-instead-of-fallback 1 test fails
Mobile-path response validation 1 test fails (gap found and closed — see below)
Streaming generator (buffer the full listing) 1 test fails
Download/upload limit-set choice 10 tests fail

A coverage gap this found. The mobile listing path forwards its tighter limits to the relay, and a test asserted the request carried them — but nothing asserted the response was validated. Deleting assertMobileFileDirectoryWithinLimit left the suite fully green. That's vacuous coverage: the limit looked enforced because the request looked right. Added validates bounded relay results on the mobile path too, which now fails when the assertion is removed.

Follow-up: the budget had no caller

A later sweep for a specific defect class — a bound landed without the code that applies it — found one here, and it is worth stating plainly because it means part of this slice was previously inert.

WINDOWS_SSH_UPLOAD_PACKAGE_MAX_BYTES (48 MiB) and SshDirectoryTransferBudget were both defined and unit-tested, but nothing constructed the budget for a Windows folder upload. The constant had zero references outside its own definition. So on the actual upload path, collectWindowsUploadEntries still walked the tree with readdir, base64'd every file into one array, and handed the result to a bare JSON.stringify — the exact unbounded accumulation this slice is meant to remove. The unit tests passed the whole time, because they exercised the budget class directly rather than the code that was supposed to use it.

Fixed by wiring the consumer:

  • Charge the budget while walking — recordPath per directory and file, recordFile per file size, so depth/entries/path/total-bytes are enforced during collection instead of after.
  • Stream the directory — opendir with for await instead of readdir, so a huge directory never materializes as one array. The handle closes on every exit path.
  • Bound the serialization — stringifyJsonWithinByteLimit(entries, WINDOWS_SSH_UPLOAD_PACKAGE_MAX_BYTES) fails at the ceiling rather than building an arbitrarily large string.
  • Read to the stat'd size — a fixed-size read loop rather than readFile, so a file growing mid-upload cannot expand an allocation the budget already accounted for. A short read or trailing bytes raise the existing "File changed during upload" error.

A second pass found the tests themselves were vacuous at the call site. The added
tests imported stringifyJsonWithinByteLimit and the budget class and called them
directly — so they proved the ceiling arithmetic, but not that the upload path used it.
Deleting the wiring above (new SshDirectoryTransferBudget(), the recordPath/recordFile
charges, the bounded serialize) left the suite fully green. That is the same defect class
this slice exists to close, one level up: a bound split from its call site, with a test
suite that can't tell.

The tests now drive uploadDirectoryViaSystemSsh against real on-disk fixtures. Every
mutation of the wiring fails at least one test:

Mutation Result
Delete the per-entry recordPath/recordFile charges 2 tests fail
Delete the per-directory recordPath charge 1 test fails
Replace the bounded serialize with plain JSON.stringify 2 tests fail
Construct the budget with all limits at MAX_SAFE_INTEGER 3 tests fail
Rethrow the raw JSON error instead of the typed capacity error 1 test fails
Rewrite the 48 MiB ceiling to MAX_SAFE_INTEGER 3 tests fail

Each rejection is also asserted to happen before spawn, so an oversized tree never
reaches an SSH process. The ceilings are asserted as literals
(expect(SSH_DIRECTORY_TRANSFER_LIMITS.maximumEntries).toBe(4_096)) — sizing a fixture
from the constant would pass at any value.

One assertion was itself vacuous on the first attempt: the serializer spy accumulated
calls from the direct-call tests earlier in the file, so the call-site assertion passed
even when the upload bypassed it. It now clears between tests, which is what makes the
JSON.stringify mutation fail.

Typed failure for oversized packages. stringifyJsonWithinByteLimit throws
JsonStringifyByteLimitError, which is not an SshDirectoryTransferCapacityError — so
the one rejection most likely to be hit in practice escaped the typed contract the other
six advertise. It is now translated to SshDirectoryTransferCapacityError('package').
This matters because JSON escaping can outgrow the bytes charged during the walk: a
control character in a filename costs 1 byte against the path budget but 6 once escaped.

Generalized lesson: a slice must not split a bound from its call site. Landing the constant alone yields a test suite that is green and a memory ceiling that does nothing.

Two limit sets, deliberately

Uploads build an in-memory package, so 4,096 entries / 32 MiB total is the right ceiling. Downloads stream each file straight to disk and hold one directory's entries at a time, so their real cost is depth plus that directory's size — the upload ceiling would reject an ordinary checkout containing node_modules.

Downloads therefore get a 1,000,000-entry whole-tree backstop while keeping the depth, per-path, and per-file guards. The choice is asserted: swapping downloads to the tighter set fails 10 tests.

Proof of zero regressions

  • src/main/ssh at the chain tip: 1,007 passed / 0 failed (65 files). Across src/main/ssh + src/main/providers + src/shared: 4,996 passed, 2 failures in src/shared/setup-agent-sequencing.test.ts — load-sensitive, pass in isolation, and untouched by this slice.
  • Typecheck clean: 0 errors on both config/tsconfig.node.json and config/tsconfig.web.json.
  • Lint at the repo baseline: 27 warnings / 0 errors. Format clean.
  • Merges cleanly into current main.

User-facing behavior changes

Three worth naming explicitly:

  1. An SSH host running an older relay can no longer browse directories. It gets "Safe remote directory browsing requires an updated relay. Reconnect the SSH target before retrying." This is intentional — the alternative is retaining the unbounded enumeration this slice removes — but it is a real behavior change for anyone connected to a stale relay, and the fix (reconnect) is stated in the message. The probe happens once per provider, not per listing.

  2. A directory exceeding the listing ceiling now fails with "This folder is too large to list safely" instead of loading. Previously it would load and could exhaust memory.

  3. A Windows folder upload above the budget now fails instead of proceeding. This ceiling existed in the code before but was never applied, so this is the point at which it starts having an effect. The limits are 4,096 entries, depth 64, 16 KiB per path / 4 MiB retained, 16 MiB per file / 32 MiB total, plus a 48 MiB serialized package. The failure is a typed SshDirectoryTransferCapacityError naming which limit was hit, and it is raised before any SSH process is spawned — not a silent truncation, so no file is dropped from a transfer that reports success. Uploading a folder large enough to hit this previously risked exhausting memory mid-transfer.

Folder downloads of ordinary repositories are unaffected — that's what the separate download limit set is for.

Made with Orca 🐋

Three unbounded remote-filesystem paths, all reachable by browsing or
downloading a large directory over SSH.

Directory listing
- `readDir` now calls the relay's bounded `fs.readDirBounded` and validates the
  response against the same ceilings it asked for, so a relay that ignores the
  limits cannot hand back an arbitrarily large listing.
- An older relay without the bounded method is refused with a reconnect prompt
  rather than falling back, since the fallback is exactly the unbounded
  enumeration this removes.

SFTP enumeration
- `readDirViaSftp` materialized an entire directory before returning.
  `readDirectoryEntriesViaSftp` is an async generator over `opendir`/`readdir`
  chunks, so a caller that stops early -- at a budget ceiling, or on cancel --
  never holds the whole listing. The handle is closed on every exit path.

Folder transfer budget
- `SshDirectoryTransferBudget` bounds entries, depth, per-path bytes, retained
  path bytes, per-file bytes, and total file bytes for recursive transfers.
- Upload and download get separate limit sets. Uploads build an in-memory
  package, so 4,096 entries / 32 MiB total is right. Downloads stream each file
  to disk and hold one directory's entries at a time, so that ceiling would
  reject an ordinary checkout containing node_modules; downloads get a
  1,000,000-entry whole-tree backstop while keeping the depth and per-path
  guards.

Every bound is mutation-tested -- removing any one of the nine fails at least
one test, including the download/upload limit-set choice and the streaming
generator itself.

Co-authored-by: Orca <[email protected]>
nwparker and others added 4 commits July 27, 2026 18:17
The 48 MiB package ceiling and the directory transfer budget were both
landed without the code that uses them, so neither bound anything: a
Windows folder upload still walked the tree with readdir, buffered every
entry, and serialized the whole package with an unbounded JSON.stringify.

Charge the budget while collecting entries, stream the directory with
opendir instead of materializing one array, and serialize through the
bounded stringifier so an oversized package fails before it is built.
The upload package tests exercised the budget class and the bounded serializer
directly, so deleting the wiring in collectWindowsUploadEntries left the suite
green around a ceiling that no longer applied. They now call
uploadDirectoryViaSystemSsh with real on-disk fixtures.

Also reports an oversized package as SshDirectoryTransferCapacityError('package')
instead of leaking the raw JSON limit error, so every capacity rejection carries
the typed reason the failure path advertises.

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

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Closing: the relay-backed SSH filesystem provider was removed with the SSH relay (#27214/#27215). Remote directory listings now go through the managed server's files.readDir, which already enforces a remote listing budget (assertDirListingWithinRemoteBudget). The stacked #10887 (SSH config include bounds) is still valid and stays open.

@OrcaWin OrcaWin closed this Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants