Skip to content

feat(loader): add path traversal protection - #16

Closed
robcohen wants to merge 1 commit into
mainfrom
feat/path-security
Closed

robcohen wants to merge 1 commit into
mainfrom
feat/path-security

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

  • Add security feature to prevent malicious ledger files from accessing files outside the ledger directory
  • New with_path_security(bool) method to enable/disable protection
  • New with_root_dir(PathBuf) method to set custom root directory
  • New PathTraversal error variant for security violations

Motivation

This protects against attacks where a crafted .beancount file uses relative paths like include "../../../etc/passwd" to escape the intended directory.

Test plan

  • Unit tests for path traversal detection
  • Test that valid relative includes still work
  • Test custom root directory configuration

🤖 Generated with Claude Code

Add security feature to prevent malicious ledger files from accessing
files outside the ledger directory via include directives.

- Add `with_path_security(bool)` to enable/disable protection
- Add `with_root_dir(PathBuf)` to set custom root directory
- Add `PathTraversal` error variant for security violations
- Includes are validated to stay within the root directory

This protects against attacks where a crafted .beancount file uses
relative paths like `include "../../../etc/passwd"` to escape the
intended directory.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

// Set root directory for path security if enabled but not explicitly set
if self.enforce_path_security && self.root_dir.is_none() {
self.root_dir = canonical.parent().map(Path::to_path_buf);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 Security Issue: Path traversal protection bypass when main file is at filesystem root. When loading a file like '/ledger.beancount', canonical.parent() returns Some('/'), setting root_dir to '/'. Since all absolute paths start with '/', the security check at line 295 (!canonical.starts_with(root)) always passes, allowing unrestricted file access across the entire filesystem.

Severity: HIGH
Category: path_traversal
Tool: ClaudeCode AI Security Analysis

Exploit Scenario: An attacker who can control where the main beancount file is loaded from (e.g., through a web interface or configuration) could place it at the root directory. The file '/ledger.beancount' could then include sensitive files like 'include "etc/passwd"' or 'include "home/user/.ssh/id_rsa"'. Since root_dir would be '/' and all paths start with '/', the security check would pass, granting access to any readable file on the system.

Recommendation: Add validation to reject loading files from the filesystem root, or implement a minimum depth requirement. Consider: if canonical.parent() == Some(Path::new("/")) { return Err(LoadError::SecurityViolation { msg: "Cannot load files from filesystem root" }); }. Alternatively, use a more robust containment check that handles the root directory case explicitly.

@robcohen

Copy link
Copy Markdown
Member Author

Recreating with correct branch name

@robcohen robcohen closed this Jan 10, 2026
@robcohen
robcohen deleted the feat/path-security branch January 13, 2026 15:55
robcohen added a commit that referenced this pull request Jun 20, 2026
CI clippy (--all-targets) flagged clippy::match_wildcard_for_single_variants
in the new test; use a refutable let-else instead of a wildcard match arm.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jun 20, 2026
* fix(query): name the offending token instead of mislabeling trailing input as EOF

The query parser classified a parse error as "unexpected end of input"
whenever `found()` was `None`. But chumsky's `end()` combinator — which
rejects leftover tokens after a valid prefix — also reports `found() ==
None`, so `SELECT … GROUP BY account WHERE …` and `SELECT account FOOBAR`
were both labeled EOF even though the error span pointed at the real
offending token (WHERE / FOOBAR).

Classify by the error span instead: a position at or past the end of the
input is a genuine EOF; otherwise name the unexpected token at that
position.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(review): avoid clippy match-wildcard lint in the #16 test

CI clippy (--all-targets) flagged clippy::match_wildcard_for_single_variants
in the new test; use a refutable let-else instead of a wildcard match arm.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(review): preserve chumsky messages + test_ prefix

Addresses Copilot on #1453:
- Only disambiguate EOF-vs-trailing-token in the found()==None case; when
  chumsky reports a concrete token, keep its richer message (e.to_string()).
- Rename the test to the test_ prefix used by the rest of the module.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 23, 2026
#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
robcohen added a commit that referenced this pull request Jul 23, 2026
* test(returns): messy-imported-ledger suite; correct query returns docs

#1850 §6 (with §5 edge cases): a suite exercising net-units returns over the
imperfect/imported ledgers this effort targets, through the SHARED
scope_returns/scopes_returns composition (the exact path the CLI and the WIT
component take), so it also pins real PriceDatabase price resolution.

Cases (crates/rustledger-query/tests/messy_returns_test.rs):
- over-sell of an empty-cost {} lot → net −5, valued at market (−600), tolerated;
- missing opening buy (importer started mid-history) → short net position;
- clean empty-cost {} reduction → net units valued identically;
- falling prices → a real NEGATIVE money- and time-weighted rate (beangrow
  CRASHES here — beangrow#4 / #16; our Newton+Brent xirr returns Option<f64>);
- near-total loss → defined large-negative rate, no crash;
- missing intermediate price (late first price) → MWR computes from cash flows +
  priced terminal, TWR degrades to None (not an error) — the §5 missing-price
  policy;
- per-scope isolation: an elided in-scope scope fails alone (UnbookedInput) while
  a clean scope computes, over one shared accumulation (what --by-group relies on).

Also corrects the scope_returns/scopes_returns doc comments (§2), which still
carried the #1849 strict-clean language — now contradicted by the net-units
model: cost-basis/lot errors are tolerated, and UnbookedInput is PER-SCOPE, not a
whole-ledger abort.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

* docs(returns): fix scope_returns booked wording + elided-error contract (review 2)

Second review pass doc drift, query composition root:
- scope_returns summary said "from a booked, pad-expanded stream" -> interpolated
  (booking not required; net units valued at market).
- scope_returns/scopes_returns # Errors described UnbookedInput as firing only for
  an in-scope elided holding; the elided-external-leg fix also fires it for an
  external boundary leg (unknown cash flow), so both now name BOTH shapes.

Doc-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
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.

1 participant