Skip to content

MM-69725: Add adversarial tests and fixes - #6

Merged
agarciamontoro merged 5 commits into
masterfrom
adversarial.tests
Jul 28, 2026
Merged

agarciamontoro merged 5 commits into
masterfrom
adversarial.tests

Conversation

@agarciamontoro

Copy link
Copy Markdown
Member

Summary

Get both #4 and #5 into master.

Ticket Link

https://mattermost.atlassian.net/browse/MM-69725

jgheithcock and others added 2 commits July 24, 2026 13:23
* Additional tests for problematic PDFs

* MM-69725: Address fixture test review feedback

Avoid counting retained plaintext in allocation probes, preserve depth-limit
errors for assertions, and align the fixture tooling defaults and failures.
* Propagate ctx through lexer reload and CMap parsing

The buffer.reload() method is called for every chunk read from a stream,
but previously had no way to respect context cancellation. A malicious
PDF with a huge ToUnicode CMap or a giant literal string token could hold
the goroutine indefinitely even after the caller cancelled.

Changes:
- Add ctx field to buffer; reload() checks it before each read so
  long tokens and stream decodes stay cancellable.
- Thread ctx through Interpret → buffer so PostScript streams
  (CMap, content) honor cancellation at the lexer level.
- Add internal Font.encoder(ctx) / getEncoder(ctx) / charmapEncoding(ctx)
  and readCmap(ctx, …) so ToUnicode CMap parsing uses the caller's ctx
  instead of context.Background().
- GetPlainText and Content now call encoder(ctx) so the full extraction
  path is cancellable end-to-end.

* Cap Predictor Columns to prevent large up-front alloc

applyFilter allocates a ~2×Columns-byte buffer before any content is
read. A malicious PDF with a huge Columns value (e.g. 2^31-1) would
cause a multi-GB allocation before cancellation or EOF.

Add maxPredictorColumns = 1<<20 (1M columns, well above any real
image scanline or xref stream) and panic with a clear error if the
value is out of range.

Also update adversarial_pdfs/README.md to reflect the "gap under test"
framing and add a probe command for manual testing.

* Cap literal string tokens and fix AcroForm alloc threshold

String token cap:
readLiteralString and readHexString accumulate the entire token into a
growing slice with no upper bound. A malicious PDF can embed a huge
(...) or <...> string — either raw on disk or compressed via FlateDecode
— forcing an unbounded allocation before any cancel poll fires.
Add maxStringBytes = 128 MiB and panic with a clear error if either
accumulator exceeds it.

AcroForm test threshold:
The hardcoded 8 MiB limit in TestAdversarial_AcroFormStaysCheap was
calibrated for the medium-scale fixture (~2 MB, 10 K fields). At large
scale (50 K fields, ~9.4 MB), xref-table parsing allocates proportional
to object count, so the threshold must scale with the fixture. Use
len(data) + 2 MiB instead.

* Fix nested_content depth at small scale

depth=200 is below maxObjectDepth=1000, so the depth-limit test never
triggered at small scale. The fixture is a few KB regardless of depth,
so use 1200 (same as medium/large) across all scales.

* Convert Python script into Go

* Remove development tools and documents

* Add CI step to run adversarial tests

* Run CI on push to master, and all on PRs
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cd5ff1ef-78da-4965-aca3-f1d028b1ef81

📥 Commits

Reviewing files that changed from the base of the PR and between 106c9a3 and 90a69c6.

📒 Files selected for processing (3)
  • adversarial_extract_test.go
  • lex.go
  • page.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • lex.go

📝 Walkthrough

Walkthrough

PDF extraction now propagates cancellation through parsing and font decoding, limits oversized strings and predictor allocations, reports nesting-limit errors consistently, and adds generated adversarial fixtures with tagged tests and CI execution.

Changes

Adversarial extraction safeguards

Layer / File(s) Summary
Parser cancellation and allocation guards
lex.go, read.go
Parsing observes context cancellation, limits string token sizes, standardizes nesting-depth errors, and caps predictor columns.
Context-aware page extraction
ps.go, page.go
Page text and content extraction pass contexts through font and CMap decoding while preserving recovered errors.
Adversarial fixture generation
tools/gen_adversarial_pdfs/main.go, tools/adversarial_pdfs/.gitignore
A CLI generates scaled PDFs covering large CMaps, strings, compressed streams, operators, AcroForm fields, and nested content.
Adversarial test and CI execution
adversarial_extract_test.go, .github/workflows/ci.yml
Tagged tests enforce cancellation, allocation, extraction, and nesting contracts; CI generates fixtures and runs them.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant GetPlainText
  participant FontEncoder
  participant Interpret
  participant Buffer
  GetPlainText->>FontEncoder: decode ToUnicode CMap with context
  FontEncoder->>Interpret: Interpret(context)
  Interpret->>Buffer: assign context
  Buffer-->>Interpret: return cancellation error
  Interpret-->>GetPlainText: propagate recovered error
