Originally created by: shamario13
Comprehensive security hardening based on a full audit of the codebase. Fixes span four severity levels: HIGH, MEDIUM, LOW, and INFORMATIONAL.
analysing_pathFiles: pdf_craft/common/folder.py, pdf_craft/common/asset.py, pdf_craft/transform.py
When pdf-craft is wrapped in a service that accepts a user-controlled analysing_path, an attacker could point it at an arbitrary writable location (e.g. /var/www/html/), causing the OCR pipeline to write files outside the intended working directory.
assert_within_root(path, root) helper that resolves both paths before comparing (symlinks and .. components cannot bypass it)EnsureFolder with an optional safe_root parameter that validates analysing_path before any directory is createdsafe_root parameter to transform_markdown and transform_epub (backward-compatible, defaults to None)Resolved AssetHub._asset_path to an absolute canonical path at construction time
:::python
transform.transform_markdown(
pdf_path=user_pdf,
markdown_path=out_md,
analysing_path=user_supplied_path, # untrusted
safe_root=/var/app/workdir, # enforced boundary
)
Files: .github/workflows/merge-build.yml, .github/workflows/pr-check.yml
Floating version tags (@v4, @v5, @v3) allow a tag-hijack on any of these actions to run attacker-controlled code in CI with full GITHUB_TOKEN access. Pinned all three to full commit SHAs:
actions/checkout → 34e114876b0b11c390a56381ad16ebd13914f8d5 (v4)actions/setup-python → a26af69be951a213d495a4c3e4e4022e16d87065 (v5)abatilo/actions-poetry → fd0e6716a0de25ef6ade151b8b53190b0376acfd (v3)File: pdf_craft/llm/core.py
Log files contain verbatim PDF text and were created with the process umask (typically world-readable on multi-user systems). Added os.chmod(file_path, 0o600) after FileHandler creation on POSIX systems.
Files: scripts/gen_md.py, scripts/gen_epub.py
Both scripts now check the PDF_CRAFT_API_KEY environment variable first and fall back to format.json only if it is not set, providing a safer alternative to storing credentials on disk.
File: pdf_craft/toc/llm_analyser.py
PDF-extracted heading and TOC text was embedded verbatim into LLM prompts. Wrapped all PDF-derived text in <text>...</text> delimiters and updated both system prompts to instruct the model that only content inside those tags is PDF data.
Files: pdf_craft/common/xml.py, pyproject.toml
Replaced xml.etree.ElementTree.fromstring with defusedxml.ElementTree.fromstring throughout. Added defusedxml>=0.7.1 as a dependency.
Image.crop()File: pdf_craft/sequence/chapter.py
_parse_det() now rejects negative values and degenerate bounding boxes (x1 >= x2 or y1 >= y2) before they reach Pillow's Image.crop().
File: pdf_craft/pdf/page_ref.py
A PDF with unrealistically large declared page dimensions could produce an unbounded DPI value, causing Poppler to attempt excessive memory allocation. Added _MAX_DPI = 600 cap in _dpi_with_size().
save_xml()File: pdf_craft/common/xml.py
Replaced the fixed .xml.tmp suffix with tempfile.mkstemp(dir=file_path.parent), giving each writer a unique random name while keeping the write-then-rename atomic (same directory = same filesystem).
File: pdf_craft/llm/context.py
Changed uuid4().hex[:12] (48-bit) to uuid4().hex (128-bit). No reason to truncate.
has_repetitive_ngrams()File: pdf_craft/pdf/ngrams.py
Replaced per-comparison tuple(chars[i:i+n]) creation (O(n) per comparison) with a Rabin-Karp rolling hash. N-gram comparisons are now O(1) (hash check) with O(n) string verification only on hash matches, eliminating the CPU spike risk from crafted OCR output.
File: pdf_craft/common/xml.py
Added a _MAX_XML_BYTES = 100 MB gate in read_xml() that checks file_path.stat().st_size before reading the file into memory, preventing OOM from unexpectedly large intermediate files.
json-repair silently reconstructed malformed LLM outputFile: pdf_craft/toc/llm_analyser.py
Removed the json-repair dependency entirely. Both _validate_title_response and _validate_toc_response now use strict json.loads() — malformed JSON in the RESULT section triggers a model retry with a descriptive error message instead of being silently reconstructed (which could mask prompt-injection payloads). Also removed json-repair from pyproject.toml.
transform_markdown / transform_epub with analysing_path inside safe_root — works normallyanalysing_path outside safe_root — raises ValueError before any filesystem writessafe_root — no behavioural change (backward-compatible)det attribute with negative or degenerate values — ValueError raised at parse timelog_dir_path set — chmod 600 on POSIX, owner-only readablePDF_CRAFT_API_KEY env var set — scripts use it instead of format.json key🤖 Generated with Claude Code
Originally posted by: coderabbitai[bot]
Walkthrough
This PR adds multiple safety and behavior changes across the codebase: it enforces path containment via a new assert_within_root and EnsureFolder.safe_root (wired through Transform.transform_markdown/transform_epub), normalizes AssetHub paths with Path.resolve(), tightens XML parsing and atomic save behavior, implements rolling-hash n-gram repetition detection, caps computed DPI, validates rectangle coordinates, updates LLM prompts and strict JSON parsing, allows runtime LLM key overrides, tightens per-request logfile permissions, and pins CI action versions.
Sequence Diagram(s)
Possibly related PRs
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
| Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ✅ Passed | The title follows the required format with type and subject, and is closely related to the main security improvement: adding a safe_root path traversal guard. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Description check | ✅ Passed | The pull request description comprehensively relates to the changeset, detailing security hardening across multiple severity levels with clear file-by-file mapping. |✨ Finishing Touches
✨ Simplify code
- [ ] Create PR with simplified codeThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)Comment
@coderabbitai helpto get the list of available commands and usage tips.