Skip to content

Harden PDF/A and PDF/X conformance, memory safety, and Rust bounds checks - #295

Open
balazs-szucs wants to merge 11 commits into
fix/pdf-repair-engine-hardeningfrom
fix/pdfa-pdfx-conformance-and-safety
Open

balazs-szucs wants to merge 11 commits into
fix/pdf-repair-engine-hardeningfrom
fix/pdfa-pdfx-conformance-and-safety

Conversation

@balazs-szucs

@balazs-szucs balazs-szucs commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Description of Changes

Applies ISO 19005 (PDF/A), ISO 15930 (PDF/X), C++ memory-safety, and Rust bounds-checking fixes across the native bridge and Java pipeline. Fixes /CIDSet bitmask generation on re-subsetted CID/SFNT/CFF fonts per ISO 19005-2 §6.2.11.4.2, leaves XMP Metadata uncompressed for PDF/A-1, enforces integer/iterator bounds in C++ and Rust, and cleans up test formatting.

Changed:

  • Compute /CIDSet directly from retained PostScript/CFF/SFNT subset glyphs via reloaded FreeType sub-faces in jpdfium_font_normalizer.cpp, jpdfium_qpdf_fonts_embed.cpp, and jpdfium_qpdf_fonts_subset.cpp.
  • Enforce uncompressed XMP Metadata streams, preserve output intents and PDF/X color invariants across jpdfium_color.cpp, jpdfium_pdfx.cpp, jpdfium_qpdf_sanitize.cpp, PdfCompressor.java, and PdfXConverter.java.
  • Harden lifetime/bounds checks across jpdfium_internal.h, jpdfium_qpdf_internal.h, jpdfium_advanced.cpp, jpdfium_pattern.cpp, jpdfium_qpdf_pages.cpp, jpdfium_redact.cpp, jpdfium_render.cpp, jpdfium_sanitize.cpp, jpdfium_signature.cpp, and native/rust/jpdfium-impl/src/lib.rs.
  • Move the PDF/A conformance production changes from PR Add real veraPDF ISO 19005 PDF/A conformance validation tests #297 into this PR: PdfRepair, PdfFontEmbedder, PdfFontAuditor, font normalizer/shared/subset/embed, and repair tokenization.
  • Update PdfTestAssertions.java, SaveTransportTest.java, FontNormalizerTest.java (ISO 19005-2 /CIDSet), and RedactionSessionTest.java.

Checklist

General

  • I have read the Contributing Guide
  • I have performed a self-review of my own code
  • My changes generate no new warnings
  • Notable user-facing changes are recorded under ## [Unreleased] in CHANGELOG.md

Library changes

  • Javadoc covers any new or changed public type or member
  • Public API changes are additive, or .github/workflows/compatibility.yml excludes the break with a reason
  • Version references stay consistent across the README, docs/installation.md, and the POMs

Native or FFM changes

  • Rebuilt the bridge at the stack tip (bash native/build-real.sh)
  • Ran ./gradlew :jpdfium:integrationTest
  • Updated native/bridge/include/jpdfium.h and the ABI notes for any ABI change

Testing

  • Added or updated tests that cover the change
  • ./gradlew :jpdfium:integrationTest passes

@coderabbitai

coderabbitai Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Explain Change →

Summary

Summary by CodeRabbit

  • New Features
    • PDF repair can recover more malformed or truncated documents, preserve clean signed PDFs, and report when a usable repair isn’t possible.
    • Font tools can identify damaged embedded fonts and improve font replacement and normalization.
  • Bug Fixes
    • PDF/A and PDF/X processing better respects format requirements, including object-stream settings and page-box boundaries.
    • Compression, sanitization, redaction, and PDF conversion handle more edge cases and malformed data reliably.
    • Text and pattern matching results are serialized more reliably, while PDF metadata and font mappings are handled more safely.
    • Invalid or missing output buffers are handled more safely across PDF operations.

The pull request updates PDF font processing, repair, PDF/A and PDF/X conversion, compression, sanitization, pattern APIs, and native API checks. It also adds PDF byte-comparison helpers and updates related tests and security scanner configuration.

Changes: Font processing

Layer / File(s) Summary
Font inspection and embedding
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java, jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java, native/bridge/src/jpdfium_qpdf_fonts_embed.cpp, native/bridge/src/jpdfium_qpdf_fonts_subset.cpp, jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderTest.java
Font auditing and embedding use visible text, codepoint coverage, configured font paths, and embedded-program validity. Native embedding preserves inherited mappings and derives CID sets from embedded font programs. Tests cover invisible text and non-renderable codepoints.
Font normalization and cmap repair
native/bridge/include/jpdfium_font_internal.h, native/bridge/include/jpdfium_qpdf_internal.h, native/bridge/src/jpdfium_font_normalizer.cpp, native/bridge/src/jpdfium_font_shared.cpp, jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
Native normalization repairs font widths, encodings, Type 1 lengths, CID metadata, cmap tables, and CID sets. Tests update CIDSet expectations to exclude CID 0.

PDF repair

Layer / File(s) Summary
Repair input checks and result selection
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java, native/bridge/src/jpdfium_repair.cpp, jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
The repair flow handles signed and password-blocked documents, prepares input, validates repair stages, and accepts or compacts output only when it meets page checks. Tests cover malformed nesting and salvage cases.
PDF token and page-tree reconstruction
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
Repair helpers normalize malformed tokens, rebuild page trees from page dictionaries, and restore trailer references during truncated-file salvage.

PDF/A and PDF/X output

Layer / File(s) Summary
PDF/A recognition and page boxes
jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java, jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
PDF/A detection recognizes single-quoted claims and applies PDF/A-1 object-stream settings. Java page-box handling clamps boxes to the MediaBox.
PDF/X writer and metadata configuration
native/bridge/src/jpdfium_color.cpp, native/bridge/src/jpdfium_qpdf_pages.cpp
PDF/X writer settings select output versions and object-stream behavior. Metadata parsing, date conversion, catalog version handling, and changed-page tracking are also updated.
PDF/X resource conversion and audit
native/bridge/src/jpdfium_pdfx.cpp
PDF/X processing converts additional color spaces and shading, checks resource and annotation structures, removes selected actions and files, and clamps page boxes.

Rust PDF compression and conversion

Layer / File(s) Summary
Stream compression and input validation
native/rust/jpdfium-impl/src/lib.rs
Compression handles additional Flate stream forms, skips metadata streams, and retains filtered data when recompression does not reduce its size. C-ABI pointer checks and pixel-buffer validation are updated, with tests for stream integrity.

Pattern API JSON handling

Layer / File(s) Summary
Pattern JSON parsing and output
native/bridge/src/jpdfium_pattern.cpp
PCRE2 and FlashText results use JSON string escaping. FlashText parsing handles quoted content and object bounds, and result pointers are initialized and checked.

PDF sanitization and byte comparisons

Layer / File(s) Summary
Sanitization and output handling
native/bridge/src/jpdfium_sanitize.cpp, native/bridge/src/jpdfium_qpdf_sanitize.cpp
Sanitization updates CMap and document-structure handling, validates PDF values, and checks output buffers. File output uses scoped stream ownership.
Serialized PDF comparison tests
jpdfium/src/test/java/stirling/software/jpdfium/PdfTestAssertions.java, jpdfium/src/test/java/stirling/software/jpdfium/SaveTransportTest.java, jpdfium/src/test/java/stirling/software/jpdfium/redact/RedactionSessionTest.java
Test helpers compare PDF bytes outside validated trailer ID ranges. Save and redaction tests use these helpers.

Native API and resource checks

Layer / File(s) Summary
Native ownership and API validation
native/bridge/include/jpdfium_internal.h, native/bridge/src/jpdfium_advanced.cpp, native/bridge/src/jpdfium_redact.cpp, native/bridge/src/jpdfium_render.cpp, native/bridge/src/jpdfium_signature.cpp, native/bridge/src/jpdfium_qpdf_pages.cpp
Native document ownership is explicit. Buffer, signature, and version-forcing paths validate or configure their output handling.

Security scanner configuration

Layer / File(s) Summary
OSV scanner configuration
.github/workflows/security.yml, osv-scanner.toml
The security workflow passes the scanner configuration file. The configuration lists RUSTSEC-2026-0543 as ignored with a tracking explanation.

Possibly related issues

  • Stirling-Tools/JPDFium#191: The changes address parts of the issue’s PDF/A and PDF/X metadata and conformance concerns, but do not cover the full operation matrix.

Possibly related PRs

Change: Bug fix

Merge Risk: Moderate · up to 097a8

