Bound build_context file reads and fail closed on oversized inputs
Hi Keshav,
This is the separate MR we agreed to on #6, holding the _MAX_READ_BYTES work that I pulled out so that one could stay scoped to the TP3 fix. It is stacked on #6 (the first commit shown here is #6's TP3 commit), so please merge #6 first, after which this diff reduces to the single bounded-reads commit.
What it does:
- raises the per-file cap to 50 MiB and aligns it with
static_runner.MAX_FILE_BYTES, so the limit lives as one number rather than two that can drift. - makes
build_contextfail closed: it now aborts in_validate_file_sizesbefore_read_file_cacheever runs, rather than silently caching an oversized file as empty. This is the heart of your original concern, a file large enough that we skip it should not come back reported as "safe". - counts lines in fixed 64 KiB binary chunks (so a multi-GB, newline-free file is never materialised whole).
- reads only a bounded prefix of an oversized SKILL.md, since the frontmatter sits at the top of the file.
- adds the same byte-counted guard to the direct analyzer entry points (static, AST, taint, YARA), so a caller that bypasses
build_contextdoes not reintroduce a silent skip.
Before raising this I had three other models review it independently against the actual code (not my description of it), and I want to be upfront about what they found, because it bears on exactly the discussion you wanted to have:
- the fail-closed guard does not yet cover the LLM
semantic_*analyzers.llm_analyzer_base.get_batcheshas no size check, so a programmatic caller that injects an oversizedfile_cachestill gets through on that path. - the manifest prefix read is in text mode, so the cap is counting characters and not UTF-8 bytes (the comment claims bytes), which only matters for multibyte content reaching
_parse_manifestdirectly. - user-supplied YARA rule files (via
--yara-rules-dir) are compiled with no size cap. They are not skill components, so they sidestep the gate. - the larger one, which is really a surrounding issue rather than something this MR introduces: the whole ingest layer in
input_handler.pyruns beforebuild_contextever sees a file, and it is unbounded. The URL download buffers the full body in memory,extractallhas no uncompressed-size bound so a "zip bomb" fills the disk, and the git clone has no post-clone size check. So the 50 MiB per-file gate can be defeated upstream, before it runs.
My instinct, and I am happy to be argued out of it, is to keep this MR to the per-file build_context bounding (which is self-contained and tested at 605 passing), and to raise a separate issue for the ingest-layer hardening, since that is a bigger change with its own design questions (streaming downloads against a running byte counter, a total-uncompressed-size budget for zip extraction, a clone size cap). I can fold (1) to (3) into this MR if you would rather have them here, or split them out as well, whichever you prefer.
Please add comments inline or on the thread, whichever is easier for you.
I opened #21 for the ingest-layer hardening I mentioned above (the unbounded URL download, the extractall zip-bomb, the git clone with no size check), so this MR can stay scoped to the per-file build_context bounding. A multi-model review of the issue draft turned up two more paths worth folding into that work, the single-file shutil.copy2 in _wrap_single_file, and symlinks planted in a zip or clone (a symlink to /etc/passwd passes the size gate today and gets read), so #21 now covers those as well.
While I was in this area I also opened #20, which is a different concern but a related one: detecting large blocks of whitespace used to hide prompt-injection instructions from a human reviewer (padding a file so the injected text sits well below, or off to the right of, what anyone sees on opening it). It is a detection pattern rather than ingest bounding, so it does not belong in this MR, but I am noting it here since it came out of the same read-through.
Thanks again, all fair. The split, the env crash, and the follow-ups are handled, and I have rebased onto current main now that #6 has landed, so the earlier dirty state is gone.
Blocking 1 (not self-contained). Done. The PR is now just the per-file read bounding (12 files, +323/-29 against main): build_context.py, static_runner.py, static_yara.py, behavioral_ast.py, behavioral_taint_tracking.py, llm_analyzer_base.py (one guard, see below) and their tests. I dropped the three pieces that did not belong: the retry/backoff and configurable concurrency (overlaps #29), the per-batch isolation and the _partition_findings_by_batch_coverage fallback (overlaps #32), and the Pydantic structured-output change (LLMFinding / MetaAnalyzerFinding ge/le to field_validator), which I will raise as its own PR with the rationale since it changes the LLM contract. meta_analyzer.py is untouched here, and I am happy to coordinate with whoever lands retry and batch-isolation.
Blocking 2 (import-time crash). That code is out of this PR with the split. For the record, the concurrency work I am proposing no longer parses env at import at all: the module-level int/float reads are replaced by a helper called lazily from resolve_max_concurrency() and the retry paths, which strips, falls back on empty or non-numeric input, warns, and clamps concurrency to a minimum of 1, so SKILLSPECTOR_MAX_CONCURRENCY= yields the default rather than a traceback.
The follow-ups, now folded in (not deferred). On reflection these all sit inside the bounded-reads surface, so they belong here:
get_batchesnow callsraise_if_content_exceeds_limitper cached file, so a programmatic caller injecting an oversizedfile_cacheon thesemantic_*path fails closed instead of being chunked and sent to the LLM. It is imported lazily inside the function, since a module-level import would cycle through the analyzers package__init__(which imports thesemantic_*analyzers, which importllm_analyzer_base).--yara-rules-dirrule files are now stat-capped in_collect_rule_files: an operator rule file over the limit is skipped with a warning (rule files are config, not the artifact under analysis, so skip rather than abort)._parse_manifestnow reads a bounded binary prefix and decodes, so the cap is a true byte ceiling rather than a character count, closing the multibyte gap you flagged in the "same memory bound" comment.
One change worth your eye: the analyzer guard now counts characters, not re-encoded bytes. You rightly liked the switch to len(content.encode("utf-8")), but it mis-fires on the build_context path: _read_file_cache decodes with errors="replace", so an undecodable on-disk byte becomes a 3-byte U+FFFD on re-encode. A legitimate binary file that passes the authoritative on-disk gate (_validate_file_sizes, stat) then inflates past 50 MiB on re-encode and aborts the whole scan (a ~17 MiB binary re-encodes to ~52 MiB). So raise_if_content_exceeds_limit now measures len(content) characters, always <= the source UTF-8 byte length, so content the on-disk gate admitted can never trip it while an injected oversized string still does. The byte-accurate enforcement stays where it can be measured correctly, on stat().st_size in _validate_file_sizes. There is a regression test for the sub-limit multibyte case.
MAX_FILE_BYTES, 1 MB to 50 MiB. Intentional, and you are right about the cost: it stops silently skipping mid-size files (better detection, aligns the two limits), but those files now get chunked and sent to the LLM, so it is a real resource and spend change, noted in the docs.
The ingest layer (the one I would prioritize). Out of scope for this PR but tracked now at #131: _download_file buffers the full response.content (input_handler.py:159), _extract_zip calls zf.extractall with no uncompressed-size or file-count budget (input_handler.py:182), and the shallow clone has a 60s timeout but no post-clone size cap (input_handler.py:131), so a multi-GB download or a decompression bomb defeats the 50 MiB per-file gate before it runs (zipfile sanitises member names, so DoS not path traversal). The README note makes clear the 50 MiB figure is a per-file analysis limit, not an ingest limit.
_count_lines counting only \n: acknowledged, documented, not security-relevant; happy to switch to a splitlines-equivalent if you would prefer parity.
Whenever you get a chance, this one is ready for another look. I split it down to just the per-file read bounding as you asked, moved the env parsing to a lazy, defensive helper so that an empty or non-numeric value falls back to the default rather than crashing at import, and rebased onto current main now that #6 has landed, so the earlier dirty state is gone. The Pydantic structured-output change went out on its own as #133 (merged), with the rationale you wanted. No rush, just flagging that the three blockers from the 06-21 review are all handled now.
@wernerkasselman-au - Please address review comments and resolve merge conflicts
Hi @rng1995,
Closing this one myself rather than rebasing it, and splitting out the part that is still true. Reasoning, so the history is clear.
This PR has been overtaken. It is based on a5092dd (the #85 era). Since
then main has put roughly +1,700/-170 into the exact six source files it
touches, and the change that matters is architectural: the inspection ledger.
build_context was reorganised around discovery and cache events, OMS
signature scoping, symlink-safe _read_text_no_follow, and a prewarmed AST
cache; static_runner.MAX_FILE_BYTES became
MAX_FILE_CHARS = MAX_PYTHON_AST_SOURCE_CHARS.
More importantly, main answered the original concern a different way, and I
think the better way. Your first review asked that a file large enough to be
skipped must not come back reported as "safe". This PR answered that by failing
closed and aborting the scan. main answers it by skipping and recording:
LedgerOutcome.SKIPPED with LedgerReason.SIZE_LIMIT, carrying
observed_characters / limit_characters / observed_bytes, emitted from
static_runner, behavioral_ast, behavioral_taint_tracking, and
static_yara. An oversized file now shows up as explicitly not-analyzed and
counts against analysis_completeness, which gets the honesty guarantee
without letting one big file abort a whole scan. Rebasing this PR would mean
re-imposing an abort policy over a mechanism you have already shipped, against
a subsystem that did not exist when I wrote it. That is not a rebase, it is a
different PR with a worse premise.
The ingest half is also done: #131 is closed and INGEST_MAX_BYTES /
INGEST_MAX_ZIP_MEMBERS landed in #164.
One finding from this PR is still live on current main, and I have opened
it as #377. _read_file_cache() still calls _read_text_no_follow(), which
does an unbounded source.read(), on every component. INGEST_MAX_BYTES does
not reach it (that budget is scoped to remote and archive ingest, and a local
directory goes through validate_local_input_path(), which does no sizing), so
a local directory scan still materialises a multi-GB file whole before any
analyzer skips it.
#377 is deliberately small and follows your convention rather than mine: it
stats before reading, reuses the stat already taken for the S_ISREG check,
and emits a SIZE_LIMIT ledger event instead of raising. The bound is derived
from the largest character budget downstream rather than picked, so it provably
cannot exclude content any consumer would have accepted.
Nothing here is lost, and I am happy to reopen if you would rather I rework this one in place.
Thanks for the review time you put into it.
Werner