Skip to content

fix(store): bound the reader's memory by checking each file's size first - #252

Merged
Antruly merged 1 commit into
mainfrom
fix/251-template-store-read-bound
Oct 18, 2026
Merged

Antruly merged 1 commit into
mainfrom
fix/251-template-store-read-bound

Conversation

@Antruly

@Antruly Antruly commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes #251. The local store read every package file in full before comparing its size with maxFileBytes, so the per-file limit bounded the answer but not the memory the reader allocated. The reader now stats each file and refuses an oversized one from its size; the post-read comparison stays as the guard for a file that grows between the two calls.

Problem and expected behavior

walkFiles in src/application/TemplateStore.ts did:

content = await readFile(child);
if (content.byteLength > limits.maxFileBytes) throw invalid(...);

On main at b5abe0b, a package whose files/src/main.cc is 17 bytes, mode 000, imported with maxFileBytes: 8, reported:

expected 'io_error' to be 'invalid_package'

EACCES is only reachable after the read was attempted, so the size check was not what refused the file. The limit is documented in src/domain/templatePackage.ts:71 as the bound on one file, and the P4 scan (TemplateScan.ts, in #250, not yet on main at b5abe0b) already stats before reading for the same reason. Expected: the size decides, the buffer is never allocated, and the error names the limit.

Change and scope

  • walkFiles stats each regular file and refuses size > maxFileBytes with invalid_package before readFile; the post-read comparison remains and is commented as the growth-between-calls guard.
  • The module header now states that ordering and the residual race.
  • One regression case in TemplateStore.test.ts, skipped on Windows and as root (where the file mode is not enforced).

Not included: changing any store layout, metadata, limits, error codes, or contracts; a bounded read implementation for the growth race (the same narrow TOCTOU the scan accepts and documents).

Contract and boundary impact

  • Earliest changed layer: application (src/application/TemplateStore.ts).
  • Tool contract changes, and whether docs/public/tool-catalog.json was regenerated: none.
  • libuvcpp feature mapping changes: none.
  • Generated-code impact: none.
  • Evidence, unknown, or error-contract semantics: an oversized file now reports invalid_package instead of an io_error caused by reading it; no new code.
  • Generated metadata, package, or installation impact: none.

Expected effects:

  • Read files on the local filesystem.
  • Write files, including generated workspaces and build directories.
  • Compile or link C++ via CMake.
  • Start or stop a process.
  • Open a listening socket.
  • Make an outbound network request.
  • Record or persist captured traffic.
  • Documentation or usability only; no runtime effect.
  • Not sure yet; needs maintainer guidance.

Evidence and regression coverage

  • Tests added or updated: one case in src/application/TemplateStore.test.ts (16 → 17 in that file).
  • Base reproduction or other evidence: observed at b5abe0b — the case fails with expected 'io_error' to be 'invalid_package'. The same case passes at 934c74d. The defect proof is the error path itself: EACCES can only be produced by the readFile call, so it shows the read happened before the size decision.
  • The exact command a reviewer can run: npm run test:local -- src/application/TemplateStore.test.ts
  • Remaining proof gaps:
    • The memory bound is structural (the allocation is now gated by stat), not measured as peak RSS; no test allocates an arbitrarily large buffer.
    • The growth-between-stat-and-read race is not exercised; the post-read check covers it but the race itself is the same accepted TOCTOU the scan documents.
    • The regression case does not run on Windows or as root, where mode 000 is not enforced there.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable in the output.
  • Coverage that was not examined is reported as unknown, not complete.
  • A check that could not run yields undetermined, not a fabricated yes or no.
  • Resource kinds and provenance survive the boundary unchanged.

Validation performed

All commands ran in /tmp/wt-readbound at 934c74d, on Linux.

  • npm run test:local -- src/application/TemplateStore.test.ts — 17 passed (red before the change: 1 failed, 16 passed).

  • npx tsc --noEmit — exit 0.

  • npx oxfmt --check on the two changed files — "All matched files use the correct format."

  • npx oxlint on the two changed files — exit 0; only the two pre-existing TemplateStore.ts warnings (FileWalk unused, file over 500 lines), unchanged by this PR.

  • npm run check:pr with LIBUVCPP_ROOT=/home/zwy/下载/libuvcpp-1.7.0-linux-x64, PKG_CONFIG_PATH=$LIBUVCPP_ROOT/lib/pkgconfig, LD_LIBRARY_PATH=$LIBUVCPP_ROOT/lib — exit 0; vitest 78 files passed, 2 skipped; 1449 passed, 14 skipped (1463). The 14 skips are the same named lanes (native-probe build cache absent, opt-in published-package lane, Windows-only locators); none is claimed as covered.

  • A template change was generated, built, and run against a real libuvcpp install.

  • Not applicable (no template or libuvcpp-facing change).

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • libuvcpp version floor impact: none.
  • New network exposure or listening behaviour: none.
  • Package or release metadata impact: none.

Author readiness

Human owner: @Antruly

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above. (Fixes #251)
  • Tests cover the changed observable behaviour and its meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed. (No docs or contracts declare the reader's internals; the module header states the bound.)
  • User-visible CLI or MCP changes include representative output. (No CLI/MCP change.)
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

walkFiles read every package file in full and compared byteLength with
maxFileBytes afterwards, so a package holding an arbitrarily large file was
loaded before it was refused. The reader now stats each file and refuses an
oversized one from its size, which is what the limit is for; the post-read
comparison stays as the guard for a file that grows between the two calls.

Observed on main b5abe0b: an import of a 17-byte file with mode 000 and
maxFileBytes 8 reported io_error (EACCES), reachable only after the read was
attempted. The new case asserts invalid_package naming the limit instead, and
skips on Windows and as root, where the mode is not enforced.
@Antruly

Antruly commented Oct 18, 2026

Copy link
Copy Markdown
Owner Author

Review — fix(store): bound the reader's memory by checking each file's size first

Reviewed at head 934c74d against main at b5abe0b (the merge of #248). No blocking findings. This is the reader-side half of the note I raised on #248 ("a file is read whole before its size is checked"), and it fixes it in the right place.

What I verified independently

  • The defect and the fix are the same fact. I removed the new stat block from walkFiles as a mutation and ran the new case: it fails with expected 'io_error' to be 'invalid_package' (the EACCES path), exactly as the PR body claims; restoring the block makes it pass. So the test kills the regression rather than merely passing.
  • Ordering is right. Symlinks are classified from the Dirent before stat, so the new call cannot follow a link that the walk is about to refuse; a missing file between readdir and stat still reports io_error, the same code as the old readFile failure; and the post-read comparison is retained and commented as the growth-between-calls guard, so the race is refused rather than silently admitted.
  • The regression test is meaningful. Mode 000 on a 17-byte file with maxFileBytes: 8 means a read would fail with EACCES; reporting invalid_package with "larger than 8 bytes" can only happen if the size decided first. The Windows/root skips are honest (getuid?.() === 0 covers the root case on POSIX).
  • Gates at this head: TemplateStore.test.ts 17 passed; tsc --noEmit, oxfmt --check, lint, verify:test-discovery clean. CI: all 15 applicable checks pass (the two skipped jobs are the libuvcpp/MSVC lanes selected off for this change).

Non-blocking (my judgement)

  1. The manifest read is still unbounded. readPackageDirectory reads template.json whole before any limit applies (TemplateStore.ts:399), and maxFileBytes describes files/ only. A very large manifest still allocates in full, so "bounds the buffer the reader allocates" is true for package files, not for the reader as a whole. Bounding it too (a stat plus a documented manifest limit) would make the header's claim unconditional; at minimum the header could say which read it bounds. Not a regression — the file is still user-supplied input, though.
  2. The body's precedent citation points at an unmerged PR. "the P4 scan (TemplateScan.ts) already stats before reading" is true of feat(store): export, inspect, and scan template packages #250, which is not on main at b5abe0b; a reader of the merge commit will not find the file. A sentence naming the PR would keep the claim checkable.
  3. The store's own metadata read (TemplateStore.ts:495) is also unbounded, but the store wrote those bytes and they are small by construction; no action needed.

I am marking this ready and approving it for the owner under today's standing authorization.

@Antruly
Antruly marked this pull request as ready for review October 18, 2026 12:25
@Antruly

Antruly commented Oct 18, 2026

Copy link
Copy Markdown
Owner Author

Owner approval. Approved at 934c74d58745a6bd1dcf777379668372dcf48ebd.

Reviewed in this comment. No blocking findings: the size decision now precedes the read, a mutation that removes the stat makes the new test fail exactly as the defect did, and the post-read comparison still covers a file that grows between the two calls. The two non-blocking notes recorded there (the manifest read is still unbounded; the P4 precedent citation names an unmerged PR) do not hold the change.

At this head: TemplateStore.test.ts 17 passed, tsc --noEmit, oxfmt --check, lint and verify:test-discovery clean. All applicable checks pass. Readiness is declared (Owned by @Antruly; author readiness declared.).

Merging as a merge commit at the exact reviewed head.

Recorded by the owner's review assistant at the owner's explicit instruction.

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.

[Bug] The template store reads a package file before checking its size, so the byte limit does not bound memory

1 participant