Loading

Possibly related PRs

  • mattermost/pdf#2: Updates the PDF extraction pipeline to propagate context.Context.
  • mattermost/pdf#4: Adds the related adversarial extraction tests and fixture tooling.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: adding adversarial tests and related fixes for PDF parsing.
Description check ✅ Passed The description is related to the PR scope, saying it merges the two related changes into master.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch adversarial.tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@adversarial_extract_test.go`:
- Line 33: Update the missing-fixtures failure message in the adversarial
fixture test to direct users to run the Go generator via `go run
./tools/gen_adversarial_pdfs ...`, replacing the nonexistent Python script
reference while preserving the existing directory and error details.
- Around line 63-72: Update the timeout test flow around GetPlainText and the
affected setup at lines 100–121 so cancellation is triggered only after an
instrumented reader confirms parsing has begun and content has been consumed.
Measure cancellation latency and allocations from that confirmation point, and
replace the fixed 5ms wall-clock assertion with a deterministic check that
avoids CI timing flakiness while still verifying cancellation behavior.

In `@lex.go`:
- Around line 41-44: Update readLiteralString so the maxStringBytes limit is
checked after every append to tmp, including escaped characters and
nested-parenthesis content, rather than only in the default branch. Preserve the
existing limit error behavior and ensure all append paths cannot grow tmp beyond
the cap.

In `@page.go`:
- Line 417: Make cancellation cooperative throughout page text processing: in
page.go lines 417-417, add ctx.Err() checks inside the endcodespacerange,
endbfchar, and endbfrange mapping loops and propagate cancellation as an error;
in page.go lines 611-611, update Page.GetPlainText to use the context-aware
decode path; in page.go lines 1010-1010, make Page.Content use that same
context-aware decoding path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a1f744cc-beac-4967-bd1e-e9a1022ab9af

📥 Commits

Reviewing files that changed from the base of the PR and between 9173490 and 106c9a3.

📒 Files selected for processing (8)
  • .github/workflows/ci.yml
  • adversarial_extract_test.go
  • lex.go
  • page.go
  • ps.go
  • read.go
  • tools/adversarial_pdfs/.gitignore
  • tools/gen_adversarial_pdfs/main.go

Comment thread adversarial_extract_test.go Outdated
Comment thread adversarial_extract_test.go
Comment thread lex.go
Comment thread page.go
maxStringBytes was only checked in readLiteralString's default
branch. Escaped characters, octal escapes, and nested-parenthesis
bytes all append to tmp through other branches, so a payload built
from those (e.g. repeated \n escapes) could still grow the token
past the cap before ever tripping the check. Move the check to run
once per loop iteration, after the switch, so every append path is
bounded the same way.
Interpret only polls ctx between tokens, but readCmap's
end{codespacerange,bf{char,range}} handlers each loop n times within a
single token callback, where n comes straight from an
attacker-controlled int64 on the stack. A malicious ToUnicode CMap can
set n arbitrarily high, turning one callback into an unbounded busy loop
that no cancellation can interrupt. Check ctx.Err() on each iteration
and bail out via the existing ok=false path so these loops stay
cooperative with a canceled context.
Fix the outdated mention to the Python script.

The four cancel-cheaply tests used a fixed 200us context timeout that,
measured against unrestricted runs taking 10-340ms, was expiring before
GetPlainText ever reached the fixture's adversarial content. The tests
were passing by canceling before parsing started, not by exercising
cancellation mid-parse.

Replace the fixed timeout with contentStreamTrigger, an io.ReaderAt
wrapper that cancels only after it observes a run of consecutive,
sequentially-offset reads: the signature of the lexer actually
streaming through a stream's bytes, as opposed to the scattered
small reads used to resolve the xref table, page tree, and fonts.
Cancellation latency and allocations are then measured from that
confirmed point forward, giving a deterministic signal instead of
one that races an arbitrary deadline against unrelated setup cost.
@jgheithcock

Copy link
Copy Markdown

/update-branch

@mattermost-build

Copy link
Copy Markdown

Error trying to update the PR.
Please do it manually.

@agarciamontoro
agarciamontoro merged commit cd8a834 into master Jul 28, 2026
2 checks passed
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.

3 participants