The change broadens PDF/A, PDF/X, repair and font normalization behavior. Several open edge cases can silently alter output, such as tiling-pattern spacing, repaired page trees, font mappings and ToUnicode maps. Resolve or consciously accept these before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names PDF/A and PDF/X conformance, memory safety, and Rust bounds checks. The changeset covers all three areas: CIDSet and XMP metadata changes for PDF/A, PDF/X box and color changes, C++ li…
Description check Passed The description follows the template structure: it has the Description of Changes section and the Checklist with General, Library, Native/FFM, and Testing subsections. It explains the main changes (CI…
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.
Full details: Title check

Explanation

The title names PDF/A and PDF/X conformance, memory safety, and Rust bounds checks. The changeset covers all three areas: CIDSet and XMP metadata changes for PDF/A, PDF/X box and color changes, C++ lifetime and bounds hardening, and Rust bounds checks in lib.rs. The title is slightly broad and long (73 characters), but it names the main changes accurately.

Full details: Description check

Explanation

The description follows the template structure: it has the Description of Changes section and the Checklist with General, Library, Native/FFM, and Testing subsections. It explains the main changes (CIDSet computation, XMP metadata, bounds hardening, moved PR #297 changes) and lists the test updates. The changelog item under [Unreleased] is unchecked, and the description does not mention a Closes #issue reference. The description also marks the integrationTest run as passing while the template's ./gradlew test item is not checked.

Resolution

Record the user-facing changes under ## [Unreleased] in CHANGELOG.md and check that item, or state why no entry is needed. Add a Closes #(issue number) line if an issue exists. Confirm whether ./gradlew test passes, since the description only reports :jpdfium:integrationTest.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks 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

@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: 36

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 35b022b and f2358a9.

Files selected for processing: 28

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
  • jpdfium/src/test/java/stirling/software/jpdfium/PdfTestAssertions.java
  • jpdfium/src/test/java/stirling/software/jpdfium/SaveTransportTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/redact/RedactionSessionTest.java
  • native/bridge/include/jpdfium_font_internal.h
  • native/bridge/include/jpdfium_internal.h
  • native/bridge/include/jpdfium_qpdf_internal.h
  • native/bridge/src/jpdfium_advanced.cpp
  • native/bridge/src/jpdfium_color.cpp
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_font_shared.cpp
  • native/bridge/src/jpdfium_pattern.cpp
  • native/bridge/src/jpdfium_pdfx.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_embed.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_subset.cpp
  • native/bridge/src/jpdfium_qpdf_pages.cpp
  • native/bridge/src/jpdfium_qpdf_sanitize.cpp
  • native/bridge/src/jpdfium_redact.cpp
  • native/bridge/src/jpdfium_render.cpp
  • native/bridge/src/jpdfium_repair.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
  • native/bridge/src/jpdfium_signature.cpp
  • native/rust/jpdfium-impl/src/lib.rs
Files with no reviewable changes: 1

  • native/bridge/include/jpdfium_qpdf_internal.h

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Review details

Context from checks skipped due to timeout: 1

  • GitHub Check: CodeRabbit
Additional context used

Code guidelines: 1

.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 4

Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • native/bridge/include/jpdfium_font_internal.h
  • native/bridge/include/jpdfium_internal.h
  • native/bridge/src/jpdfium_advanced.cpp
  • native/bridge/src/jpdfium_color.cpp
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_font_shared.cpp
  • native/bridge/src/jpdfium_pattern.cpp
  • native/bridge/src/jpdfium_pdfx.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_embed.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_subset.cpp
  • native/bridge/src/jpdfium_qpdf_pages.cpp
  • native/bridge/src/jpdfium_qpdf_sanitize.cpp
  • native/bridge/src/jpdfium_redact.cpp
  • native/bridge/src/jpdfium_render.cpp
  • native/bridge/src/jpdfium_repair.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
  • native/bridge/src/jpdfium_signature.cpp
Enforce meaningful assertions, deterministic concurrency, failure-path cleanup, and explicit native/stub requirements.

CodeRabbit configuration file

Files:

  • jpdfium/src/test/java/stirling/software/jpdfium/PdfTestAssertions.java
  • jpdfium/src/test/java/stirling/software/jpdfium/SaveTransportTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/redact/RedactionSessionTest.java
Apply the Java 25 and FFM rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
  • jpdfium/src/test/java/stirling/software/jpdfium/PdfTestAssertions.java
  • jpdfium/src/test/java/stirling/software/jpdfium/SaveTransportTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/redact/RedactionSessionTest.java
Source excerpt: These rules apply to maintained source.

CodeRabbit inference engine (.github/CODERABBIT_REVIEW.md)

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
  • jpdfium/src/test/java/stirling/software/jpdfium/PdfTestAssertions.java
  • jpdfium/src/test/java/stirling/software/jpdfium/SaveTransportTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/redact/RedactionSessionTest.java
  • native/bridge/include/jpdfium_font_internal.h
  • native/bridge/include/jpdfium_internal.h
  • native/bridge/src/jpdfium_advanced.cpp
  • native/bridge/src/jpdfium_color.cpp
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_font_shared.cpp
  • native/bridge/src/jpdfium_pattern.cpp
  • native/bridge/src/jpdfium_pdfx.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_embed.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_subset.cpp
  • native/bridge/src/jpdfium_qpdf_pages.cpp
  • native/bridge/src/jpdfium_qpdf_sanitize.cpp
  • native/bridge/src/jpdfium_redact.cpp
  • native/bridge/src/jpdfium_render.cpp
  • native/bridge/src/jpdfium_repair.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
  • native/bridge/src/jpdfium_signature.cpp
  • native/rust/jpdfium-impl/src/lib.rs
Learnings: 2

Learning: 2026-10-31T10:47:27.879Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-31T10:47:27.879Z
Learning: Source excerpt:
# JPDFium review standards

## Java 25 style

- Remove unused imports, raw types, dead branches, redundant casts, unnecessary wrappers, and duplicated helpers.

Applied to files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
Learning: 2026-10-20T15:53:18.441Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-20T15:53:18.441Z
Learning: Source excerpt:
# JPDFium review standards

## Comments and documentation

- Keep ordinary inline comments to one or two concise sentences. Longer public contracts and subtle ABI/lifetime explanations are justified; do not shorten them until ambiguity remains.

Applied to files:

  • native/bridge/src/jpdfium_pattern.cpp
ast-grep (0.51.1)

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java

[warning] 1184-1184: Use a randomly-generated IV
Context: byte[] tail = (trailer + "%%EOF\n").getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)

Clippy (1.99.1)

native/rust/jpdfium-impl/src/lib.rs

[warning] 67-67: manual implementation of .is_multiple_of()

(warning)

Additional comments: 2

native/bridge/src/jpdfium_font_shared.cpp: 1

397-398: Data Integrity & Integration

The arithmetic concern is real but its reachability is not established. ensureSfntCmapSubtable narrows the cumulative output offset to uint32_t at native/bridge/src/jpdfium_font_shared.cpp:397 without checking the total. Its per-entry bounds check at line 355 allows duplicated or overlapping directory ranges. When the total exceeds UINT32_MAX, the offsets wrap and later table copies can overwrite earlier output.

Whether a PDF font can trigger this depends on whether the pinned FreeType loader accepts such a directory. The repair callers in native/bridge/src/jpdfium_font_normalizer.cpp:1092-1136 pass the same buffer that backs the loaded face, so an accepted directory would reach this helper. The FreeType sfnt loader is not in the checkout, so that premise cannot be decided here.

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java: 1

587-587: Stability & Availability

Public scan can race document close without admission.

visibleFontKeys obtains the native page segment through rawHandleForRead(), which retains no admission. The page and document close paths do not wait for in-flight raw-handle use. A concurrent PdfDocument.close() can free native state between line 587 and the invokeExact calls. Whether this is a defect depends on the documented threading contract for PdfDocument, which is not established in the inspected source. The same unguarded pattern already exists in other public methods, so this change does not introduce it.

boolean rawPdfa = m.first[N_PDFA_PART] >= 0 || m.first[N_PDFA_PART_ATTR] >= 0
|| m.first[N_PDFA_CONF] >= 0 || m.first[N_PDFA_CONF_ATTR] >= 0
|| m.first[N_PDFA_PART_SQ] >= 0 || m.first[N_PDFA_CONF] >= 0
|| m.first[N_PDFA_CONF_ATTR] >= 0 || m.first[N_PDFA_CONF_SQ] >= 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Resolve the PDF/A part after a conformance-only match.

If compressed catalog XMP claims part 1, an Info string containing pdfaid:conformance='B' now makes rawPdfa true. With no raw part-1 or GTS_PDFA1 marker, this skips metadata decoding and returns 2 instead of the previous 1. Compression then selects object-stream generation and can retain that output when smaller. (raw.githubusercontent.com)

When the raw match does not establish the part, inspect the catalog metadata before selecting the structural policy. Add a regression with this combination.

Comment on lines +597 to +600
} catch (Throwable t) {
NativeRuntime.rethrowFatal(t);
// A page that cannot be walked tells us nothing; do not hide fonts.
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Discard incomplete visibility results.

If page 0 contributes font A and enumeration of page 1 fails, this returns {A}. embedMissing then treats page 1's font B as invisible and skips it. Child-scan failures have the same effect because collectVisibleFonts keeps partial results.

Return an explicit incomplete result, or disable suppression for the whole document after any scan failure. Keep suppression enabled only after a complete scan.

Comment on lines +325 to +326
if (!visibleFonts.isEmpty() && !visibleFonts.contains(key(name))
&& !resourceOnly.contains(name)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Do not classify an unobserved resource as invisible-only.

A page can contain visible font A and an unused font B in /Resources. Inventory gives B a nonempty pages set, so B is not resourceOnly. This condition skips B even when a matching donor exists. Before this change, B reached embedding.

This also affects fonts outside the text/form walk. Suppress a font only when inspection establishes that every use is in rendering mode 3. Preserve the documented embedding of unused resources.

out = QpdfLib.embedFonts(out, found, true, stripSignatures);
}
if (out != null && !corruptFound.isEmpty()) {
out = QpdfLib.embedFonts(out, corruptFound, false, stripSignatures);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Heavy lift

Verify CID mappings before automatic corrupt-font replacement.

For a corrupt Identity-H font whose CID 1 means A, a donor can contain A at GID 36. The coverage check passes, but replacement mode skips prepareMissingCidMapping because the descriptor already has a program. The native path retains /CIDToGIDMap /Identity, so CID 1 renders the donor's GID 1 instead of A.

Use a verified CID-to-donor-GID mapping for corrupt fonts. If the mapping cannot be preserved, leave the font unresolved rather than reporting successful embedding.

Comment on lines +354 to +357
if (*p == '\\' && *(p + 1) && (!limit || p + 1 < limit)) {
++p;
}
value.push_back(*p++);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Quick win

Decode JSON escapes before registering keywords.

For [{"keyword": "caf\u00e9","label":"PERSON"}], this loop registers cafu00e9, not café. Searches for café then return no match. Likewise, \n becomes n instead of a newline.

Decode JSON escapes, including Unicode escapes, before calling addKeyword. Add regressions that verify the resulting matches, while preserving plain strings and escaped quotes.

As per coding guidelines, “Preserve stable public behavior.”

Source: Coding guidelines

if (proc.isDictionary() && proc.hasKey("/ColorSpace")) {
ColourSpaceInfo pinfo = Classify(proc.getKey("/ColorSpace"), depth + 1);
if (pinfo.replacement.isInitialized() && !pinfo.replacement.isNull()) {
proc.replaceKey("/ColorSpace", pinfo.replacement);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Heavy lift

Preserve the DeviceN process-channel contract.

For /Process << /ColorSpace /DeviceRGB /Components [/Red /Green /Blue] >>, this changes /ColorSpace to /DeviceCMYK but retains three component names and the original DeviceN channels. /Components must match the process colour space in count and order. The resulting dictionary violates that contract. (udp.adobe.io)

Preserve the process mapping when supported. Otherwise, reject the conversion until the complete channel model can be converted. Add a regression that checks /ColorSpace, /Components, and rendered output.

As per coding guidelines, “Preserve stable public behavior.”

Source: Coding guidelines

}
QPDFObjectHandle fn = dict.getKey("/Function");
const int inputs = shading_type == 1 ? 2 : 1;
if (fn.isNull() || !ConvertFunction(fn, inputs, cs.kind, cs)) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Heavy lift

Do not convert a shading by transforming only its endpoints.

This newly routes RGB shadings through the Type 2 endpoint rewrite in ConvertFunction. Type 2 functions interpolate between their endpoints. (udp.adobe.io)

For a linear black-to-red gradient without a LUT, the rewritten midpoint is CMYK [0,0.5,0.5,0.5]. Converting the original RGB midpoint with ConvertComponents gives [0,1,1,0.5]. The endpoints agree, but intermediate colours do not.

Compose the original function with the colour transformation, or use a sufficiently sampled replacement. Add a midpoint regression, not only endpoint assertions.

As per coding guidelines, “Preserve public pixel semantics.”

Source: Coding guidelines


Major · Data Integrity & Integration · Heavy lift

Keep failed shading conversion atomic.

For an X1a Lab shading, use a Type 3 function with a Type 2 subfunction followed by a Type 4 subfunction. Stitching functions can combine these function types. (udp.adobe.io)

ConvertFunction changes the first subfunction to four CMYK outputs. It then rejects the Lab Type 4 subfunction. This return leaves the shading's /ColorSpace as Lab while retaining the modified four-output subfunction. Preparation can then publish the inconsistent shading.

Stage the complete function graph and commit only after conversion succeeds. On failure, preserve the original graph or reject preparation. Add a regression that fails after the first subfunction converts.

As per coding guidelines, “Every early return and exception must preserve the documented state and cleanup contract.”

Source: Coding guidelines

ClampPatternSteps(pat);
QPDFObjectHandle pat_dict = pat.isStream() ? pat.getDict() : pat;
if (pat_dict.isDictionary()) {
ClampPatternSteps(pat);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Do not change valid tiling-pattern spacing.

Pattern steps use pattern-space coordinates and need not have magnitude at least one. They must be nonzero. (udp.adobe.io)

For XStep=YStep=0.5, BBox=[0,0,0.5,0.5], and Matrix=[20,0,0,20,0,0], this new call changes both steps to 1. It leaves the cell and matrix unchanged, doubling the repetition distance and introducing gaps.

Preserve valid finite steps. If a renderer cannot support a pattern, reject it instead of silently changing its geometry. Add a rendering regression for fractional steps with a scaling matrix.

As per coding guidelines, “Preserve stable public behavior.”

Source: Coding guidelines

if (!data || data->getSize() < 4) return false;
auto const* b = reinterpret_cast<uint8_t const*>(data->getBuffer());
if (b[0] == 0x00 && b[1] == 0x01 && b[2] == 0x00 && b[3] == 0x00) return true;
if (b[0] == 0x01 && b[1] == 0x00 && b[2] == 0x04 && b[3] == 0x04) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Quick win

Accept valid CFF header variants before scheduling replacement.

A valid CFF program can start with 01 00 04 01; offSize permits values 1 through 4. This predicate rejects that program and emits programValid=false. embedMissing then replaces a valid embedded font or reports it unresolved. Adobe's CFF specification defines these bytes as header fields, not a fixed four-byte magic. (adobe-type-tools.github.io)

Validate the CFF header fields instead. Apply the same correction to PdfFontAuditor.looksLikeFontProgram, and add a regression that preserves a valid CFF with offSize != 4.

@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.

Review continued from previous batch...

assertValidHexSlot(actual, actSlots.firstStart, actSlots.firstEnd, message + " (actual /ID[0])");
assertValidHexSlot(expected, expSlots.secondStart, expSlots.secondEnd, message + " (expected /ID[1])");
assertValidHexSlot(actual, actSlots.secondStart, actSlots.secondEnd, message + " (actual /ID[1])");
assertBytesEqualOutsideRange(expected, actual, expSlots.firstStart + 1, expSlots.secondEnd - 1, message);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Compare the bytes between the two ID strings.

/ID[<AA> <BB>] and /ID[<AA>X<BB>] pass this assertion. All hex validations succeed, but the excluded range also contains the separator and inner delimiters. This lets the transport test accept changes outside the ID digits.

Exclude the two digit ranges separately. Compare the intervening bytes exactly. Add a regression that rejects the changed separator but accepts changed ID digits.

private static TrailerIdSlots findTrailerIdSlots(byte[] pdf) {
int id = -1;
for (int i = pdf.length - 3; i >= 0; i--) {
if (pdf[i] == '/' && pdf[i + 1] == 'I' && pdf[i + 2] == 'D') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Match the actual trailer /ID key.

The reverse scan also matches /IDBackup. With /ID[<00><11>] /IDBackup[<AA><BB>], changing the final <BB> to <CC> passes both public assertions. The scanner selects /IDBackup, so the helpers exempt unrelated bytes instead of the trailer ID.

Locate the exact /ID key in the trailer dictionary and validate its array boundaries. Add a regression with an unchanged real ID and a changed /IDBackup value.

Comment on lines +1433 to +1435
setString("/Registry", "Adobe");
setString("/Ordering", "Identity");
setInt("/Supplement", 0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Heavy lift

Supported by static analysis

Script executed:

sed -n '1386,1495p' native/bridge/src/jpdfium_font_normalizer.cpp
rg -n 'fixCidSystemInfo|repairFontToUnicode|/Ordering' native/bridge/src/jpdfium_font_normalizer.cpp

Repository: Stirling-Tools/JPDFium

Length of output: 5857


Script executed:

sed -n '90,135p' native/bridge/src/jpdfium_font_normalizer.cpp | cat -n
echo ---
sed -n '1596,1616p' native/bridge/src/jpdfium_font_normalizer.cpp | cat -n

Repository: Stirling-Tools/JPDFium

Length of output: 4256


Keep the existing collection for Identity-H and Identity-V descendants.

The Identity branch of fixCidSystemInfo overwrites /Registry, /Ordering, and /Supplement unconditionally. For a descendant that already has an Adobe Japan1 collection, /Ordering changes to Identity before repairFontToUnicode runs. adobeOrderingForCidFont then reads Identity, so the Adobe collection ToUnicode fallback can no longer select the Japan1 table for fonts that lack usable ToUnicode mappings.

The overwrite must not discard a valid existing collection. Resolve the required CIDSystemInfo for Identity CMaps against ISO 19005-2 6.2.11.3.1 before changing the Identity branch, because the current Adobe/Identity/0 values appear to satisfy that clause. Read the descendant collection before this branch changes it, or keep it for the ToUnicode fallback.

"/CMapName /JPDFium-Redact def\n/CMapType 2 def\n";
"/CMapName /JPDFium-Redact def\n/CMapType 2 def\n"
"1 begincodespacerange\n"
<< (twoByte ? "<0000> <FFFF>\n" : "<00> <FF>\n") << "endcodespacerange\n";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Preserve codespaces for every retained source width.

With mappings <41> and <8140> and content <00418140>, the existing width heuristic retains both mappings. This new declaration permits only two-byte codes, but Line 331 still emits <41>. The resulting ToUnicode CMap has a mapping outside its declared codespace. Codespace matching requires the same source-code length. (opensource.adobe.com)

Preserve the original encoding-consistent codespace ranges when filtering mappings. Add a mixed-width regression that checks both mappings and their codespaces.

As per coding guidelines, “Preserve stable public behavior,” including output-format semantics.

Source: Coding guidelines

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (11)

Major · Keep the last successful output when a pass makes no changes. · PdfFontEmbedder.java:408-411

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:408-411
Major · Functional Correctness · Quick win

Keep the last successful output when a pass makes no changes.

QpdfLib.embedFonts returns null on native rc 1. If the missing-font pass returns null, this code skips corrupt-font replacement. If the missing-font pass succeeds but replacement returns null, this code discards the successful rewrite and returns the original PDF. Start each pass with the last successful PDF and replace it only when the pass returns new bytes. Test both orders of success and no change.

Major · Aggregate codepoints page by page instead of materializing the whole… · PdfFontEmbedder.java:769

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:769
Major · Performance & Scalability · Quick win

Aggregate codepoints page by page instead of materializing the whole document.

usedCodepoints calls PdfTextExtractor.extractAll(doc), which builds every PageText before the loop starts. Each page keeps its TextLine and TextChar lists alive for the whole document, so peak memory grows with the document's total text. The loop only needs the unique codepoints for each font name.

Change the loop so each page's PageText can be released before the next page is extracted. Use a per-page extraction entry point, if one is accessible from this package. Keep extractAll unchanged for callers that need the complete list.

Major · Keep a valid /Encoding when a font name contains… · jpdfium_font_normalizer.cpp:1145-1148

native/bridge/src/jpdfium_font_normalizer.cpp:1145-1148
Major · Data Integrity & Integration · Heavy lift

Keep a valid /Encoding when a font name contains symbol.

isSymbolicFamilyName matches any font name that contains symbol, so /ExampleSymbolText matches. normalizeSimpleTrueTypeEncoding removes /Encoding at lines 1145-1151 before it checks the cmap. For a font with a (3,1) cmap and no (3,0) cmap, lines 1159-1162 then clear the symbolic flag, but the removed /Encoding is not restored. A valid Differences entry that maps code 65 to /B is lost, so code 65 can render a different glyph.

The whole-document TrueType pass at lines 1806-1811 removes /Encoding the same way, before any cmap check.

Decide the symbolic flag and encoding removal from the effective cmap and the existing /Encoding together. Use one shared decision in both passes. Keep the symbolic repair for fonts whose mappings need it. Add a regression test that code 65 still selects /B after normalization and after reopening the output.

Minor · Do not classify an oversized font program as corrupt. · PdfFontAuditor.java:684

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java:684
Minor · Functional Correctness · Quick win

Do not classify an oversized font program as corrupt.

If PDFium reports a valid 65 MiB program, getFontProgram returns null without inspecting it. collectCorruptFonts then reports the font as corrupt. Keep the allocation limit, but distinguish an uninspected program from an invalid one. Add a regression that verifies the size limit does not add the font to the result.

Minor · Apply control cleanup only to complete single-scalar… · jpdfium_font_normalizer.cpp:1234-1235

native/bridge/src/jpdfium_font_normalizer.cpp:1234-1235
Minor · Functional Correctness · Quick win

Apply control cleanup only to complete single-scalar names.

For /uni000D0041, the check reads only 000D. It changes the name to /.notdef, then drops the Differences entry, even if the font has a glyph with that exact name. Parse the complete name before classifying it as a control. Keep multi-scalar names intact and continue to clean up single-scalar control names.

Minor · Check cmap reads against each subtable's declared length. · jpdfium_font_normalizer.cpp:851

native/bridge/src/jpdfium_font_normalizer.cpp:851
Minor · Data Integrity & Integration · Quick win

Check cmap reads against each subtable's declared length.

A Format 4 idRangeOffset can leave its subtable and still pass the enclosing cmap check. The validator then interprets bytes from the next subtable as a glyph ID, which can change the CIDSet decision. Format 6 entries and Format 12 groups use the same enclosing bound. Validate each declared subtable length against the enclosing cmap, then reject lookups and arrays that leave that subtable. Keep the corrected Format 12 field offsets.

Based on learnings, offset-based font lookups must stay within the subtable's declared length, not just the enclosing table.

Also applies to: 862-862, 874-874

Source: Learnings

Minor · Publish the corrected /W when every corrected width equals… · jpdfium_font_normalizer.cpp:538

native/bridge/src/jpdfium_font_normalizer.cpp:538
Minor · Data Integrity & Integration · Quick win

Publish the corrected /W when every corrected width equals /DW.

repairCidFontWidths rewrites every existing /W entry in full mode, including unused CIDs. When a corrected width equals /DW, buildCidWidthsArray omits it and returns an empty array. The guard at line 567 then skips the write, so the old /W entry survives. For example, /DW 1000 with /W [7 [500]] and an unused CID 7 whose program width is 1000 keeps the width 500. The stored width then contradicts the embedded program, which the comment at lines 532-534 says must not happen.

Publish the corrected state in this case. Removing /W makes every CID use /DW, which matches the corrected widths. Entries that differ from /DW still produce a nonempty array and keep the current replacement.

Suggested fix

-    if (array.getArrayNItems() > 0) {
-        target.replaceKey("/W", array);
-        ++state.wFixed;
-        state.changed = true;
-    }
+    if (array.getArrayNItems() > 0) {
+        target.replaceKey("/W", array);
+    } else {
+        target.removeKey("/W");
+    }
+    ++state.wFixed;
+    state.changed = true;
Minor · Keep width-only repair from changing fonts it skips. · jpdfium_font_normalizer.cpp:1834-1836

native/bridge/src/jpdfium_font_normalizer.cpp:1834-1836
Minor · Data Integrity & Integration · Quick win

Keep width-only repair from changing fonts it skips.

FontNormalizer.repairWidths documents that fonts without a readable embedded program are skipped. repairWidthsAll calls the same native operation with page index -1. In that whole-document pass, the Type0 loop at jpdfium_font_normalizer.cpp:1823-1838 removes /CIDSet from every Type0 font that processFont did not inspect, including fonts whose program fails to load. The reload at line 1857 publishes the change. PdfRedactor calls repairWidthsAll by default, so an unrelated optional descriptor key can be removed from a skipped font during redaction.

The width-only path must leave skipped fonts unchanged. If the whole-document CIDSet cleanup is required for another mode, restrict it to that mode. If the cleanup must also apply to width-only calls, the repairWidths javadoc must state the change.

Minor · Reject uni-prefixed Differences names whose code units… · jpdfium_font_normalizer.cpp:1268-1273

native/bridge/src/jpdfium_font_normalizer.cpp:1268-1273
Minor · Functional Correctness · Quick win

Reject uni-prefixed Differences names whose code units are not hexadecimal.

A name such as /uniZZZZ fails the hex check at lines 1219-1233. Lines 1268-1273 still accept it, because algorithmicName checks only the uni prefix and the length. The override is then stored at line 1276, and the base encoding for that code does not apply. A uni name must contain one or more groups of four hexadecimal digits after uni. A name that does not match this form must not set validGlyph. Valid multi-scalar names, such as /uni00410042, must still be kept.

Minor · Do not derive CIDSet from the original face when the… · jpdfium_font_normalizer.cpp:1650-1656

native/bridge/src/jpdfium_font_normalizer.cpp:1650-1656
Minor · Data Integrity & Integration · Quick win

Do not derive CIDSet from the original face when the replacement program cannot be read.

After a successful resubset, the embedded program is the replacement stream. If reading that stream throws, or reloading it returns null, cidSetFace keeps the original face. The cmapFitsProgram guard is skipped because didResubset is true, and the /CIDFontType0 removal does not cover /CIDFontType2. The writer then publishes a CIDSet for the original program on the replaced stream.

The required behavior is that CIDSet must describe the embedded program that is actually written. When the replacement cannot be inspected, the code must not publish coverage derived from the original face. Choose between removing the key and another behavior that the applicable profile permits.

Trivial · Remove the unreachable bundled fallback. · PdfFontEmbedder.java:354-359

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:354-359
Trivial · Maintainability & Code Quality · Quick win

Remove the unreachable bundled fallback.

restrictedName returns null or a face with embeddable() == false. This branch requires the opposite, so it cannot select an alternate. Remove it, or use a lookup that can return a distinct embeddable candidate. As per coding guidelines, “Remove unused imports, raw types, dead branches, redundant casts, unnecessary wrappers, and duplicated helpers.”

Source: Coding guidelines

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f2358a9 and 6693988.

Files selected for processing: 6

  • .github/workflows/security.yml
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • native/bridge/include/jpdfium_font_internal.h
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • osv-scanner.toml
Files with no reviewable changes: 1

  • native/bridge/include/jpdfium_font_internal.h

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Review details

Context from checks skipped due to timeout: 1

  • GitHub Check: CodeRabbit
CI failures not shown inline: 2

GitHub Actions: Security / 3_OpenSSF Scorecard.txt: Security

Conclusion: failure

View job details

##[group]Run ossf/scorecard-action@3e931c8cb6ae3ef28804a82c1e76ce290610138f
 with:
   results_file: results.sarif
   results_format: sarif
   publish_results: true
   repo_***REDACTED_SECRET_ASSIGNMENT***
   file_mode: archive
   fail_on_publish_error: false
   internal_publish_base_url: https://api.scorecard.dev
   internal_default_***REDACTED_SECRET_ASSIGNMENT***
 ##[endgroup]
 ##[command]/usr/bin/docker run --name ghcrioossfscorecardactionv250_9bdd8c --label 988979 --workdir /github/workspace --rm -e "INPUT_RESULTS_FILE" -e "INPUT_RESULTS_FORMAT" -e "INPUT_PUBLISH_RESULTS" -e "INPUT_REPO_TOKEN" -e "INPUT_FILE_MODE" -e "INPUT_FAIL_ON_PUBLISH_ERROR" -e "INPUT_INTERNAL_PUBLISH_BASE_URL" -e "INPUT_INTERNAL_DEFAULT_TOKEN" -e "HOME" -e "GITHUB_JOB" -e "GITHUB_REF" -e "GITHUB_SHA" -e "GITHUB_REPOSITORY" -e "GITHUB_REPOSITORY_OWNER" -e "GITHUB_REPOSITORY_OWNER_ID" -e "GITHUB_RUN_ID" -e "GITHUB_RUN_NUMBER" -e "GITHUB_RETENTION_DAYS" -e "GITHUB_RUN_ATTEMPT" -e "GITHUB_ACTOR_ID" -e "GITHUB_ACTOR" -e "GITHUB_WORKFLOW" -e "GITHUB_HEAD_REF" -e "GITHUB_BASE_REF" -e "GITHUB_EVENT_NAME" -e "GITHUB_SERVER_URL" -e "GITHUB_API_URL" -e "GITHUB_GRAPHQL_URL" -e "GITHUB_REF_NAME" -e "GITHUB_REF_PROTECTED" -e "GITHUB_REF_TYPE" -e "GITHUB_WORKFLOW_REF" -e "GITHUB_WORKFLOW_SHA" -e "GITHUB_REPOSITORY_ID" -e "GITHUB_TRIGGERING_ACTOR" -e "GITHUB_WORKSPACE" -e "GITHUB_ACTION" -e "GITHUB_EVENT_PATH" -e "GITHUB_ACTION_REPOSITORY" -e "GITHUB_ACTION_REF" -e "GITHUB_PATH" -e "GITHUB_ENV" -e "GITHUB_STEP_SUMMARY" -e "GITHUB_STATE" -e "GITHUB_OUTPUT" -e "GITHUB_ARTIFACTS" -e "GITHUB_ARTIFACTS_LIST" -e "RUNNER_OS" -e "RUNNER_ARCH" -e "RUNNER_NAME" -e "RUNNER_ENVIRONMENT" -e "RUNNER_TOOL_CACHE" -e "RUNNER_TEMP" -e "RUNNER_WORKSPACE" -e "ACTIONS_RUNTIME_URL" -e "ACTIONS_RUNTIME_TOKEN" -e "ACTIONS_CACHE_URL" -e "ACTIONS_ID_TOKEN_REQUEST_URL" -e "ACTIONS_ID_TOKEN_REQUEST_TOKEN" -e "ACTIONS_RESULTS_URL" -e "ACTIONS_CACHE_MODE" -e "ACTIONS_ORCHESTRATION_ID" -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/...

GitHub Actions: Security / OpenSSF Scorecard: Security

Conclusion: failure

View job details

##[group]Run ossf/scorecard-action@3e931c8cb6ae3ef28804a82c1e76ce290610138f
 with:
   results_file: results.sarif
   results_format: sarif
   publish_results: true
   repo_***REDACTED_SECRET_ASSIGNMENT***
   file_mode: archive
   fail_on_publish_error: false
   internal_publish_base_url: https://api.scorecard.dev
   internal_default_***REDACTED_SECRET_ASSIGNMENT***
 ##[endgroup]
 ##[command]/usr/bin/docker run --name ghcrioossfscorecardactionv250_9bdd8c --label 988979 --workdir /github/workspace --rm -e "INPUT_RESULTS_FILE" -e "INPUT_RESULTS_FORMAT" -e "INPUT_PUBLISH_RESULTS" -e "INPUT_REPO_TOKEN" -e "INPUT_FILE_MODE" -e "INPUT_FAIL_ON_PUBLISH_ERROR" -e "INPUT_INTERNAL_PUBLISH_BASE_URL" -e "INPUT_INTERNAL_DEFAULT_TOKEN" -e "HOME" -e "GITHUB_JOB" -e "GITHUB_REF" -e "GITHUB_SHA" -e "GITHUB_REPOSITORY" -e "GITHUB_REPOSITORY_OWNER" -e "GITHUB_REPOSITORY_OWNER_ID" -e "GITHUB_RUN_ID" -e "GITHUB_RUN_NUMBER" -e "GITHUB_RETENTION_DAYS" -e "GITHUB_RUN_ATTEMPT" -e "GITHUB_ACTOR_ID" -e "GITHUB_ACTOR" -e "GITHUB_WORKFLOW" -e "GITHUB_HEAD_REF" -e "GITHUB_BASE_REF" -e "GITHUB_EVENT_NAME" -e "GITHUB_SERVER_URL" -e "GITHUB_API_URL" -e "GITHUB_GRAPHQL_URL" -e "GITHUB_REF_NAME" -e "GITHUB_REF_PROTECTED" -e "GITHUB_REF_TYPE" -e "GITHUB_WORKFLOW_REF" -e "GITHUB_WORKFLOW_SHA" -e "GITHUB_REPOSITORY_ID" -e "GITHUB_TRIGGERING_ACTOR" -e "GITHUB_WORKSPACE" -e "GITHUB_ACTION" -e "GITHUB_EVENT_PATH" -e "GITHUB_ACTION_REPOSITORY" -e "GITHUB_ACTION_REF" -e "GITHUB_PATH" -e "GITHUB_ENV" -e "GITHUB_STEP_SUMMARY" -e "GITHUB_STATE" -e "GITHUB_OUTPUT" -e "GITHUB_ARTIFACTS" -e "GITHUB_ARTIFACTS_LIST" -e "RUNNER_OS" -e "RUNNER_ARCH" -e "RUNNER_NAME" -e "RUNNER_ENVIRONMENT" -e "RUNNER_TOOL_CACHE" -e "RUNNER_TEMP" -e "RUNNER_WORKSPACE" -e "ACTIONS_RUNTIME_URL" -e "ACTIONS_RUNTIME_TOKEN" -e "ACTIONS_CACHE_URL" -e "ACTIONS_ID_TOKEN_REQUEST_URL" -e "ACTIONS_ID_TOKEN_REQUEST_TOKEN" -e "ACTIONS_RESULTS_URL" -e "ACTIONS_CACHE_MODE" -e "ACTIONS_ORCHESTRATION_ID" -e GITHUB_ACTIONS=true -e CI=true -v "/var/run/...
Additional context used

Code guidelines: 1

.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 3

Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • native/bridge/src/jpdfium_font_normalizer.cpp
Apply the Java 25 and FFM rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
Source excerpt: These rules apply to maintained source.

CodeRabbit inference engine (.github/CODERABBIT_REVIEW.md)

Files:

  • .github/workflows/security.yml
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • osv-scanner.toml
Learnings: 1

Learning: 2026-10-31T10:47:27.879Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-31T10:47:27.879Z
Learning: Source excerpt:
# JPDFium review standards

## Java 25 style

- Do not catch `Throwable` merely to swallow or log it. Catch broadly only at a justified boundary or cleanup guard, preserving fatal-error policy and cleanup ordering.

Applied to files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java
Additional comments: 6

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontAuditor.java: 1

734-735: Do not return a partial visibility set after an object walk fails.

If the walk records font A and the render-mode query for visible font B throws, this catch leaves {A} intact. The caller then skips B as invisible. Rethrow fatal errors and propagate nonfatal scan failures to the page-level handler, which already returns null.

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java: 2

325-325: Require positive evidence before skipping a font as invisible.

If a page draws font A and lists unused font B in /Resources, B has a nonempty page set but is absent from visibleFonts. This branch skips B before donor lookup, contrary to the contract to embed every non-embedded resource. Skip only fonts whose observed uses are all in rendering mode 3 and whose visibility scan is complete.


411-411: Data Integrity & Integration

The concern that an existing /FontFile* makes the native loop skip a corrupt font is not supported. For a donor whose name matches, the loop with onlyMissing false replaces the existing program stream with the donor stream.

native/bridge/src/jpdfium_font_normalizer.cpp: 3

845-845: The supplied prior review already covers the Format 4 scan budget, symbolic identity mapping, ligature component mapping, PFB lengths, Identity collection overwrite, face destruction order, PDF/A-1 CIDSet removal, and stale program snapshot.

Also applies to: 1107-1107, 1124-1126, 1333-1338, 1432-1434, 1638-1639, 1659-1659, 1706-1706


773-774: Data Integrity & Integration

The loop sets a CIDSet bit for any CID whose /CIDToGIDMap entry is GID 0, and only CID 0 is removed afterward. Whether that bit is a conformance defect depends on whether a CID mapped to .notdef counts as "present in the font program" under ISO 19005-2 §6.2.11.4.2. The available sources conflict on this point, and the ISO text was not retrieved. The claimed defect is therefore not decided.


1781-1781: Data Integrity & Integration

The retry-and-double-count mechanism is real in the inspected code. A font that throws after the counter increments is not marked, and the whole-document passes re-run it. Its counted total can then be inflated, and the Type0 pass can remove its /CIDSet if the retry also throws.

The claim depends on a throw that occurs after the first state change. The inspected lines do not establish one. The helpers listed in the evidence could throw from unguarded QPDF calls, and their bodies were not inspected. The review comment's effect is therefore conditional on those helper bodies, and this review cannot decide it from the inspected source.

@balazs-szucs
balazs-szucs force-pushed the fix/pdfa-pdfx-conformance-and-safety branch from bab670b to 5f3ae13 Compare November 18, 2026 19:55
@balazs-szucs
balazs-szucs force-pushed the fix/pdfa-pdfx-conformance-and-safety branch from 5f3ae13 to af870ff Compare November 18, 2026 20:33
…ecks

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
@balazs-szucs
balazs-szucs force-pushed the fix/pdfa-pdfx-conformance-and-safety branch from af870ff to 853966b Compare November 19, 2026 12:58
if (data[0] == 0x01 && data[1] == 0x00 && data[2] == 0x04 && data[3] == 0x04) return true;
String head = new String(data, 0, Math.min(4, data.length), StandardCharsets.ISO_8859_1);
if ("OTTO".equals(head) || "true".equals(head) || "ttcf".equals(head)) return true;
if (data.length >= 4 && data[0] == '%' && data[1] == '!') return true;
String head = new String(data, 0, Math.min(4, data.length), StandardCharsets.ISO_8859_1);
if ("OTTO".equals(head) || "true".equals(head) || "ttcf".equals(head)) return true;
if (data.length >= 4 && data[0] == '%' && data[1] == '!') return true;
return data.length >= 2 && (data[0] & 0xFF) == 0x80 && data[1] == 0x01;
int genStart = j;
while (j < dict.length() && Character.isDigit(dict.charAt(j))) j++;
if (j > genStart) {
int genEnd = j;
+ dict.substring(at);
}

private static String inheritPageAttributes(String dict, String text, long number, long generation) {
+ dict.substring(at);
}

private static String inheritPageAttributes(String dict, String text, long number, long generation) {
…ormat jpdfium_qpdf.cpp

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
…dditions

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

@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: 27

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (10)

Major · Do not let an incompatible replacement donor discard successful… · PdfFontEmbedder.java:421

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:421
Major · Data Integrity & Integration · Heavy lift

Do not let an incompatible replacement donor discard successful embedding.

If the first pass embeds Helvetica and the second pass supplies a Type 1 donor for a corrupt CID font, native code rejects the replacement batch with -4. QpdfLib throws, so the caller loses the successfully rewritten PDF. Before this change, the same missing Helvetica could be embedded without attempting that replacement. Reject the incompatible donor before the replacement pass and leave that CID font unresolved. Keep password and signature failures visible. (raw.githubusercontent.com)

Major · Try the next donor when coverage rejects the preferred face. · PdfFontEmbedder.java:396-402

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java:396-402
Major · Functional Correctness · Heavy lift

Try the next donor when coverage rejects the preferred face.

If SimSun resolves first to PingFangSC and that face lacks a required ideograph, this branch abandons the font. It never tries an installed NotoSansSC face that covers the text. Validate candidates in preference order and stop at the first eligible face with sufficient coverage. Keep the first choice when it already covers the text.

Major · Keep predefined-CMap substitution when the glyph mapping is… · jpdfium_qpdf_fonts_embed.cpp:570

native/bridge/src/jpdfium_qpdf_fonts_embed.cpp:570
Major · Functional Correctness · Quick win

Keep predefined-CMap substitution when the glyph mapping is independent of /ToUnicode.

A supported 90msp-RKSJ-H font with an inherited /ToUnicode stream now returns false before the native code scans the used CIDs. The caller skips the font. The predefined branch derives glyph mappings from the Adobe collection tables, not from the local /ToUnicode stream. Keep the inherited stream, but limit this refusal to paths that cannot otherwise establish a complete glyph mapping.

Major · Do not mark zero-filled CID map gaps as present glyphs. · jpdfium_qpdf_fonts_embed.cpp:793

native/bridge/src/jpdfium_qpdf_fonts_embed.cpp:793
Major · Data Integrity & Integration · Quick win

Do not mark zero-filled CID map gaps as present glyphs.

If a subset retains CID 3 but not CIDs 1 and 2, the generated /CIDToGIDMap fills those gaps with GID 0. cidsPresentInProgram accepts those entries because zero is below the glyph count. The bitmap writer clears CID 0, not CIDs 1 and 2. Exclude GID 0 entries from the membership scan and apply the same rule in the normalizer. Verify that the reopened bitmap marks CID 3 but not either gap. (raw.githubusercontent.com)

Major · Validate the full algorithmic glyph name before keeping… · jpdfium_font_normalizer.cpp:1332-1337

native/bridge/src/jpdfium_font_normalizer.cpp:1332-1337
Major · Data Integrity & Integration · Quick win

Validate the full algorithmic glyph name before keeping a Differences entry.

/u110000 and /uni41Z1 pass this prefix check. Neither names a valid Unicode scalar or sequence. Both can survive normalization in /Differences. Use the full glyph-name parser for algorithmic names, and retain valid entries such as /u0042 and /uni0041.

Major · Do not reclassify fonts after the normalizer has… · jpdfium_font_normalizer.cpp:1792-1802

native/bridge/src/jpdfium_font_normalizer.cpp:1792-1802
Major · Data Integrity & Integration · Quick win

Do not reclassify fonts after the normalizer has processed them.

In the supplemental TrueType sweep, the processedFonts check follows the symbolic flag update. A font named SymbolExample with (3,1) and (3,10) cmap records but no (3,0) can first be classified as nonsymbolic by normalizeSimpleTrueTypeEncoding, then be marked symbolic by this sweep. The output then fails the symbolic cmap rule. Check processedFonts before changing the descriptor, and apply the same classification logic to unprocessed fonts. This range uses the pinned source because the supplemental sweep was omitted from the annotated excerpt. (raw.githubusercontent.com)

Major · Do not edit a shared /CIDSystemInfo dictionary in place. · jpdfium_font_normalizer.cpp:1470

native/bridge/src/jpdfium_font_normalizer.cpp:1470
Major · Data Integrity & Integration · Quick win

Do not edit a shared /CIDSystemInfo dictionary in place.

If an Identity-H descendant and a Japan1 descendant reference the same indirect dictionary, each repair writes its values into that shared object. Whichever runs last leaves the other descendant with the wrong collection. Install a private dictionary on the target when its values must change. Leave the original reference in place when the values already match.

Major · Read /CIDSystemInfo from the stream dictionary, not the… · jpdfium_font_normalizer.cpp:1482

native/bridge/src/jpdfium_font_normalizer.cpp:1482
Major · Data Integrity & Integration · Quick win

Read /CIDSystemInfo from the stream dictionary, not the stream object.

enc is a stream here (line 1481). QPDFObjectHandle::getKey on a stream handle does not reach the stream dictionary. qpdf returns null with a type warning. As a result, src.isDictionary() is false, the target's Registry, Ordering, and Supplement are not synchronized, and the function returns at line 1491. If the target had no dictionary /CIDSystemInfo, the empty dictionary created at line 1456 stays without its required keys.

Read the key through the stream dictionary:

Suggested fix

-        QPDFObjectHandle src = enc.getKey("/CIDSystemInfo");
+        QPDFObjectHandle src = enc.getDict().getKey("/CIDSystemInfo");
Major · Decode original Flate bytes before document-wide decompression. · lib.rs:175

native/rust/jpdfium-impl/src/lib.rs:175
Major · Data Integrity & Integration · Heavy lift

Decode original Flate bytes before document-wide decompression.

The new raw-DEFLATE recovery is bypassed for a /FlateDecode stream containing 01 03 00 FC FF 71 20 51 (q Q). In lopdf 0.47.0, failed zlib and header-skipped decoding can still publish empty content and remove /Filter. The empty-stream guard then skips the object, so compression saves an empty stream without calling the new fallback. (raw.githubusercontent.com)

Decode each original Flate stream before destructive decompression, while preserving /DecodeParms semantics. Add an end-to-end raw-DEFLATE fixture and assert its decoded content after reopening. The helper-only test cannot detect this integration failure.

Severity: major. Confidence: high for the declared dependency version.

Minor · The stale-width test cannot show that CID 0 was repaired. · FontNormalizerTest.java:777

jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java:777
Minor · Functional Correctness · Quick win

The stale-width test cannot show that CID 0 was repaired.

withCidWidth replaces the whole /W array with one entry for CID 0. The width repair counts any other used CID that has a GID but no width as a change. The assertion widthsRepaired == 1 can therefore pass without correcting the CID 0 width.

CID 0 can also be excluded before the comparison. buildCidToGidTable drops entries whose GID is 0. If the embedded map sends CID 0 to GID 0, the injected width is never checked.

Use a stale width on a used CID whose GID is nonzero. After normalization, assert that the saved /W value for that CID equals the font program advance. Keep the CID 0 case only with its own assertion on the saved value.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 6693988 and 12dede4.

Files selected for processing: 16

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
  • jpdfium/src/test/java/stirling/software/jpdfium/PdfPageRedactNativeTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/QpdfIntegrationTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_qpdf.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_embed.cpp
  • native/bridge/src/jpdfium_repair.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
  • native/library-size-budgets.txt
  • native/rust/jpdfium-impl/src/lib.rs
Files with no reviewable changes: 1

  • native/bridge/src/jpdfium_qpdf.cpp

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Review details

Context from checks skipped due to timeout: 42

  • GitHub Check: CodeRabbit
  • GitHub Check: Native bridge libFuzzer (ASan/UBSan, real PDFium)
  • GitHub Check: Natural System Libvips & Downstream Integration (Linux x64)
  • GitHub Check: Samples E2E Suite (All 88 Feature Samples)
  • GitHub Check: README Quick Start Example (Linux x64)
  • GitHub Check: Concurrency Stress Tests (Linux x64)
  • GitHub Check: Musl Native Detection (Alpine)
  • GitHub Check: Build & Verify (Compilation) (windows-latest)
  • GitHub Check: Build & Verify (Compilation) (ubuntu-latest)
  • GitHub Check: JMH Benchmarks (advisory)
  • GitHub Check: Build & Verify (Compilation) (macos-15)
  • GitHub Check: Publish Maven Dry Run
  • GitHub Check: GraalVM Native Image Smoke & E2E Test (Linux x64)
  • GitHub Check: Robustness, Leak & Determinism Tests (Linux x64)
  • GitHub Check: Unit & Integration E2E Tests (Linux x64)
  • GitHub Check: Restricted-env compat (no execstack + hermetic bundle)
  • GitHub Check: CodeQL Analysis (c-cpp)
  • GitHub Check: CLI correctness & no-corruption tests
  • GitHub Check: Public API compatibility (japicmp vs last release)
  • GitHub Check: Bundle verify (symbols, RPATH, linkage, sizes)
  • GitHub Check: Corpus (generate + native)
  • GitHub Check: FFM layout vs pinned PDFium headers
  • GitHub Check: CodeQL Analysis (java-kotlin)
  • GitHub Check: build-natives (windows-x64, windows-latest)
  • GitHub Check: Java - SpotBugs + Checkstyle + PMD + Spotless
  • GitHub Check: build-natives (linux-x64, ubuntu-latest)
  • GitHub Check: build-natives (windows-arm64, windows-11-arm)
  • GitHub Check: build-natives (darwin-x64, macos-15-intel)
  • GitHub Check: Samples E2E (88 features via RunAllSamples)
  • GitHub Check: build-natives (linux-arm64, ubuntu-24.04-arm)
  • GitHub Check: Module descriptor integrity
  • GitHub Check: Corpus + integration e2e
  • GitHub Check: Shellcheck (scripts + native/*.sh)
  • GitHub Check: JaCoCo coverage (non-blocking ratchet)
  • GitHub Check: Javadoc builds cleanly
  • GitHub Check: C++ - clang-tidy + cppcheck + clang-format
  • GitHub Check: build-natives (darwin-arm64, macos-15)
  • GitHub Check: Flaky-test guard (3× rerun)
  • GitHub Check: Outdated dependencies report
  • GitHub Check: CodeQL (java-kotlin)
  • GitHub Check: CodeQL (c-cpp)
  • GitHub Check: OSV vulnerability scan
Additional context used

Code guidelines: 1

.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 4

Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_embed.cpp
  • native/bridge/src/jpdfium_repair.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
Enforce meaningful assertions, deterministic concurrency, failure-path cleanup, and explicit native/stub requirements.

CodeRabbit configuration file

Files:

  • jpdfium/src/test/java/stirling/software/jpdfium/PdfPageRedactNativeTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/QpdfIntegrationTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
Apply the Java 25 and FFM rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
  • jpdfium/src/test/java/stirling/software/jpdfium/PdfPageRedactNativeTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/QpdfIntegrationTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
Source excerpt: These rules apply to maintained source.

CodeRabbit inference engine (.github/CODERABBIT_REVIEW.md)

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfXConverter.java
  • jpdfium/src/test/java/stirling/software/jpdfium/PdfPageRedactNativeTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfFontEmbedderTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/doc/QpdfIntegrationTest.java
  • jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_qpdf_fonts_embed.cpp
  • native/bridge/src/jpdfium_repair.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
  • native/library-size-budgets.txt
  • native/rust/jpdfium-impl/src/lib.rs
Learnings: 4

Learning: 2026-10-20T15:53:18.441Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-20T15:53:18.441Z
Learning: Source excerpt:
# JPDFium review standards

## Comments and documentation

- Remove stale TODOs, placeholder branches, speculative fallbacks, and obsolete comments in changed code. Do not require unrelated cleanup.

Applied to files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
Learning: 2026-10-20T15:53:18.441Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-20T15:53:18.441Z
Learning: Source excerpt:
# JPDFium review standards

## Comments and documentation

- Comments explain invariants, ownership, non-obvious constraints, or reasons. Remove line-by-line narration, repeated summaries, decorative banners, and change-history commentary.

Applied to files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
Learning: 2026-10-31T10:47:27.879Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-31T10:47:27.879Z
Learning: Source excerpt:
# JPDFium review standards

## Tests, profiling, and delivery

- Validate semantic preservation through reopen, independent structural checks, and representative rendering/text properties. A successful open is insufficient.

Applied to files:

  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
Learning: 2026-10-20T15:53:18.441Z

Learnt from: CR
Repo: Stirling-Tools/JPDFium PR: 0
File: .github/CODERABBIT_REVIEW.md:0-0
Timestamp: 2026-10-20T15:53:18.441Z
Learning: Source excerpt:
# JPDFium review standards

## Tests, profiling, and delivery

- Every defect fix needs a focused regression with an observable expected result. No `assertTrue(true)`, swallowed failures, or tests that silently pass when fixtures/tools/source roots are missing.

Applied to files:

  • jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java
ast-grep (0.51.1)

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java

[warning] 1341-1341: Use a randomly-generated IV
Context: byte[] tail = (trailer + "%%EOF\n").getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)

jpdfium/src/test/java/stirling/software/jpdfium/doc/PdfRepairTest.java

[warning] 480-481: Use a randomly-generated IV
Context: byte[] deepNesting = ("%PDF-1.4\n" + "<<".repeat(100) + "/Im1 5 0 R")
.getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)


[warning] 491-492: Use a randomly-generated IV
Context: byte[] headerless = ("<<".repeat(70) + "/Type /Page")
.getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)


[warning] 557-557: Use a randomly-generated IV
Context: byte[] pdf = sb.toString().getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)


[warning] 608-608: Use a randomly-generated IV
Context: byte[] pdf = sb.toString().getBytes(StandardCharsets.ISO_8859_1);
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)

jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java

[warning] 706-706: Use a randomly-generated IV
Context: byte[] staleCidSet = new byte[] {(byte) 0x80, 0, 0, 0, 0x08, 0, 0x20};
Note: [CWE-329] Generation of Predictable IV with CBC Mode.

(random-iv)

Clippy (1.99.1)

native/rust/jpdfium-impl/src/lib.rs

[warning] 69-69: manual implementation of .is_multiple_of()

(warning)

Additional comments: 7

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java: 2

421-421: Automatic corrupt-CID replacement still needs mapping validation. If CID 1 means A but the donor places A at GID 36, Unicode coverage can pass while the preserved /Identity map selects GID 1.


334-336: The visibility check can still skip an unused page font. A font listed in a page’s resources has a page in the inventory even when no text uses it. Its absence from visibleFonts does not establish Tr 3 use. The auditor can also return a partial set when an object walk fails. (raw.githubusercontent.com)

native/bridge/src/jpdfium_font_normalizer.cpp: 4

1702-1703: cidSetOwned is still destroyed before cidSetGuard retires the face that borrows its bytes. (freetype.org)


1188-1190: The ligature-name loop still installs a multi-scalar glyph such as f_i as the nominal glyph for each component.


1547-1547: The unconditional /CIDSet removal still affects PDF/A-1 CIDFont subsets, where the entry is required. (github-wiki-see.page)


1139-1141: Functional Correctness

The reload at lines 1139-1141 has no evidence of skipping a valid re-subsetted face. The resubset path validates subset.bytes with the same faceIndex before storing it (lines 674-676), and the cmap repair then reloads those same bytes with that index (lines 1139-1140). If the first check succeeds, the second should too.

jpdfium/src/test/java/stirling/software/jpdfium/fonts/FontNormalizerTest.java: 1

804-804: Functional Correctness

The review comment poses a question about the generated map. Its premise is a runtime-generated artifact. The inspected source shows that a zero-filled hole is possible when mapping keys are sparse. The source that decides whether this fixture produces such a hole was not inspected: the population of remappedGlyph or job.cidGlyph for issue20065, and the cids set that the normalizer passes to buildCidSetBits (jpdfium_font_normalizer.cpp lines 900-925). Without those, the assertion at FontNormalizerTest.java:804-807 cannot be shown to demand a bit for a glyphless CID. No defect is established, and no correction is proposed.

Comment on lines +465 to +467
* an unembedded font. Fonts used only by invisible text (render mode 3) are embedded too:
* PDF/A-2 6.2.11.5 requires them to carry a font program, so the strict path never skips
* them the way the best-effort {@link #embedMissing(byte[], boolean, Path...)} entry does.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Describe invisible-font embedding as strict API policy.

PDF/A-2 clause 6.2.11.5 concerns font metrics. Its embedding rule exempts fonts used only in rendering mode 3. Keep the stricter API behavior if intended, but remove the claim that PDF/A-2 requires it. Update the matching comments in the best-effort branch and integration test. (github.com)

|| ch.unicode() == 0xFFFD) {
continue;
}
result.computeIfAbsent(key(ch.fontName()), k -> new HashSet<>())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Supported by static analysis

Script executed:

# Locate the key() definition and its call sites in PdfFontEmbedder.java.
rg -n -F -e 'key(' -e 'computeIfAbsent' -- jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java || test "$?" -eq 1

# Read the coverage collection window around line 798.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '776,812p'

# Read the donor validation window around line 380.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '362,416p'

Repository: Stirling-Tools/JPDFium

Length of output: 5849


Script executed:

# Read key() definition and its normalization.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '718,740p'

# Read the loop header that binds key for the coverage lookup at line 380.
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfFontEmbedder.java | sed -n '338,352p'

Repository: Stirling-Tools/JPDFium

Length of output: 1821


Scope the coverage check to the missing font's own codepoints.

key() strips the subset prefix, so usedCodepoints merges every subset of one base family into one set. The donor check at lines 380-402 then requires codepoints drawn by other subsets. For example, a missing GHIJKL+Acme that uses only A is rejected by a donor that covers A but not Ω, because ABCDEF+Acme draws Ω. The missing font is then not embedded.

Build the coverage requirement from codepoints drawn with the missing font itself. Keep the base-family key for font resolution at lines 346, 703, and 1218.

byte[] current = inputBytes;
byte[] input = inputBytes;
RepairResult signed = signedDocumentResult(input, writeDiagnostics);
if (signed != null) return signed;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Do not report successful sanitization without sanitizing.

If an openable signed PDF contains an embedded file, sanitize(true) returns CLEAN and the original bytes before it reaches sanitization. Preserving the signature is correct, but the caller cannot tell that the requested sanitization did not happen. Return an explicit conflict when sanitization is requested. Keep signed pass-through when it is not requested. Test both options on the same signed fixture.

Comment on lines +308 to +311
if (!salvagedResult.isUsable() && usePdfioFallback) {
salvagedResult = RepairLib.pdfioRepair(pageTree);
}
if (!salvagedResult.isUsable() && useLopdfFallback) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Supported by static analysis

Script executed:

# Cascade guards and fallback calls
cat -n jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java | sed -n '296,362p'
# Where pageTree and salvagedResult are bound
rg -n -F -e 'pageTree' -e 'salvagedResult' -- jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java || test "$?" -eq 1
# hasPages and isUsable definitions
rg -n -F -e 'hasPages' -e 'isUsable' -- jpdfium/src/main/java/stirling/software/jpdfium/doc/ || test "$?" -eq 1

Repository: Stirling-Tools/JPDFium

Length of output: 7697


Run the enabled fallbacks until a page-bearing result is found.

The fallback guards at lines 308 and 311 check only isUsable(). The adoption check at line 314 also requires hasPages(...). A usable RepairLib.repair(pageTree, flags) result with no pages therefore skips both fallbacks and is rejected. The same mismatch exists at lines 325 and 328 for the truncated-file salvage.

Both fallbacks operate on pageTree, the same bytes the core repair received. A page-bearing fallback result can therefore recover the document that the core repair left without pages. Gate each fallback on the negation of the adoption condition, !(salvagedResult.isUsable() && hasPages(salvagedResult.repairedPdf())), at lines 308, 311, and 325. A usable page-bearing core result should still stop the cascade.

os << "\"issues\":" << warnings_to_json(warnings);

} catch (QPDFExc& e) {
} catch (std::exception& e) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Build fatal diagnostics independently of partial success output.

If warnings_to_json() throws and allocation then recovers, the widened catch appends fatal fields after the existing "issues": prefix. RepairLib.inspect() returns the malformed JSON. Start the fatal response in a clean buffer and publish only a complete response. Inject a failure during warning serialization and check that Java receives parseable fatal JSON.


Major · Stability & Availability · Heavy lift

Translate diagnostic allocation failures at the C boundary.

If inspection throws std::bad_alloc and memory remains exhausted, the new catch allocates msg and escaped. A second allocation failure escapes the exported function. Final string materialization is also outside the try block. Initialize the output pointer to null and return a checked error code if a diagnostic cannot be built or copied. Update RepairLib.inspect() to handle that result before reading the pointer. Verify with allocation failure injection.

As per coding guidelines, “Exported boundaries translate exceptions; noexcept alone does not translate them.”

Source: Coding guidelines

// surrogate pairs) never truncate.
std::string ub = pendingHex[2];
for (uint64_t code = lo; code <= hi && out.size() < kMaxEntries; code++) {
if (hasSurrogateUnit(ub)) break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Preserve valid surrogate pairs in consecutive ranges.

Minor; high confidence. For <0002> <0003> <D83DDE00>, this check rejects the valid UTF-16BE pair before adding either mapping. Adobe explicitly permits surrogate-pair destinations in bfrange. (pdfa.org)

If another mapping parses successfully, the sanitizer replaces /ToUnicode without these surviving mappings. Validate surrogate pairing instead of rejecting every surrogate unit. Add a saved-text regression with BMP and supplementary characters. (raw.githubusercontent.com)

As per coding guidelines, “Preserve stable public behavior,” including output-format semantics.

Source: Coding guidelines

Comment thread native/bridge/src/jpdfium_sanitize.cpp Resolved
Comment thread native/bridge/src/jpdfium_sanitize.cpp Outdated
flushBfChar();
else if (section == CmapSection::BfRange)
flushBfRange();
flushBfChar();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Stability & Availability · Quick win

Dispatch EOF cleanup to the active CMap section.

Major; high confidence. An unterminated bfrange array with 100,000 short destination strings reaches flushBfChar() here. That helper repeatedly erases two elements from the vector front. This causes roughly 2.5 billion string-element moves and treats range operands as bfchar mappings. The output-entry cap does not prevent this work. (raw.githubusercontent.com)

Flush only the active section and reject incomplete arrays. Add a truncated-array regression with an observable rejection result and bounded completion time.

As per coding guidelines, “Every defect fix needs a focused regression with an observable expected result.”

Source: Coding guidelines

Comment on lines +1316 to +1320
let bad_flate = {
let mut z = zenc.finish().unwrap();
let last = z.len() - 1;
z[last] ^= 0xFF;
z

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Maintainability & Code Quality · Quick win

Exercise the still-filtered branch in the regression test.

lopdf 0.47.0 already recovers this corrupt-Adler fixture during doc.decompress(). It removes /Filter before the loop, so this test also passes with the old defective replacement branch. (raw.githubusercontent.com)

Add a zlib stream containing q Q with /DecodeParms << /Predictor 12 /Columns 1 >>. lopdf rejects its predictor data, leaving the stream filtered. Assert that the original compressed bytes and filter remain unchanged when zopfli cannot shrink the content. This distinguishes the fixed branch from the old implementation. (raw.githubusercontent.com)

Severity: minor. Confidence: high. As per coding guidelines, “Every defect fix needs a focused regression with an observable expected result.”

Source: Coding guidelines

…zer, and ToUnicode parser

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

@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: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 12dede4 and 097a8a2.

Files selected for processing: 4

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_sanitize.cpp

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Review details

Additional context used

Code guidelines: 1

.github/CODERABBIT_REVIEW.md — configured
Path-based instructions: 3

Apply the native ownership, C ABI, C++23, engine integration, memory, and SIMD rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
Apply the Java 25 and FFM rules from .github/CODERABBIT_REVIEW.md.

CodeRabbit configuration file

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
Source excerpt: These rules apply to maintained source.

CodeRabbit inference engine (.github/CODERABBIT_REVIEW.md)

Files:

  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java
  • jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java
  • native/bridge/src/jpdfium_font_normalizer.cpp
  • native/bridge/src/jpdfium_sanitize.cpp
Additional comments: 1

jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfRepair.java: 1

357-358: Performance & Scalability

The concern that compaction skipping makes repaired output "much larger" is not supported. The native repair writer sets setCompressStreams(true), so the core output keeps compressed streams, and no decoded-QDF output path appeared in the inspected source. The compaction guard skips compaction when either format flag is set, not only when both are set. That skip is deliberate. Compaction would conflict with the classic xref and PDF 1.4 settings the flags require.

? PdfOptimizer.optimize(resultBytes, PdfOptimizer.DEFAULT, 9,
PdfOptimizer.OBJECT_STREAMS_PRESERVE,
? PdfOptimizer.optimize(resultBytes,
PdfOptimizer.RECOMPRESS_FLATE | PdfOptimizer.COMPRESS_STREAMS, 9,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Heavy lift

Supported by static analysis

Script executed:

rg -n -i 'XStep|YStep|applyDocumentOptions|clamp' native/bridge/src/jpdfium_qpdf.cpp
sed -n 425,475p jpdfium/src/main/java/stirling/software/jpdfium/doc/PdfCompressor.java

Repository: Stirling-Tools/JPDFium

Length of output: 4477


Keep tiling-pattern steps unchanged in the PDF/A-1 stream pass.

The stream pass calls PdfOptimizer.optimize with RECOMPRESS_FLATE | COMPRESS_STREAMS. Native applyDocumentOptions runs clampPatternSteps before it checks any flag. That clamp replaces a tiling-pattern /XStep or /YStep with an absolute value below 1.0 by 1.0. A pattern with /XStep 0.5 therefore renders with different tile spacing after this pass.

The Java code adopts the output whenever it is smaller (opt.length < resultBytes.length). It does not compare rendering, so the changed pattern is accepted without a check.

This pass must leave tiling-pattern steps unchanged, or reject its output when they change. Keep the overflow clamp for non-finite and out-of-range steps, because the native source documents that protection.

Add a regression. Render a PDF/A-1 page that contains a /XStep 0.5 tiling pattern before and after this pass, and assert that the rendering matches.

Comment on lines +259 to +262
if (ub.size() > 0 && span > (kMaxTotalDestBytes - totalDestBytes) / ub.size()) {
pendingHex.clear();
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Do not publish a partial CMap after a resource limit.

If an earlier mapping succeeds, this return discards the range but leaves parseToUnicode() successful. Lines 799-807 then replace /ToUnicode with incomplete mappings.

For example, place <0001> <0041> before range <0002> <FFFF> with a 258-byte destination containing repeated <0042> units. This check rejects the range. Surviving content <00010002> loses the mapping for 0002, which the previous implementation retained.

Propagate limit exhaustion separately. Skip the replacement or fail sanitization instead of publishing a partial CMap. Add a regression that checks the surviving mapping and the limit result.

As per coding guidelines, “Preserve stable public behavior,” including output-format semantics.

Source: Coding guidelines

This branch has not been deployed

No deployments
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