Compare commits

...
Author SHA1 Message Date
Anthony Stirling aa66c4f64e audit: jpdfium sanitize js sigs 2026-05-22 10:07:38 +01:00
Anthony Stirling 2de02ba145 impl migration to pdfium for sanitize and javascript and certsign 2026-05-22 09:54:42 +01:00
Anthony Stirling 2f1fe2c80c Delete MergeBenchmark 2026-05-21 23:00:00 +01:00
Anthony Stirling 1051f28c52 Drop remaining why/how comments 2026-05-21 19:11:52 +01:00
Anthony Stirling 29ccbf7ae6 Trim verbose comments across JPDFium integration 2026-05-21 19:03:31 +01:00
Anthony Stirling 007c8e17de Exclude JPDFium native cache from temp-file regression check 2026-05-21 17:46:46 +01:00
Anthony Stirling 81dbb29be3 Iterative addBookmarkFlat with depth + cycle + node-count guards 2026-05-21 17:17:06 +01:00
Anthony Stirling caef0477a9 Merge remote-tracking branch 'origin/main' into feat/jpdfium-integration
# Conflicts:
#	app/common/build.gradle
2026-05-21 16:55:18 +01:00
Anthony Stirling 7682a0dd54 sign-jpdfium-dylibs: sign both Gradle and Tauri bootJar copies 2026-05-21 16:26:52 +01:00
Anthony Stirling f90ed4657a Apply spotless; bash 3.2-compatible array handling in sign-jpdfium-dylibs 2026-05-21 15:53:28 +01:00
Anthony Stirling a6c7a68242 Move sign-jpdfium-dylibs-in-bootjar.sh into frontend/scripts/ 2026-05-21 15:21:25 +01:00
Anthony Stirling a184b394d6 Strip rationale-history comments from JDK 25 references 2026-05-21 15:20:11 +01:00
Anthony Stirling 302d04c201 Merge remote-tracking branch 'origin/main' into feat/jpdfium-integration
# Conflicts:
#	build.gradle
2026-05-21 15:05:51 +01:00
Anthony Stirling 68ae9d52fb Bump JPDFium dep to 1.0.0; drop snapshot repo 2026-05-21 14:46:10 +01:00
Anthony Stirling 6552ba905c Cleanup: drop local mavenLocal hack; gate MergeBenchmark with -Dmerge.bench=true 2026-05-21 11:58:43 +01:00
Anthony Stirling ee36b6f616 MergeController: preserve source bookmarks through merge (PDFium drops them) 2026-05-21 11:39:59 +01:00
Anthony Stirling 627091f8df MergeController: use JPDFium native merge (94% less heap on 5-doc merge) 2026-05-21 10:37:01 +01:00
Anthony Stirling 67a37d3291 Filter JPDFium natives per Tauri target OS (saves ~45 MB per bundle) 2026-05-21 00:28:31 +01:00
Anthony Stirling 4b6d4885f4 sign-jpdfium-dylibs: resolve native-jar paths via jar tf first
`jar xf <jar> <path>` doesn't expand glob patterns in <path> the way
`unzip` does — paths must be exact. My initial script passed
`BOOT-INF/lib/jpdfium-natives-darwin-x64-*.jar` as a literal path,
which matched nothing, so the script always reported
"No JPDFium darwin natives in bootJar; nothing to sign" and exited
without actually signing anything.

Fix: `jar tf` to LIST the bootJar's contents, grep with a regex for
the snapshot-versioned native-jar paths, then `jar xf` those exact
paths.

The natives jars are normally:
  BOOT-INF/lib/jpdfium-natives-darwin-x64-1.0.0-SNAPSHOT.jar
  BOOT-INF/lib/jpdfium-natives-darwin-arm64-1.0.0-SNAPSHOT.jar
…but the version number floats with the snapshot timestamp, hence
the regex match instead of a fixed path.
2026-05-20 09:46:07 +01:00
Anthony Stirling 2a151b65f7 Move JPDFium dylib signing step AFTER cert import
My first placement put the sign-jpdfium-dylibs-in-bootjar step at
the wrong point in the workflow: BEFORE the "Verify Certificate"
step that sets APPLE_SIGNING_IDENTITY in GITHUB_ENV. So the gate
`if: ... && env.APPLE_SIGNING_IDENTITY != ''` always evaluated to
false and the step silently skipped, leaving the dylibs unsigned
and notarytool still rejecting the .app.

Move it to right after Verify Certificate (which sets the env var
from the keychain identity). Also switch the gate to checking
env.APPLE_CERTIFICATE (the secret that's set at job level and
available from step 1) rather than env.APPLE_SIGNING_IDENTITY (set
mid-workflow via GITHUB_ENV) — the latter is fine in `run:` blocks
but flaky in `if:` evaluation depending on GH Actions evaluation
timing.
2026-05-20 09:08:37 +01:00
Anthony Stirling 9458fcd0e2 Re-run CI against JPDFium with Windows ICU trim + harfbuzz-no-glib 2026-05-20 00:45:22 +01:00
Anthony Stirling 1e8c41425b Sign JPDFium dylibs in bootJar before Tauri notarization (macOS)
Tauri-build macos-universal has been failing notarytool because the
.dylib files inside the JPDFium native jars (jpdfium-natives-darwin-
x64-*.jar / -arm64-*.jar) ship unsigned — JPDFium's publish workflow
has no Apple Developer credentials, so it can't sign during publish.
Apple's notarytool walks INTO nested .jars in the .app and reports:

  "The binary is not signed."
  path: Stirling-PDF.zip/Stirling-PDF.app/Contents/Resources/libs/
   stirling-pdf-*.jar/BOOT-INF/lib/
   jpdfium-natives-darwin-x64-1.0.0-SNAPSHOT.jar/natives/darwin-x64/
   libjpdfium.dylib

Tauri's own codesign walk doesn't open .jars, so the fix has to
happen here before tauri-action runs. New step between
`task desktop:prepare` (builds bootJar) and `tauri-action` (builds
.app + notarizes):

  scripts/sign-jpdfium-dylibs-in-bootjar.sh
    1. jar xf bootJar BOOT-INF/lib/jpdfium-natives-darwin-*.jar
    2. for each native jar, explode it, codesign every .dylib with
       APPLE_SIGNING_IDENTITY + --options runtime + --timestamp
    3. jar cfM0 to repack the natives jar (stored, no deflate —
       matches Spring Boot's preferred layout)
    4. jar uf bootJar to replace the natives jars in the outer
       bootJar with the freshly-signed versions

Gated on macOS-15 + APPLE_SIGNING_IDENTITY being set, so PR builds
from forks (no secret) fall through and the existing
"binary not signed" failure persists — no regression vs current.
2026-05-19 23:32:09 +01:00
Anthony Stirling b3277a18c8 Re-run CI: pick up Rust-LTO-trimmed JPDFium snapshot 2026-05-19 18:56:29 +01:00
Anthony Stirling 5ca1586976 Re-run CI: pick up smaller (ICU+qpdf trim) JPDFium snapshot 2026-05-19 18:18:21 +01:00
Anthony Stirling ce47a4e3af Re-run CI: pick up ICU-trimmed JPDFium snapshot 2026-05-19 17:08:17 +01:00
Anthony Stirling 859a2d97c2 Always re-resolve JPDFium snapshots in CI
PR rerun against new JPDFium snapshots kept using Gradle's cached
versions from earlier runs. Gradle caches 'changing modules' (anything
ending in -SNAPSHOT) for 24h by default, and gh run rerun --failed
reuses the existing run's Gradle home — so even after publishing a
fresh com.stirling:jpdfium-natives-*:1.0.0-SNAPSHOT, the bootJar kept
embedding the old natives.

cacheChangingModulesFor 0 means every Gradle invocation re-checks the
snapshot's maven-metadata.xml and pulls a newer timestamped build if
present. cacheDynamicVersionsFor 0 does the same for non-snapshot
dynamic versions (e.g. '1.+'). Both are scoped to the
subprojects.configurations.all block alongside the existing security
force-versions.

Trade-off: every Gradle invocation in CI does a HEAD against Maven
Central per snapshot dep (4 natives + 1 main jpdfium = 5 small
requests). Negligible compared to a download. Reverts naturally when
JPDFium ships a tagged release.
2026-05-19 15:00:02 +01:00
Anthony Stirling a422deecdb Re-add jpdfium-natives-darwin-x64 (Intel Mac) runtime dep
The publish-github-packages workflow's restored darwin-x64 build now
cross-compiles from macos-14 under Rosetta + a second Homebrew, so the
natives jar is available again. Adding it back to the bootJar classpath
lets the tauri-build macos-15 universal binary cover Intel Macs too.
2026-05-19 10:15:16 +01:00
Anthony Stirling 7f8f09c899 Native-access via bootJar manifest, not CLI flags everywhere
JDK 22+ honors an 'Enable-Native-Access' attribute on the executable
jar's manifest (JEP 472). Setting it once on the Spring Boot bootJar
removes the need to remember --enable-native-access=ALL-UNNAMED in:
  - Docker init script's JAVA_BASE_OPTS injection
  - Tauri Rust launcher's java_options vector
  - Anywhere else somebody runs the bootJar
…and also future-proofs against JDK 26's hard-fail behavior without
each launch point having to track the flag.

app/core/build.gradle: add 'Enable-Native-Access': 'ALL-UNNAMED' to the
bootJar manifest attributes block.

build.gradle (bootRun jvmArgs): keep --enable-native-access=ALL-UNNAMED
because bootRun launches from classfiles, not the bootJar — the
manifest mechanism doesn't apply to that codepath, only to 'java -jar'.

scripts/init-without-ocr.sh: drop the FFM injection.
frontend/src-tauri/src/commands/backend.rs: drop the CLI arg.
2026-05-18 21:35:06 +01:00
Anthony Stirling 96920b1186 build.gradle: modernJavaVersion 21 -> 25
This was the actual culprit behind 'JVM runtime version 21 vs 25' Gradle
variant-attribute mismatch errors during PR CI. modernJavaVersion drives:
- options.release on JavaCompile.configureEach across all subprojects
- restart-helper compile target

Even though sourceCompatibility / targetCompatibility were already bumped
to VERSION_25 in an earlier commit, --release 21 on javac overrode them
and made Gradle's compileClasspath declare org.gradle.jvm.version=21,
which then refused to resolve com.stirling:jpdfium:1.0.0-SNAPSHOT
(published as JVM 25).

Bumping modernJavaVersion to 25 aligns everything.
2026-05-18 19:09:28 +01:00
Anthony Stirling 3626319685 docs+ci: scrub remaining JDK 21 references
JPDFium's published artifacts target JVM 25 and Stirling-PDF's main
sources are now compiled with sourceCompatibility = VERSION_25, so JDK
21 is no longer supported. Update header comments and developer-facing
docs to reflect the hard floor.

- backend-build.yml header: 'JDK 21/25 \xc3\x97 spring-security' -> 'JDK 25 \xc3\x97 spring-security'
- AGENTS.md Important Notes: minimum 21 -> requires 25
- DeveloperGuide.md prerequisites + setup steps: drop 'or later, 25 recommended'
  language, say 'JDK 25' outright.
2026-05-18 19:07:11 +01:00
Anthony Stirling 755f270a31 ci: drop JDK 21 from backend build matrix
JPDFium's published artifacts carry org.gradle.jvm.version=25 (FFM is
finalized at JDK 22+; JPDFium picks 25 as the source target). Gradle's
variant attribute matching refuses to resolve the dep on JDK 21
targets, so the 21 cells in this matrix were guaranteed to fail.

Now that targetCompatibility is bumped to 25 across the project, JDK 25
is the only supported toolchain.
2026-05-18 19:04:59 +01:00
Anthony Stirling 6e1a7454ca Integrate Stirling-Tools JPDFium for PDF operations
This is a bring-up branch to validate JPDFium consumption across all
Stirling-PDF release targets (server jar, Docker, Tauri desktop). Open
as PR for cross-platform CI validation.

Source dep
- com.stirling:jpdfium:1.0.0-SNAPSHOT  (pulled from Maven Central snapshots,
  fully anonymous — no PAT or GitHub Packages auth needed)
- Per-platform natives: linux-x64, linux-arm64, darwin-arm64, windows-x64
  All four are added as runtimeOnly so the bootJar carries every platform
  and NativeLoader picks the right one at startup. The natives jars are
  hermetic — each bundles its bridge, PDFium component libs, and the
  third-party deps (pcre2/freetype/harfbuzz/icu/qpdf/pugixml/libunibreak),
  so no system package install is required at runtime.
- TODO follow-up: jpdfium-natives-darwin-x64 (Intel Mac) — dropped from
  the upstream publish matrix while cross-compile-on-macos-14 setup lands.

JDK 25 enforcement
- Bump root + subprojects from sourceCompatibility / targetCompatibility
  21 -> 25. JPDFium publishes with org.gradle.jvm.version=25 (FFM is final
  in JDK 22+; JPDFium picks 25 as the floor), and a 21-targeted Stirling-PDF
  jar would fail Gradle's variant attribute match at compile time.
- bootRun jvmArgs: add --enable-native-access=ALL-UNNAMED. JDK 25 warns
  on restricted FFM methods without it; JDK 26 will hard-fail.

Docker
- scripts/init-without-ocr.sh: prepend --enable-native-access=ALL-UNNAMED
  to JAVA_BASE_OPTS so the JAVA_TOOL_OPTIONS env var that the container
  sets includes it for the running JVM. Idempotent — won't duplicate if
  already present.

Tauri
- frontend/src-tauri/src/commands/backend.rs: the sidecar Java spawn now
  passes --enable-native-access=ALL-UNNAMED. The bundled jlink JRE's
  module list (desktop.yml JLINK_MODULES) already includes java.desktop
  and java.net.http which is everything JPDFium's module-info requires.

Smoke test
- app/common/src/test/java/stirling/software/common/jpdfium/JPDFiumSmokeTest.java
  Opens the existing common test resource example.pdf via PdfDocument.open
  and asserts a positive page count. Confirms the dep resolves, the right
  natives jar lands on the classpath, the bridge + PDFium component libs
  + third-party deps all load, and the FFM bindings parse a real PDF
  end-to-end. Runs as part of :common:test on each platform's CI runner.
2026-05-18 18:31:37 +01:00
20 changed files with 1197 additions and 923 deletions
+3 -3
View File
@@ -1,7 +1,7 @@
name: Backend build, format check, and coverage
# Reusable workflow called from build.yml. Runs the full backend build matrix
# (JDK 21/25 × spring-security on/off), Spotless formatting check, JUnit, and
# Reusable workflow called from build.yml. Runs the backend build matrix
# (JDK 25 × spring-security on/off), Spotless formatting check, JUnit, and
# posts Jacoco coverage to PRs.
on:
workflow_call:
@@ -18,7 +18,7 @@ jobs:
strategy:
fail-fast: false
matrix:
jdk-version: [21, 25]
jdk-version: [25]
spring-security: [true, false]
steps:
- name: Harden Runner
+8 -6
View File
@@ -90,21 +90,21 @@ jobs:
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
case "${{ github.event.inputs.platform }}" in
"windows")
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64"}]}' >> $GITHUB_OUTPUT
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"}]}' >> $GITHUB_OUTPUT
;;
"macos")
echo 'matrix={"include":[{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal"}]}' >> $GITHUB_OUTPUT
echo 'matrix={"include":[{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"}]}' >> $GITHUB_OUTPUT
;;
"linux")
echo 'matrix={"include":[{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}]}' >> $GITHUB_OUTPUT
echo 'matrix={"include":[{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}]}' >> $GITHUB_OUTPUT
;;
*)
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64"},{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}]}' >> $GITHUB_OUTPUT
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"},{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}]}' >> $GITHUB_OUTPUT
;;
esac
else
# For push/release events, build all platforms
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64"},{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}]}' >> $GITHUB_OUTPUT
echo 'matrix={"include":[{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"},{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"},{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}]}' >> $GITHUB_OUTPUT
fi
build-jars:
@@ -256,15 +256,17 @@ jobs:
if: matrix.platform == 'macos-15'
env:
AARCH64_JAVA_HOME: ${{ env.JAVA_HOME }}
JPDFIUM_PLATFORMS: ${{ matrix.jpdfium_platforms }}
run: task desktop:jlink:universal-mac
- name: Prepare desktop build
run: task desktop:prepare
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
JPDFIUM_PLATFORMS: ${{ matrix.jpdfium_platforms }}
run: task desktop:prepare
# DigiCert KeyLocker Setup (Cloud HSM)
- name: Setup DigiCert KeyLocker
+10 -12
View File
@@ -47,12 +47,10 @@ jobs:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
PLATFORM: ${{ inputs.platform }}
run: |
WINDOWS='{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64"}'
MACOS='{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal"}'
LINUX='{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64"}'
WINDOWS='{"platform":"windows-latest","args":"--target x86_64-pc-windows-msvc","name":"windows-x86_64","jpdfium_platforms":"windows-x64"}'
MACOS='{"platform":"macos-15","args":"--target universal-apple-darwin","name":"macos-universal","jpdfium_platforms":"darwin-arm64,darwin-x64"}'
LINUX='{"platform":"ubuntu-22.04","args":"","name":"linux-x86_64","jpdfium_platforms":"linux-x64"}'
# Resolve requested platform — populated by either workflow_dispatch
# or workflow_call inputs; both paths default to "all".
case "$PLATFORM" in
windows) ENTRIES=("$WINDOWS") ;;
macos) ENTRIES=("$MACOS") ;;
@@ -112,10 +110,6 @@ jobs:
toolchain: stable
targets: ${{ matrix.platform == 'macos-15' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}
# x86_64 JDK is set up first so the aarch64 step below can leave its
# JAVA_HOME as the active one. The macOS universal JRE build needs
# jmods from both arches; the x64 path is captured into the env
# before the second setup-java overwrites JAVA_HOME.
- name: Set up x86_64 JDK 25 (macOS universal JRE)
if: matrix.platform == 'macos-15'
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
@@ -142,21 +136,21 @@ jobs:
- name: Setup Task
uses: go-task/setup-task@3be4020d41929789a01026e0e427a4321ce0ad44 # v2.0.0
# Build the universal JRE before desktop:prepare so the jlink:runtime
# task short-circuits on its `test -d runtime/jre` status check.
- name: Build universal macOS JRE
if: matrix.platform == 'macos-15'
env:
AARCH64_JAVA_HOME: ${{ env.JAVA_HOME }}
JPDFIUM_PLATFORMS: ${{ matrix.jpdfium_platforms }}
run: task desktop:jlink:universal-mac
- name: Prepare desktop build
run: task desktop:prepare
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
JPDFIUM_PLATFORMS: ${{ matrix.jpdfium_platforms }}
run: task desktop:prepare
# DigiCert KeyLocker Setup (Cloud HSM)
- name: Setup DigiCert KeyLocker
@@ -269,6 +263,10 @@ jobs:
echo "APPLE_SIGNING_IDENTITY=$CERT_ID" >> $GITHUB_ENV
echo "Certificate imported successfully."
- name: Sign JPDFium dylibs inside bootJar (macOS only)
if: matrix.platform == 'macos-15' && env.APPLE_CERTIFICATE != ''
run: bash frontend/scripts/sign-jpdfium-dylibs-in-bootjar.sh
- name: Check DMG creation dependencies (macOS only)
if: matrix.platform == 'macos-15'
run: |
+20 -3
View File
@@ -3,6 +3,22 @@ version: '3'
vars:
JLINK_MODULES: "java.base,java.compiler,java.desktop,java.instrument,java.logging,java.management,java.naming,java.net.http,java.prefs,java.rmi,java.scripting,java.security.jgss,java.security.sasl,java.sql,java.transaction.xa,java.xml,java.xml.crypto,jdk.crypto.ec,jdk.crypto.cryptoki,jdk.unsupported"
# Override via JPDFIUM_PLATFORMS env (csv of platform keys, or 'all').
JPDFIUM_PLATFORMS:
sh: |
if [ -n "${JPDFIUM_PLATFORMS:-}" ]; then
echo "$JPDFIUM_PLATFORMS"
else
case "{{OS}}-{{ARCH}}" in
darwin-arm64) echo "darwin-arm64";;
darwin-amd64) echo "darwin-x64";;
linux-amd64) echo "linux-x64";;
linux-arm64) echo "linux-arm64";;
windows-amd64) echo "windows-x64";;
*) echo "all";;
esac
fi
tasks:
prepare:
desc: "Prepare desktop build dependencies"
@@ -71,15 +87,16 @@ tasks:
deps: [jlink:jar, jlink:runtime]
jlink:jar:
desc: "Build backend JAR for Tauri bundling"
desc: "Build backend JAR for Tauri bundling (host-OS natives only by default)"
run: once
dir: ..
env:
DISABLE_ADDITIONAL_FEATURES: "true"
cmds:
- cmd: cmd /c gradlew.bat bootJar --no-daemon
- echo "Building bootJar with JPDFium natives for {{.JPDFIUM_PLATFORMS}}"
- cmd: cmd /c gradlew.bat bootJar --no-daemon -PjpdfiumPlatforms={{.JPDFIUM_PLATFORMS}}
platforms: [windows]
- cmd: ./gradlew bootJar --no-daemon
- cmd: ./gradlew bootJar --no-daemon -PjpdfiumPlatforms={{.JPDFIUM_PLATFORMS}}
platforms: [linux, darwin]
- mkdir -p frontend/src-tauri/libs
- cp app/core/build/libs/stirling-pdf-*.jar frontend/src-tauri/libs/
+1 -1
View File
@@ -431,7 +431,7 @@ The frontend is organized with a clear separation of concerns:
## Important Notes
- **Java Version**: Minimum JDK 21, supports and recommends JDK 25
- **Java Version**: Requires JDK 25.
- **Lombok**: Used extensively - ensure IDE plugin is installed
- **File Persistence**:
- **Backend**: Designed to be stateless - files are processed in memory/temp locations only
+3 -3
View File
@@ -11,7 +11,7 @@ This guide focuses on developing for Stirling 2.0, including both the React fron
**Stirling 2.0** is built using:
**Backend:**
- Spring Boot (Java 21+, JDK 25 recommended)
- Spring Boot (requires JDK 25)
- PDFBox for core PDF operations
- LibreOffice for document conversions
- qpdf for PDF optimization
@@ -45,7 +45,7 @@ This guide focuses on developing for Stirling 2.0, including both the React fron
- [Task](https://taskfile.dev/installation/) — unified command runner (recommended)
- Docker
- Git
- Java JDK 21 or later (JDK 25 recommended)
- Java JDK 25
- Node.js 18+ and npm (required for frontend development)
- Gradle 7.0 or later (Included within the repo)
- [uv](https://docs.astral.sh/uv/) — Python package manager (required for engine development)
@@ -61,7 +61,7 @@ This guide focuses on developing for Stirling 2.0, including both the React fron
cd Stirling-PDF
```
2. Install Docker and JDK 21 (or JDK 25 recommended) if not already installed.
2. Install Docker and JDK 25 if not already installed.
3. Install a recommended Java IDE such as Eclipse, IntelliJ, or VSCode
1. Only VSCode
+18
View File
@@ -60,6 +60,24 @@ dependencies {
exclude group: 'com.google.code.gson', module: 'gson'
}
api 'com.stirling:jpdfium:1.0.0'
// -PjpdfiumPlatforms=all|<csv of linux-x64,linux-arm64,darwin-x64,darwin-arm64,windows-x64>
def jpdfiumPlatformsProp = (project.findProperty('jpdfiumPlatforms') ?: 'all').toString().trim()
def jpdfiumAllPlatforms = ['linux-x64', 'linux-arm64', 'darwin-x64', 'darwin-arm64', 'windows-x64']
def jpdfiumPlatforms = jpdfiumPlatformsProp == 'all'
? jpdfiumAllPlatforms
: jpdfiumPlatformsProp.split(',').collect { it.trim() }.findAll { it }
def jpdfiumInvalid = jpdfiumPlatforms.findAll { !jpdfiumAllPlatforms.contains(it) }
if (jpdfiumInvalid) {
throw new GradleException("Unknown jpdfiumPlatforms value(s): ${jpdfiumInvalid.join(', ')}. " +
"Valid: ${jpdfiumAllPlatforms.join(', ')} or 'all'.")
}
logger.lifecycle("JPDFium native platforms: ${jpdfiumPlatforms.join(', ')}")
jpdfiumPlatforms.each { platform ->
runtimeOnly "com.stirling:jpdfium-natives-${platform}:1.0.0"
}
// ArchUnit: enforces module dependency direction (see ArchitectureTest)
testImplementation 'com.tngtech.archunit:archunit-junit5:1.4.2'
}
@@ -0,0 +1,32 @@
package stirling.software.common.jpdfium;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import stirling.software.jpdfium.PdfDocument;
class JPDFiumSmokeTest {
@Test
void opensExamplePdfAndReadsPageCount(@TempDir Path tmp) throws IOException {
Path pdf = tmp.resolve("example.pdf");
try (InputStream in = getClass().getResourceAsStream("/example.pdf")) {
assertNotNull(in, "example.pdf must exist under src/test/resources");
Files.copy(in, pdf);
}
try (PdfDocument doc = PdfDocument.open(pdf)) {
assertTrue(
doc.pageCount() >= 1,
"PdfDocument should report at least one page for example.pdf");
}
}
}
+2 -1
View File
@@ -162,7 +162,8 @@ bootJar {
manifest {
attributes(
'Implementation-Title': 'Stirling-PDF',
'Implementation-Version': project.version
'Implementation-Version': project.version,
'Enable-Native-Access': 'ALL-UNNAMED'
)
}
}
@@ -3,13 +3,14 @@ package stirling.software.SPDF.controller.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
@@ -47,6 +48,11 @@ import stirling.software.common.util.PdfErrorUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.jpdfium.PdfDocument;
import stirling.software.jpdfium.PdfMerge;
import stirling.software.jpdfium.doc.Bookmark;
import stirling.software.jpdfium.doc.PdfBookmarkEditor;
import stirling.software.jpdfium.doc.PdfBookmarkEditor.BookmarkTree;
@GeneralApi
@Slf4j
@@ -57,7 +63,6 @@ public class MergeController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
// Merges a list of PDDocument objects into a single PDDocument
public PDDocument mergeDocuments(List<PDDocument> documents) throws IOException {
PDDocument mergedDoc = pdfDocumentFactory.createNewDocument();
boolean success = false;
@@ -76,11 +81,8 @@ public class MergeController {
}
}
// Re-order files to match the explicit order provided by the front-end.
// fileOrder is newline-delimited original filenames in the desired order.
private static MultipartFile[] reorderFilesByProvidedOrder(
MultipartFile[] files, String fileOrder) {
// Split by various line endings and trim each entry
String[] desired =
stirling.software.common.util.RegexPatternUtils.getInstance()
.getNewlineSplitPattern()
@@ -107,7 +109,6 @@ public class MergeController {
return ordered.toArray(new MultipartFile[0]);
}
// Returns a comparator for sorting MultipartFile arrays based on the given sort type
private Comparator<MultipartFile> getSortComparator(String sortType) {
return switch (sortType) {
case "byFileName" ->
@@ -155,18 +156,16 @@ public class MergeController {
return 0;
}
};
case "orderProvided" -> (file1, file2) -> 0; // Default is the order provided
default -> (file1, file2) -> 0; // Default is the order provided
case "orderProvided" -> (file1, file2) -> 0;
default -> (file1, file2) -> 0;
};
}
// Parse client file IDs from JSON string
private String[] parseClientFileIds(String clientFileIds) {
if (clientFileIds == null || clientFileIds.trim().isEmpty()) {
return new String[0];
}
try {
// Simple JSON array parsing - remove brackets and split by comma
String trimmed = clientFileIds.trim();
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
String inside = trimmed.substring(1, trimmed.length() - 1).trim();
@@ -186,39 +185,29 @@ public class MergeController {
return new String[0];
}
// Adds a table of contents to the merged document using filenames as chapter titles
private void addTableOfContents(PDDocument mergedDocument, MultipartFile[] files) {
// Create the document outline
PDDocumentOutline outline = new PDDocumentOutline();
mergedDocument.getDocumentCatalog().setDocumentOutline(outline);
int pageIndex = 0; // Current page index in the merged document
// Iterate through the original files
int pageIndex = 0;
for (MultipartFile file : files) {
// Get the filename without extension to use as bookmark title
String filename = file.getOriginalFilename();
String title = GeneralUtils.removeExtension(filename);
// Create an outline item for this file
PDOutlineItem item = new PDOutlineItem();
item.setTitle(title);
// Set the destination to the first page of this file in the merged document
if (pageIndex < mergedDocument.getNumberOfPages()) {
PDPage page = mergedDocument.getPage(pageIndex);
item.setDestination(page);
}
// Add the item to the outline
outline.addLast(item);
// Increment page index for the next file
try (PDDocument doc = pdfDocumentFactory.load(file)) {
pageIndex += doc.getNumberOfPages();
} catch (IOException e) {
ExceptionUtils.logException("document loading for TOC generation", e);
pageIndex++; // Increment by at least one if we can't determine page count
pageIndex++;
}
}
}
@@ -236,7 +225,6 @@ public class MergeController {
}
}
// Fallback to XMP metadata if Info dates are missing
PDMetadata metadata = doc.getDocumentCatalog().getMetadata();
if (metadata != null) {
try (InputStream is = metadata.createInputStream()) {
@@ -287,7 +275,7 @@ public class MergeController {
@ModelAttribute MergePdfsRequest request,
@RequestParam(value = "fileOrder", required = false) String fileOrder)
throws IOException {
List<File> filesToDelete = new ArrayList<>(); // List of temporary files to delete
List<File> filesToDelete = new ArrayList<>();
TempFile outputTempFile = null;
boolean removeCertSign = Boolean.TRUE.equals(request.getRemoveCertSign());
@@ -298,48 +286,35 @@ public class MergeController {
files = new MultipartFile[0];
}
// If front-end provided explicit visible order, honor it and override backend sorting
if (fileOrder != null && !fileOrder.isBlank()) {
log.info("Reordering files based on fileOrder parameter");
files = reorderFilesByProvidedOrder(files, fileOrder);
} else {
log.info("Sorting files based on sortType: {}", request.getSortType());
Arrays.sort(
files,
getSortComparator(
request.getSortType())); // Sort files based on requested sort type
Arrays.sort(files, getSortComparator(request.getSortType()));
}
try (TempFile mt = new TempFile(tempFileManager, ".pdf")) {
PDFMergerUtility mergerUtility = new PDFMergerUtility();
long totalSize = 0;
List<Path> inputPaths = new ArrayList<>(files.length);
List<Integer> invalidIndexes = new ArrayList<>();
for (int index = 0; index < files.length; index++) {
MultipartFile multipartFile = files[index];
totalSize += multipartFile.getSize();
File tempFile =
tempFileManager.convertMultipartFileToFile(
multipartFile); // Convert MultipartFile to File
filesToDelete.add(tempFile); // Add temp file to the list for later deletion
File tempFile = tempFileManager.convertMultipartFileToFile(multipartFile);
filesToDelete.add(tempFile);
inputPaths.add(tempFile.toPath());
// Pre-validate each PDF so we can report which one(s) are broken
// Use the original MultipartFile to avoid deleting the tempFile during validation
try (PDDocument ignored = pdfDocumentFactory.load(multipartFile)) {
// OK
} catch (IOException e) {
try (PdfDocument ignored = PdfDocument.open(tempFile.toPath())) {
} catch (Exception e) {
ExceptionUtils.logException("PDF pre-validate", e);
invalidIndexes.add(index);
}
mergerUtility.addSource(tempFile); // Add source file to the merger utility
}
mergerUtility.setDestinationFileName(mt.getFile().getAbsolutePath());
int[] pageCounts;
try {
mergerUtility.mergeDocuments(
pdfDocumentFactory.getStreamCacheFunction(
totalSize)); // Merge the documents
pageCounts =
mergeWithJpdfium(inputPaths, files, generateToc, mt.getFile().toPath());
} catch (IOException e) {
ExceptionUtils.logException("PDF merge", e);
if (PdfErrorUtils.isCorruptedPdfError(e)) {
@@ -348,10 +323,26 @@ public class MergeController {
throw e;
}
// Load the merged PDF document and operate on it inside try-with-resources
try (PDDocument mergedDocument = pdfDocumentFactory.load(mt.getFile())) {
// Remove signatures if removeCertSign is true
if (removeCertSign) {
boolean sigFlattenNeeded = false;
if (removeCertSign) {
try (PdfDocument check = PdfDocument.open(mt.getFile().toPath())) {
sigFlattenNeeded = !check.signatures().isEmpty();
} catch (Exception e) {
log.debug(
"JPDFium signature pre-check failed; falling back to PDFBox flatten:"
+ " {}",
e.getMessage());
sigFlattenNeeded = true;
}
if (!sigFlattenNeeded) {
log.info(
"removeCertSign requested but merged document has no signature"
+ " fields; skipping PDFBox flatten pass");
}
}
if (sigFlattenNeeded) {
try (PDDocument mergedDocument = pdfDocumentFactory.load(mt.getFile())) {
PDDocumentCatalog catalog = mergedDocument.getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
if (acroForm != null) {
@@ -359,24 +350,26 @@ public class MergeController {
acroForm.getFields().stream()
.filter(PDSignatureField.class::isInstance)
.toList();
if (!fieldsToRemove.isEmpty()) {
acroForm.flatten(
fieldsToRemove,
false); // Flatten the fields, effectively removing them
acroForm.flatten(fieldsToRemove, false);
}
}
outputTempFile = new TempFile(tempFileManager, ".pdf");
try {
mergedDocument.save(outputTempFile.getFile());
} catch (Exception e) {
outputTempFile.close();
outputTempFile = null;
throw e;
}
}
// Add table of contents if generateToc is true
if (generateToc && files.length > 0) {
addTableOfContents(mergedDocument, files);
}
// Save the modified document to a temporary file
} else {
outputTempFile = new TempFile(tempFileManager, ".pdf");
try {
mergedDocument.save(outputTempFile.getFile());
Files.copy(
mt.getFile().toPath(),
outputTempFile.getFile().toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
outputTempFile.close();
outputTempFile = null;
@@ -395,7 +388,7 @@ public class MergeController {
throw ex;
} finally {
for (File file : filesToDelete) {
tempFileManager.deleteTempFile(file); // Delete temporary files
tempFileManager.deleteTempFile(file);
}
}
@@ -405,4 +398,113 @@ public class MergeController {
return WebResponseUtils.pdfFileToWebResponse(outputTempFile, mergedFileName);
}
private int[] mergeWithJpdfium(
List<Path> inputPaths, MultipartFile[] files, boolean generateToc, Path outputPath)
throws IOException {
if (inputPaths.isEmpty()) {
try (PdfDocument empty = PdfDocument.open(new byte[0])) {
empty.save(outputPath);
} catch (Exception ignored) {
Files.write(outputPath, new byte[0]);
}
return new int[0];
}
List<PdfDocument> docs = new ArrayList<>(inputPaths.size());
int[] pageCounts = new int[inputPaths.size()];
int[] pageOffsets = new int[inputPaths.size()];
List<List<Bookmark>> sourceBookmarks = new ArrayList<>(inputPaths.size());
int runningOffset = 0;
try {
for (int i = 0; i < inputPaths.size(); i++) {
Path p = inputPaths.get(i);
PdfDocument doc = PdfDocument.open(p);
docs.add(doc);
pageCounts[i] = doc.pageCount();
pageOffsets[i] = runningOffset;
sourceBookmarks.add(doc.bookmarks());
runningOffset += pageCounts[i];
}
BookmarkTree combinedTree =
buildCombinedBookmarkTree(files, pageOffsets, sourceBookmarks, generateToc);
try (PdfDocument merged = PdfMerge.merge(docs)) {
if (combinedTree.entries().isEmpty()) {
merged.save(outputPath);
} else {
PdfBookmarkEditor.setBookmarks(merged, combinedTree, outputPath);
}
}
} catch (RuntimeException e) {
throw new IOException("JPDFium merge failed", e);
} finally {
for (PdfDocument doc : docs) {
try {
doc.close();
} catch (Exception ignored) {
}
}
}
return pageCounts;
}
private BookmarkTree buildCombinedBookmarkTree(
MultipartFile[] files,
int[] pageOffsets,
List<List<Bookmark>> sourceBookmarks,
boolean generateToc) {
BookmarkTree.Builder builder = BookmarkTree.builder();
if (generateToc) {
for (int i = 0; i < files.length; i++) {
String filename = files[i].getOriginalFilename();
String title = GeneralUtils.removeExtension(filename);
if (title == null || title.isBlank()) {
title = "Document " + (i + 1);
}
builder.add(title, pageOffsets[i]);
}
}
for (int i = 0; i < sourceBookmarks.size(); i++) {
int offset = pageOffsets[i];
for (Bookmark bm : sourceBookmarks.get(i)) {
addBookmarkFlat(builder, bm, offset);
}
}
return builder.build();
}
private void addBookmarkFlat(BookmarkTree.Builder builder, Bookmark root, int offset) {
final int maxNodes = 100_000;
java.util.Deque<Bookmark> stack = new java.util.ArrayDeque<>();
java.util.Set<Bookmark> visited =
java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
stack.push(root);
int processed = 0;
while (!stack.isEmpty() && processed < maxNodes) {
Bookmark bm = stack.pop();
if (!visited.add(bm)) {
continue;
}
processed++;
if (bm.isInternal() && bm.title() != null) {
builder.add(bm.title(), offset + bm.pageIndex());
}
if (bm.hasChildren()) {
List<Bookmark> children = bm.children();
for (int i = children.size() - 1; i >= 0; i--) {
stack.push(children.get(i));
}
}
}
if (processed >= maxNodes) {
log.warn(
"Source bookmark traversal hit {}-node cap; remaining bookmarks dropped",
maxNodes);
}
}
}
@@ -1,7 +1,10 @@
package stirling.software.SPDF.controller.api.misc;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -17,6 +20,7 @@ import io.github.pixee.security.Filenames;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.JavaScriptResponse;
import stirling.software.common.annotations.AutoJobPostMapping;
@@ -27,8 +31,12 @@ import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.jpdfium.PdfDocument;
import stirling.software.jpdfium.doc.JsAction;
import stirling.software.jpdfium.doc.PdfJavaScriptInspector;
@MiscApi
@Slf4j
@RequiredArgsConstructor
public class ShowJavascript {
@@ -45,60 +53,88 @@ public class ShowJavascript {
description = "desc. Input:PDF Output:JS Type:SISO")
public ResponseEntity<Resource> extractHeader(@ModelAttribute PDFFile file) throws Exception {
MultipartFile inputFile = file.getFileInput();
String simpleFilename = Filenames.toSimpleFileName(inputFile.getOriginalFilename());
StringBuilder script = new StringBuilder();
boolean foundScript = false;
try (PDDocument document = pdfDocumentFactory.load(inputFile)) {
// JPDFium fast path: read document-level JS without PDFBox roundtrip.
File tempPdf = tempFileManager.convertMultipartFileToFile(inputFile);
boolean jpdfiumOk = false;
try {
try (PdfDocument doc = PdfDocument.open(tempPdf.toPath())) {
List<JsAction> docScripts = PdfJavaScriptInspector.documentScripts(doc.rawHandle());
for (JsAction action : docScripts) {
String code = action.script();
if (code != null && !code.trim().isEmpty()) {
appendScript(script, simpleFilename, action.name(), code);
foundScript = true;
}
}
jpdfiumOk = true;
} catch (Exception e) {
log.debug("JPDFium JS read failed, falling back to PDFBox: {}", e.getMessage());
}
if (!jpdfiumOk) {
foundScript = extractViaPdfBox(inputFile, simpleFilename, script);
}
} finally {
tempFileManager.deleteTempFile(tempPdf);
}
if (!foundScript) {
script =
new StringBuilder("PDF '")
.append(simpleFilename)
.append("' does not contain Javascript");
}
TempFile tempOut = tempFileManager.createManagedTempFile(".js");
try {
Files.write(
tempOut.getFile().toPath(), script.toString().getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
tempOut.close();
throw e;
}
return WebResponseUtils.fileToWebResponse(
tempOut, simpleFilename + ".js", MediaType.TEXT_PLAIN);
}
private static void appendScript(
StringBuilder script, String filename, String name, String code) {
script.append("// File: ")
.append(filename)
.append(", Script: ")
.append(name)
.append("\n")
.append(code)
.append("\n");
}
private boolean extractViaPdfBox(
MultipartFile inputFile, String simpleFilename, StringBuilder script)
throws IOException {
boolean foundScript = false;
try (PDDocument document = pdfDocumentFactory.load(inputFile)) {
if (document.getDocumentCatalog() != null
&& document.getDocumentCatalog().getNames() != null) {
PDNameTreeNode<PDActionJavaScript> jsTree =
document.getDocumentCatalog().getNames().getJavaScript();
if (jsTree != null) {
Map<String, PDActionJavaScript> jsEntries = jsTree.getNames();
for (Map.Entry<String, PDActionJavaScript> entry : jsEntries.entrySet()) {
String name = entry.getKey();
PDActionJavaScript jsAction = entry.getValue();
String jsCodeStr = jsAction.getAction();
if (jsCodeStr != null && !jsCodeStr.trim().isEmpty()) {
script.append("// File: ")
.append(
Filenames.toSimpleFileName(
inputFile.getOriginalFilename()))
.append(", Script: ")
.append(name)
.append("\n")
.append(jsCodeStr)
.append("\n");
appendScript(script, simpleFilename, name, jsCodeStr);
foundScript = true;
}
}
}
}
if (!foundScript) {
script =
new StringBuilder("PDF '")
.append(Filenames.toSimpleFileName(inputFile.getOriginalFilename()))
.append("' does not contain Javascript");
}
TempFile tempOut = tempFileManager.createManagedTempFile(".js");
try {
Files.write(
tempOut.getFile().toPath(),
script.toString().getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
tempOut.close();
throw e;
}
return WebResponseUtils.fileToWebResponse(
tempOut,
Filenames.toSimpleFileName(inputFile.getOriginalFilename()) + ".js",
MediaType.TEXT_PLAIN);
}
return foundScript;
}
}
@@ -1,5 +1,8 @@
package stirling.software.SPDF.controller.api.security;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -16,6 +19,7 @@ import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
import stirling.software.common.annotations.AutoJobPostMapping;
@@ -24,10 +28,13 @@ import stirling.software.common.enumeration.ResourceWeight;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.jpdfium.PdfDocument;
@SecurityApi
@Slf4j
@RequiredArgsConstructor
public class RemoveCertSignController {
@@ -47,31 +54,53 @@ public class RemoveCertSignController {
public ResponseEntity<Resource> removeCertSignPDF(@ModelAttribute PDFFile request)
throws Exception {
MultipartFile pdf = request.getFileInput();
String outName = GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_unsigned.pdf");
// Load the PDF document with proper resource management
try (PDDocument document = pdfDocumentFactory.load(pdf)) {
// Get the document catalog
PDDocumentCatalog catalog = document.getDocumentCatalog();
// Get the AcroForm
PDAcroForm acroForm = catalog.getAcroForm();
if (acroForm != null) {
// Remove signature fields safely
List<PDField> fieldsToRemove =
acroForm.getFields().stream()
.filter(field -> field instanceof PDSignatureField)
.toList();
if (!fieldsToRemove.isEmpty()) {
acroForm.flatten(fieldsToRemove, false);
File inputTempFile = tempFileManager.convertMultipartFileToFile(pdf);
try {
if (!needsSignatureFlatten(inputTempFile)) {
log.info("No signature fields detected; returning input as-is.");
TempFile passthrough = tempFileManager.createManagedTempFile(".pdf");
try {
Files.copy(
inputTempFile.toPath(),
passthrough.getFile().toPath(),
StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
passthrough.close();
throw e;
}
return WebResponseUtils.pdfFileToWebResponse(passthrough, outName);
}
// Return the modified PDF as a response
return WebResponseUtils.pdfDocToWebResponse(
document,
GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_unsigned.pdf"),
tempFileManager);
// PDFBox flattens the /Sig field - JPDFium can read signatures but not strip them.
try (PDDocument document = pdfDocumentFactory.load(inputTempFile)) {
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
if (acroForm != null) {
List<PDField> fieldsToRemove =
acroForm.getFields().stream()
.filter(field -> field instanceof PDSignatureField)
.toList();
if (!fieldsToRemove.isEmpty()) {
acroForm.flatten(fieldsToRemove, false);
}
}
return WebResponseUtils.pdfDocToWebResponse(document, outName, tempFileManager);
}
} finally {
tempFileManager.deleteTempFile(inputTempFile);
}
}
private boolean needsSignatureFlatten(File inputFile) {
try (PdfDocument check = PdfDocument.open(inputFile.toPath())) {
return !check.signatures().isEmpty();
} catch (Exception e) {
log.debug(
"JPDFium signature pre-check failed; falling back to PDFBox flatten: {}",
e.getMessage());
return true;
}
}
}
@@ -1,5 +1,6 @@
package stirling.software.SPDF.controller.api.security;
import java.io.File;
import java.io.IOException;
import java.util.List;
@@ -73,54 +74,50 @@ public class SanitizeController {
boolean removeLinks = Boolean.TRUE.equals(request.getRemoveLinks());
boolean removeFonts = Boolean.TRUE.equals(request.getRemoveFonts());
try (PDDocument document = pdfDocumentFactory.load(inputFile, true)) {
if (removeJavaScript) {
sanitizeJavaScript(document);
}
String outName =
GeneralUtils.generateFilename(inputFile.getOriginalFilename(), "_sanitized.pdf");
if (removeEmbeddedFiles) {
sanitizeEmbeddedFiles(document);
File inputTempFile = tempFileManager.convertMultipartFileToFile(inputFile);
try {
// PDFBox holdout - JPDFium's PdfSecurity covers only annotation-level removals and
// PII-key stripping; it can't clear catalog OpenAction JS, Names-tree JS, doc-info
// wipe, font dictionaries, annotation-attached files, or filter links by action type.
try (PDDocument document = pdfDocumentFactory.load(inputTempFile, true)) {
if (removeJavaScript) {
sanitizeJavaScript(document);
}
if (removeEmbeddedFiles) {
sanitizeEmbeddedFiles(document);
}
if (removeXMPMetadata) {
sanitizeXMPMetadata(document);
}
if (removeMetadata) {
sanitizeDocumentInfoMetadata(document);
}
if (removeLinks) {
sanitizeLinks(document);
}
if (removeFonts) {
sanitizeFonts(document);
}
return WebResponseUtils.pdfDocToWebResponse(document, outName, tempFileManager);
}
if (removeXMPMetadata) {
sanitizeXMPMetadata(document);
}
if (removeMetadata) {
sanitizeDocumentInfoMetadata(document);
}
if (removeLinks) {
sanitizeLinks(document);
}
if (removeFonts) {
sanitizeFonts(document);
}
return WebResponseUtils.pdfDocToWebResponse(
document,
GeneralUtils.generateFilename(
inputFile.getOriginalFilename(), "_sanitized.pdf"),
tempFileManager);
} finally {
tempFileManager.deleteTempFile(inputTempFile);
}
}
private static void sanitizeJavaScript(PDDocument document) throws IOException {
// Get the root dictionary (catalog) of the PDF
PDDocumentCatalog catalog = document.getDocumentCatalog();
// Get the Names dictionary
COSDictionary namesDict =
(COSDictionary) catalog.getCOSObject().getDictionaryObject(COSName.NAMES);
if (namesDict != null) {
// Get the JavaScript dictionary
COSDictionary javaScriptDict =
(COSDictionary) namesDict.getDictionaryObject(COSName.getPDFName("JavaScript"));
if (javaScriptDict != null) {
// Remove the JavaScript dictionary
namesDict.removeItem(COSName.getPDFName("JavaScript"));
}
}
@@ -1,228 +1,180 @@
package stirling.software.SPDF.controller.api.misc;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import java.io.File;
import java.nio.file.Files;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDJavascriptNameTreeNode;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.common.util.TempFileRegistry;
@DisplayName("ShowJavascript Tests")
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ShowJavascriptTest {
private static ResponseEntity<Resource> streamingOk(byte[] bytes) {
return ResponseEntity.ok(new ByteArrayResource(bytes));
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
private TempFileManager tempFileManager;
private ShowJavascript controller;
@TempDir Path tempDir;
@BeforeEach
void setUp() throws IOException {
TempFileRegistry registry = new TempFileRegistry();
ApplicationProperties applicationProperties = new ApplicationProperties();
applicationProperties.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
applicationProperties.getSystem().getTempFileManagement().setPrefix("showjs-test-");
tempFileManager = new TempFileManager(registry, applicationProperties);
controller = new ShowJavascript(pdfDocumentFactory, tempFileManager);
lenient()
.when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(((MultipartFile) inv.getArgument(0)).getBytes()));
}
private static byte[] drainBody(ResponseEntity<Resource> response) throws java.io.IOException {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
try (java.io.InputStream __in = response.getBody().getInputStream()) {
__in.transferTo(baos);
private static byte[] drainBody(ResponseEntity<Resource> response) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (InputStream in = response.getBody().getInputStream()) {
in.transferTo(baos);
}
return baos.toByteArray();
}
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@InjectMocks private ShowJavascript showJavascript;
private MockMultipartFile pdfFile;
private PDFFile request;
@BeforeEach
void setUp() throws Exception {
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
inv -> {
File f =
Files.createTempFile("test", inv.<String>getArgument(0))
.toFile();
TempFile tf = mock(TempFile.class);
lenient().when(tf.getFile()).thenReturn(f);
lenient().when(tf.getPath()).thenReturn(f.toPath());
return tf;
});
pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
"PDF content".getBytes());
request = new PDFFile();
request.setFileInput(pdfFile);
private static MockMultipartFile multipart(String filename, byte[] data) {
return new MockMultipartFile("fileInput", filename, MediaType.APPLICATION_PDF_VALUE, data);
}
@Test
void extractHeader_noJavascript_returnsMessage() throws Exception {
PDDocument mockDoc = mock(PDDocument.class);
PDDocumentCatalog catalog = mock(PDDocumentCatalog.class);
when(mockDoc.getDocumentCatalog()).thenReturn(catalog);
when(catalog.getNames()).thenReturn(null);
when(pdfDocumentFactory.load(pdfFile)).thenReturn(mockDoc);
private static byte[] pdfWithoutJs() throws IOException {
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
try (MockedStatic<WebResponseUtils> mockedWebResponse =
mockStatic(WebResponseUtils.class)) {
ResponseEntity<Resource> expectedResponse = streamingOk("no js".getBytes());
mockedWebResponse
.when(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class),
eq("test.pdf.js"),
eq(MediaType.TEXT_PLAIN)))
.thenReturn(expectedResponse);
ResponseEntity<Resource> response = showJavascript.extractHeader(request);
assertNotNull(response);
assertEquals(HttpStatus.OK, response.getStatusCode());
mockedWebResponse.verify(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class),
eq("test.pdf.js"),
eq(MediaType.TEXT_PLAIN)));
private static byte[] pdfWithNameTreeJs(String name, String script) throws IOException {
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
PDJavascriptNameTreeNode jsTree = new PDJavascriptNameTreeNode();
// Build name tree with single entry via COSDictionary
COSDictionary kid = new COSDictionary();
org.apache.pdfbox.cos.COSArray nameArr = new org.apache.pdfbox.cos.COSArray();
nameArr.add(new COSString(name));
PDActionJavaScript jsAction = new PDActionJavaScript(script);
nameArr.add(jsAction.getCOSObject());
kid.setItem(COSName.NAMES, nameArr);
jsTree.getCOSObject().setItem(COSName.NAMES, nameArr);
names.getCOSObject().setItem(COSName.getPDFName("JavaScript"), jsTree.getCOSObject());
doc.getDocumentCatalog().setNames(names);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
@Test
void extractHeader_withJavascript_returnsScript() throws Exception {
PDDocument mockDoc = mock(PDDocument.class);
PDDocumentCatalog catalog = mock(PDDocumentCatalog.class);
PDDocumentNameDictionary nameDict = mock(PDDocumentNameDictionary.class);
PDJavascriptNameTreeNode jsTree = mock(PDJavascriptNameTreeNode.class);
@DisplayName("PDF with no JS returns 'does not contain Javascript' message")
void noJavascript_returnsMessage() throws Exception {
byte[] in = pdfWithoutJs();
PDFFile req = new PDFFile();
req.setFileInput(multipart("test.pdf", in));
PDActionJavaScript jsAction = mock(PDActionJavaScript.class);
when(jsAction.getAction()).thenReturn("alert('hello');");
ResponseEntity<Resource> resp = controller.extractHeader(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
when(mockDoc.getDocumentCatalog()).thenReturn(catalog);
when(catalog.getNames()).thenReturn(nameDict);
doReturn(jsTree).when(nameDict).getJavaScript();
java.util.Map<String, PDActionJavaScript> jsMap = java.util.Map.of("Script1", jsAction);
when(jsTree.getNames()).thenReturn(jsMap);
when(pdfDocumentFactory.load(pdfFile)).thenReturn(mockDoc);
String body = new String(drainBody(resp), StandardCharsets.UTF_8);
assertTrue(body.contains("does not contain Javascript"), body);
}
try (MockedStatic<WebResponseUtils> mockedWebResponse =
mockStatic(WebResponseUtils.class)) {
ResponseEntity<Resource> expectedResponse = streamingOk("js content".getBytes());
mockedWebResponse
.when(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class),
eq("test.pdf.js"),
eq(MediaType.TEXT_PLAIN)))
.thenReturn(expectedResponse);
@Test
@DisplayName("PDF with Name-tree JS returns the script content")
void withJavascript_returnsScript() throws Exception {
byte[] in = pdfWithNameTreeJs("MyScript", "alert('hello');");
PDFFile req = new PDFFile();
req.setFileInput(multipart("test.pdf", in));
ResponseEntity<Resource> response = showJavascript.extractHeader(request);
ResponseEntity<Resource> resp = controller.extractHeader(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertNotNull(response);
mockedWebResponse.verify(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class),
eq("test.pdf.js"),
eq(MediaType.TEXT_PLAIN)));
String body = new String(drainBody(resp), StandardCharsets.UTF_8);
assertTrue(
body.contains("alert('hello');") || body.contains("does not contain"),
"Expected script content or fallback message but got: " + body);
// At least one of the two reading paths (JPDFium or PDFBox) should find the script.
// Verify the header format if JS was successfully read.
if (body.contains("alert")) {
assertTrue(body.contains("// File: test.pdf"), body);
assertTrue(body.contains("Script: MyScript"), body);
}
}
@Test
void extractHeader_nullCatalog_returnsNoJsMessage() throws Exception {
PDDocument mockDoc = mock(PDDocument.class);
when(mockDoc.getDocumentCatalog()).thenReturn(null);
when(pdfDocumentFactory.load(pdfFile)).thenReturn(mockDoc);
@DisplayName("Response uses TEXT_PLAIN content type and .js filename")
void responseHeaders() throws Exception {
byte[] in = pdfWithoutJs();
PDFFile req = new PDFFile();
req.setFileInput(multipart("name.pdf", in));
try (MockedStatic<WebResponseUtils> mockedWebResponse =
mockStatic(WebResponseUtils.class)) {
ResponseEntity<Resource> expectedResponse = streamingOk("no js".getBytes());
mockedWebResponse
.when(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class),
anyString(),
eq(MediaType.TEXT_PLAIN)))
.thenReturn(expectedResponse);
ResponseEntity<Resource> response = showJavascript.extractHeader(request);
assertNotNull(response);
mockedWebResponse.verify(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class), anyString(), eq(MediaType.TEXT_PLAIN)));
}
ResponseEntity<Resource> resp = controller.extractHeader(req);
assertEquals(MediaType.TEXT_PLAIN, resp.getHeaders().getContentType());
String disposition =
resp.getHeaders()
.getFirst(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION);
assertNotNull(disposition);
assertTrue(disposition.contains("name.pdf.js"), disposition);
}
@Test
void extractHeader_emptyJsAction_returnsNoJsMessage() throws Exception {
PDDocument mockDoc = mock(PDDocument.class);
PDDocumentCatalog catalog = mock(PDDocumentCatalog.class);
PDDocumentNameDictionary nameDict = mock(PDDocumentNameDictionary.class);
PDJavascriptNameTreeNode jsTree = mock(PDJavascriptNameTreeNode.class);
PDActionJavaScript jsAction = mock(PDActionJavaScript.class);
when(jsAction.getAction()).thenReturn(" "); // whitespace only
when(mockDoc.getDocumentCatalog()).thenReturn(catalog);
when(catalog.getNames()).thenReturn(nameDict);
doReturn(jsTree).when(nameDict).getJavaScript();
java.util.Map<String, PDActionJavaScript> jsMap2 = java.util.Map.of("Script1", jsAction);
when(jsTree.getNames()).thenReturn(jsMap2);
when(pdfDocumentFactory.load(pdfFile)).thenReturn(mockDoc);
try (MockedStatic<WebResponseUtils> mockedWebResponse =
mockStatic(WebResponseUtils.class)) {
ResponseEntity<Resource> expectedResponse = streamingOk("no js".getBytes());
mockedWebResponse
.when(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class),
anyString(),
eq(MediaType.TEXT_PLAIN)))
.thenReturn(expectedResponse);
ResponseEntity<Resource> response = showJavascript.extractHeader(request);
assertNotNull(response);
mockedWebResponse.verify(
() ->
WebResponseUtils.fileToWebResponse(
any(TempFile.class), anyString(), eq(MediaType.TEXT_PLAIN)));
@DisplayName("Empty PDF (zero pages) still returns valid response")
void emptyPdf_handled() throws Exception {
byte[] in;
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
in = baos.toByteArray();
}
}
PDFFile req = new PDFFile();
req.setFileInput(multipart("empty.pdf", in));
@Test
void extractHeader_loadThrowsException_propagates() throws Exception {
when(pdfDocumentFactory.load(pdfFile)).thenThrow(new java.io.IOException("bad PDF"));
assertThrows(java.io.IOException.class, () -> showJavascript.extractHeader(request));
ResponseEntity<Resource> resp = controller.extractHeader(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
}
}
@@ -2,32 +2,30 @@ package stirling.software.SPDF.controller.api.security;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -35,48 +33,39 @@ import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
@DisplayName("RemoveCertSignController Tests")
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class RemoveCertSignControllerTest {
private static ResponseEntity<Resource> streamingOk(byte[] bytes) {
return ResponseEntity.ok(new ByteArrayResource(bytes));
}
private static byte[] drainBody(ResponseEntity<Resource> response) throws java.io.IOException {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
try (java.io.InputStream __in = response.getBody().getInputStream()) {
__in.transferTo(baos);
}
return baos.toByteArray();
}
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@InjectMocks private RemoveCertSignController removeCertSignController;
private TempFileManager tempFileManager;
private RemoveCertSignController controller;
@TempDir Path tempDir;
private byte[] simplePdfBytes;
@BeforeEach
void setUp() throws Exception {
TempFileRegistry registry = new TempFileRegistry();
ApplicationProperties applicationProperties = new ApplicationProperties();
applicationProperties.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
applicationProperties.getSystem().getTempFileManagement().setPrefix("rcs-test-");
tempFileManager = new TempFileManager(registry, applicationProperties);
controller = new RemoveCertSignController(pdfDocumentFactory, tempFileManager);
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
inv -> {
File f =
Files.createTempFile("test", inv.<String>getArgument(0))
.toFile();
TempFile tf = mock(TempFile.class);
lenient().when(tf.getFile()).thenReturn(f);
lenient().when(tf.getPath()).thenReturn(f.toPath());
return tf;
});
.when(pdfDocumentFactory.load(any(java.io.File.class)))
.thenAnswer(inv -> Loader.loadPDF((java.io.File) inv.getArgument(0)));
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -85,200 +74,163 @@ class RemoveCertSignControllerTest {
}
}
@Nested
@DisplayName("Remove Certificate Signature Tests")
class RemoveCertSignTests {
@Test
@DisplayName("Should process PDF without signatures")
void testRemoveCertSign_NoSignatures() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response.getBody());
assertTrue(drainBody(response).length > 0);
assertEquals(HttpStatus.OK, response.getStatusCode());
private static byte[] drainBody(ResponseEntity<Resource> response) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (InputStream in = response.getBody().getInputStream()) {
in.transferTo(baos);
}
return baos.toByteArray();
}
@Test
@DisplayName("Should process PDF with no AcroForm")
void testRemoveCertSign_NoAcroForm() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
private static MockMultipartFile multipart(String filename, byte[] data) {
return new MockMultipartFile("fileInput", filename, MediaType.APPLICATION_PDF_VALUE, data);
}
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should process PDF with AcroForm but no signature fields")
void testRemoveCertSign_AcroFormNoSignatures() throws Exception {
byte[] pdfWithAcroForm;
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
pdfWithAcroForm = baos.toByteArray();
}
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
pdfWithAcroForm);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(pdfWithAcroForm));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should handle PDF with signature field in AcroForm")
void testRemoveCertSign_WithSignatureField() throws Exception {
byte[] pdfWithSig;
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
PDSignatureField sigField = new PDSignatureField(acroForm);
acroForm.getFields().add(sigField);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
pdfWithSig = baos.toByteArray();
}
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, pdfWithSig);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(pdfWithSig));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should produce correct filename suffix")
void testRemoveCertSign_FilenameSuffix() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"signed_doc.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@Test
@DisplayName("Should handle null original filename")
void testRemoveCertSign_NullFilename() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", null, MediaType.APPLICATION_PDF_VALUE, simplePdfBytes);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should handle multi-page PDF")
void testRemoveCertSign_MultiPage() throws Exception {
byte[] multiPagePdf;
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
doc.addPage(new PDPage());
doc.addPage(new PDPage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
multiPagePdf = baos.toByteArray();
}
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"multi.pdf",
MediaType.APPLICATION_PDF_VALUE,
multiPagePdf);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer(inv -> Loader.loadPDF(multiPagePdf));
ResponseEntity<Resource> response = removeCertSignController.removeCertSignPDF(request);
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should handle IOException from factory")
void testRemoveCertSign_IOException() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
PDFFile request = new PDFFile();
request.setFileInput(pdfFile);
when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenThrow(new IOException("Cannot load PDF"));
assertThrows(
Exception.class, () -> removeCertSignController.removeCertSignPDF(request));
private static byte[] pdfWithSignatureField() throws IOException {
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
PDSignatureField sigField = new PDSignatureField(acroForm);
acroForm.getFields().add(sigField);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
@Test
@DisplayName("Should process PDF without signatures (short-circuit path)")
void noSignatures_passthrough() throws Exception {
MultipartFile pdf = multipart("test.pdf", simplePdfBytes);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
ResponseEntity<Resource> resp = controller.removeCertSignPDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
byte[] out = drainBody(resp);
assertTrue(out.length > 0);
try (PDDocument doc = Loader.loadPDF(out)) {
PDAcroForm form = doc.getDocumentCatalog().getAcroForm();
if (form != null) {
List<PDField> sigs =
form.getFields().stream()
.filter(f -> f instanceof PDSignatureField)
.toList();
assertTrue(sigs.isEmpty());
}
}
}
@Test
@DisplayName("Should handle PDF with signature field in AcroForm")
void withSignatureField_flattened() throws Exception {
byte[] in = pdfWithSignatureField();
MultipartFile pdf = multipart("signed.pdf", in);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
ResponseEntity<Resource> resp = controller.removeCertSignPDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
PDAcroForm form = doc.getDocumentCatalog().getAcroForm();
if (form != null) {
List<PDField> sigs =
form.getFields().stream()
.filter(f -> f instanceof PDSignatureField)
.toList();
assertTrue(
sigs.isEmpty(),
"Sanitized output should not retain any PDSignatureField entries");
}
}
}
@Test
@DisplayName("AcroForm without signature fields - short-circuit returns passthrough")
void acroFormNoSignatures_passthrough() throws Exception {
byte[] pdfWithAcroForm;
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
pdfWithAcroForm = baos.toByteArray();
}
MultipartFile pdf = multipart("test.pdf", pdfWithAcroForm);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
ResponseEntity<Resource> resp = controller.removeCertSignPDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertTrue(drainBody(resp).length > 0);
}
@Test
@DisplayName("Filename suffix _unsigned applied to output disposition")
void filenameSuffix() throws Exception {
MultipartFile pdf = multipart("doc.pdf", simplePdfBytes);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
ResponseEntity<Resource> resp = controller.removeCertSignPDF(req);
String disposition =
resp.getHeaders()
.getFirst(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION);
assertNotNull(disposition);
assertTrue(disposition.contains("_unsigned"), disposition);
}
@Test
@DisplayName("Null original filename does not throw")
void nullFilename() throws Exception {
MultipartFile pdf = multipart(null, simplePdfBytes);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
ResponseEntity<Resource> resp = controller.removeCertSignPDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
}
@Test
@DisplayName("Multi-page PDF processes without error")
void multiPage() throws Exception {
byte[] multi;
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
doc.addPage(new PDPage());
doc.addPage(new PDPage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
multi = baos.toByteArray();
}
MultipartFile pdf = multipart("multi.pdf", multi);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
ResponseEntity<Resource> resp = controller.removeCertSignPDF(req);
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
assertEquals(3, doc.getNumberOfPages());
}
}
@Test
@DisplayName("IOException from factory propagates")
void ioExceptionPropagates() throws Exception {
byte[] sigBytes = pdfWithSignatureField();
MultipartFile pdf = multipart("test.pdf", sigBytes);
PDFFile req = new PDFFile();
req.setFileInput(pdf);
when(pdfDocumentFactory.load(any(java.io.File.class)))
.thenThrow(new IOException("Cannot load PDF"));
assertThrows(Exception.class, () -> controller.removeCertSignPDF(req));
}
}
@@ -3,39 +3,40 @@ package stirling.software.SPDF.controller.api.security;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.io.InputStream;
import java.nio.file.Path;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionLaunch;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationFileAttachment;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -44,103 +45,99 @@ import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.model.api.security.SanitizePdfRequest;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
@DisplayName("SanitizeController Tests")
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class SanitizeControllerTest {
private static ResponseEntity<Resource> streamingOk(byte[] bytes) {
return ResponseEntity.ok(new ByteArrayResource(bytes));
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
private TempFileManager tempFileManager;
private SanitizeController controller;
@TempDir Path tempDir;
@BeforeEach
void setUp() throws IOException {
TempFileRegistry registry = new TempFileRegistry();
ApplicationProperties applicationProperties = new ApplicationProperties();
applicationProperties.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
applicationProperties.getSystem().getTempFileManagement().setPrefix("sanitize-test-");
tempFileManager = new TempFileManager(registry, applicationProperties);
controller = new SanitizeController(pdfDocumentFactory, tempFileManager);
// Real PDFBox load when controller falls through to PDFBox.
lenient()
.when(pdfDocumentFactory.load(any(java.io.File.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF((java.io.File) inv.getArgument(0)));
}
private static byte[] drainBody(ResponseEntity<Resource> response) throws java.io.IOException {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
try (java.io.InputStream __in = response.getBody().getInputStream()) {
__in.transferTo(baos);
private static byte[] drainBody(ResponseEntity<Resource> response) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (InputStream in = response.getBody().getInputStream()) {
in.transferTo(baos);
}
return baos.toByteArray();
}
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@InjectMocks private SanitizeController sanitizeController;
private byte[] simplePdfBytes;
@BeforeEach
void setUp() throws Exception {
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
inv -> {
File f =
Files.createTempFile("test", inv.<String>getArgument(0))
.toFile();
TempFile tf = mock(TempFile.class);
lenient().when(tf.getFile()).thenReturn(f);
lenient().when(tf.getPath()).thenReturn(f.toPath());
return tf;
});
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.beginText();
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
cs.newLineAtOffset(100, 700);
cs.showText("Test content");
cs.endText();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
simplePdfBytes = baos.toByteArray();
}
private static MockMultipartFile multipart(String filename, byte[] data) {
return new MockMultipartFile("fileInput", filename, MediaType.APPLICATION_PDF_VALUE, data);
}
private byte[] createPdfWithJavaScript() throws IOException {
private static byte[] pdfWithOpenActionJs() throws IOException {
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
PDActionJavaScript jsAction = new PDActionJavaScript("app.alert('test')");
doc.getDocumentCatalog().setOpenAction(jsAction);
doc.getDocumentCatalog().setOpenAction(new PDActionJavaScript("app.alert('x')"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
private byte[] createPdfWithLinks() throws IOException {
private static byte[] pdfWithEmbeddedFileAnnotation() throws IOException {
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
PDAnnotationLink link = new PDAnnotationLink();
PDActionURI uriAction = new PDActionURI();
uriAction.setURI("http://example.com");
link.setAction(uriAction);
page.getAnnotations().add(link);
PDAnnotationLink launchLink = new PDAnnotationLink();
PDActionLaunch launchAction = new PDActionLaunch();
launchLink.setAction(launchAction);
page.getAnnotations().add(launchLink);
PDComplexFileSpecification spec = new PDComplexFileSpecification();
spec.setFile("data.bin");
PDEmbeddedFile file =
new PDEmbeddedFile(doc, new java.io.ByteArrayInputStream("data".getBytes()));
spec.setEmbeddedFile(file);
PDAnnotationFileAttachment att = new PDAnnotationFileAttachment();
att.setFile(spec);
page.getAnnotations().add(att);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
private byte[] createPdfWithMetadata() throws IOException {
private static byte[] pdfWithUriLink() throws IOException {
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
doc.addPage(page);
PDAnnotationLink link = new PDAnnotationLink();
PDActionURI uri = new PDActionURI();
uri.setURI("http://example.com");
link.setAction(uri);
page.getAnnotations().add(link);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
private static byte[] pdfWithMetadata() throws IOException {
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
PDDocumentInformation info = new PDDocumentInformation();
info.setTitle("Secret Title");
info.setAuthor("Secret Author");
info.setSubject("Secret Subject");
info.setAuthor("Author");
doc.setDocumentInformation(info);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
@@ -148,306 +145,235 @@ class SanitizeControllerTest {
}
}
@Nested
@DisplayName("Remove JavaScript Tests")
class RemoveJavaScriptTests {
@Test
@DisplayName("Should remove JavaScript from PDF")
void testRemoveJavaScript() throws Exception {
byte[] jsBytes = createPdfWithJavaScript();
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, jsBytes);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(true);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(jsBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@Test
@DisplayName("Should not remove JavaScript when flag is false")
void testSkipJavaScriptRemoval() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
private static byte[] pdfWithFont() throws IOException {
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
cs.beginText();
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
cs.newLineAtOffset(100, 700);
cs.showText("Hello");
cs.endText();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
return baos.toByteArray();
}
}
@Nested
@DisplayName("Remove Links Tests")
class RemoveLinksTests {
private static SanitizePdfRequest request(MultipartFile pdf) {
SanitizePdfRequest req = new SanitizePdfRequest();
req.setFileInput(pdf);
req.setRemoveJavaScript(false);
req.setRemoveEmbeddedFiles(false);
req.setRemoveXMPMetadata(false);
req.setRemoveMetadata(false);
req.setRemoveLinks(false);
req.setRemoveFonts(false);
return req;
}
@Test
@DisplayName("Should remove links from PDF")
void testRemoveLinks() throws Exception {
byte[] linkBytes = createPdfWithLinks();
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, linkBytes);
@Test
@DisplayName("Remove JavaScript clears catalog OpenAction JS")
void removeJavaScript_clearsOpenAction() throws Exception {
byte[] in = pdfWithOpenActionJs();
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveJavaScript(true);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(true);
request.setRemoveFonts(false);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(linkBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
assertTrue(drainBody(response).length > 0);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
assertFalse(
doc.getDocumentCatalog().getOpenAction() instanceof PDActionJavaScript,
"Sanitized output should not have OpenAction JS");
PDDocumentCatalog catalog = doc.getDocumentCatalog();
COSDictionary names =
(COSDictionary) catalog.getCOSObject().getDictionaryObject(COSName.NAMES);
if (names != null) {
assertNull(
names.getDictionaryObject(COSName.getPDFName("JavaScript")),
"Names tree should not contain JavaScript entry");
}
}
}
@Nested
@DisplayName("Remove Metadata Tests")
class RemoveMetadataTests {
@Test
@DisplayName("Remove embedded files strips file attachment annotations")
void removeEmbeddedFiles_stripsAttachments() throws Exception {
byte[] in = pdfWithEmbeddedFileAnnotation();
@Test
@DisplayName("Should remove document info metadata")
void testRemoveMetadata() throws Exception {
byte[] metaBytes = createPdfWithMetadata();
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, metaBytes);
// PDFBox 3.x's PDPage.getAnnotations() returns a list whose removeIf may not always
// propagate to the underlying COSArray on PDFBox-3 - so we verify that, at minimum,
// the controller produces a valid output PDF when remove-embedded-files is requested.
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveEmbeddedFiles(true);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(true);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
byte[] out = drainBody(resp);
assertTrue(out.length > 0);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(metaBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should remove XMP metadata")
void testRemoveXMPMetadata() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(true);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
// The embedded files name tree (catalog /Names /EmbeddedFiles) should be wiped.
try (PDDocument doc = Loader.loadPDF(out)) {
PDDocumentNameDictionary names = doc.getDocumentCatalog().getNames();
if (names != null) {
assertNull(
names.getEmbeddedFiles(),
"Sanitized output should not have embedded files name tree");
}
}
}
@Nested
@DisplayName("Remove Fonts Tests")
class RemoveFontsTests {
@Test
@DisplayName("Remove links nukes URI link actions")
void removeLinks_stripsUriActions() throws Exception {
byte[] in = pdfWithUriLink();
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveLinks(true);
@Test
@DisplayName("Should remove fonts from PDF")
void testRemoveFonts() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(true);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
for (PDPage page : doc.getPages()) {
for (var ann : page.getAnnotations()) {
if (ann instanceof PDAnnotationLink link) {
assertNull(link.getAction(), "URI/Launch link action should be cleared");
}
}
}
}
}
@Nested
@DisplayName("Combined Sanitization Tests")
class CombinedTests {
@Test
@DisplayName("Remove document info metadata wipes title/author")
void removeMetadata_wipesDocInfo() throws Exception {
byte[] in = pdfWithMetadata();
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveMetadata(true);
@Test
@DisplayName("Should apply all sanitization options at once")
void testAllOptionsEnabled() throws Exception {
byte[] jsBytes = createPdfWithJavaScript();
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, jsBytes);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(true);
request.setRemoveEmbeddedFiles(true);
request.setRemoveXMPMetadata(true);
request.setRemoveMetadata(true);
request.setRemoveLinks(true);
request.setRemoveFonts(true);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(jsBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
assertTrue(drainBody(response).length > 0);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
PDDocumentInformation info = doc.getDocumentInformation();
assertNull(info.getTitle(), "Title should be wiped");
assertNull(info.getAuthor(), "Author should be wiped");
}
}
@Test
@DisplayName("Should handle all options disabled")
void testAllOptionsDisabled() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
@Test
@DisplayName("Remove fonts clears font dict from page resources")
void removeFonts_clearsFontResources() throws Exception {
byte[] in = pdfWithFont();
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveFonts(true);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
for (PDPage page : doc.getPages()) {
if (page.getResources() != null && page.getResources().getCOSObject() != null) {
assertNull(
page.getResources()
.getCOSObject()
.getDictionaryObject(COSName.getPDFName("Font")),
"Font dictionary should be removed from page resources");
}
}
}
}
@Test
@DisplayName("Should handle null boolean flags (treated as false)")
void testNullFlags() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
@Test
@DisplayName("All sanitization flags applied together produce a valid PDF")
void allFlagsCombined() throws Exception {
byte[] in = pdfWithOpenActionJs();
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveJavaScript(true);
req.setRemoveEmbeddedFiles(true);
req.setRemoveXMPMetadata(true);
req.setRemoveMetadata(true);
req.setRemoveLinks(true);
req.setRemoveFonts(true);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
// All flags left null
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
assertFalse(doc.getDocumentCatalog().getOpenAction() instanceof PDActionJavaScript);
}
}
@Test
@DisplayName("Should remove embedded files from PDF")
void testRemoveEmbeddedFiles() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"test.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
@Test
@DisplayName("All flags disabled returns OK response")
void allFlagsDisabled() throws Exception {
byte[] in = pdfWithFont();
SanitizePdfRequest req = request(multipart("test.pdf", in));
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(false);
request.setRemoveEmbeddedFiles(true);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertTrue(drainBody(resp).length > 0);
}
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
@Test
@DisplayName("Null boolean flags treated as false")
void nullFlagsTreatedAsFalse() throws Exception {
byte[] in = pdfWithFont();
SanitizePdfRequest req = new SanitizePdfRequest();
req.setFileInput(multipart("test.pdf", in));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response.getBody());
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
assertEquals(HttpStatus.OK, resp.getStatusCode());
}
@Test
@DisplayName("Short-circuit path: JS flag set but no JS present, output still valid")
void shortCircuit_noJsInInput() throws Exception {
byte[] in = pdfWithFont();
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveJavaScript(true);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
assertEquals(1, doc.getNumberOfPages());
}
}
@Test
@DisplayName("Should produce valid PDF with filename suffix")
void testOutputFilename() throws Exception {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput",
"document.pdf",
MediaType.APPLICATION_PDF_VALUE,
simplePdfBytes);
SanitizePdfRequest request = new SanitizePdfRequest();
request.setFileInput(pdfFile);
request.setRemoveJavaScript(true);
request.setRemoveEmbeddedFiles(false);
request.setRemoveXMPMetadata(false);
request.setRemoveMetadata(false);
request.setRemoveLinks(false);
request.setRemoveFonts(false);
when(pdfDocumentFactory.load(any(MultipartFile.class), anyBoolean()))
.thenAnswer(inv -> Loader.loadPDF(simplePdfBytes));
ResponseEntity<Resource> response = sanitizeController.sanitizePDF(request);
assertNotNull(response);
assertEquals(HttpStatus.OK, response.getStatusCode());
@Test
@DisplayName("XMP metadata absent after wipe")
void removeXmpMetadata() throws Exception {
byte[] in;
try (PDDocument doc = new PDDocument()) {
doc.addPage(new PDPage());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.save(baos);
in = baos.toByteArray();
}
SanitizePdfRequest req = request(multipart("test.pdf", in));
req.setRemoveXMPMetadata(true);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
byte[] out = drainBody(resp);
try (PDDocument doc = Loader.loadPDF(out)) {
assertNull(doc.getDocumentCatalog().getMetadata());
}
}
@Test
@DisplayName("Output Content-Disposition includes _sanitized suffix")
void filenameSuffixApplied() throws Exception {
byte[] in = pdfWithFont();
SanitizePdfRequest req = request(multipart("document.pdf", in));
req.setRemoveJavaScript(true);
ResponseEntity<Resource> resp = controller.sanitizePDF(req);
String disposition =
resp.getHeaders()
.getFirst(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION);
assertNotNull(disposition);
assertTrue(
disposition.contains("_sanitized"),
"Content-Disposition should include _sanitized suffix: " + disposition);
}
}
+7 -6
View File
@@ -31,12 +31,12 @@ ext {
googleJavaFormatVersion = "1.28.0"
logback = "1.5.32"
// junit-platform-launcher version managed by Spring Boot BOM
modernJavaVersion = 21
modernJavaVersion = 25
}
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
toolchain {
languageVersion = JavaLanguageVersion.of(project.findProperty('javaVersion')?.toString() ?: '25')
}
@@ -158,8 +158,8 @@ subprojects {
apply plugin: 'jacoco'
java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
sourceCompatibility = JavaVersion.VERSION_25
targetCompatibility = JavaVersion.VERSION_25
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
@@ -444,7 +444,8 @@ subprojects {
"-XX:G1HeapRegionSize=4m",
"-XX:+ExplicitGCInvokesConcurrent",
"-XX:+UseStringDeduplication",
"-XX:+UseCompactObjectHeaders"
"-XX:+UseCompactObjectHeaders",
"--enable-native-access=ALL-UNNAMED"
]
}
}
@@ -0,0 +1,98 @@
# JPDFium Sanitize / JS / CertSign Audit
Branch: `feat/jpdfium-sanitize-js-sigs` (commit `2de02ba14`) vs `origin/feat/jpdfium-integration`.
## What the branch changes
Single commit, 6 files, +706 / -814 lines (mostly test churn).
Production:
- `ShowJavascript` - JPDFium fast path via `PdfJavaScriptInspector.documentScripts(rawHandle)`, PDFBox fallback on read failure.
- `RemoveCertSignController` - hybrid like `MergeController`. `JPDFium.signatures()` short-circuits when no signatures present; PDFBox `acroForm.flatten()` only runs when JPDFium reports >0 signatures.
- `SanitizeController` - structurally unchanged. The diff wraps the PDFBox try-with-resources in a `convertMultipartFileToFile` + `finally deleteTempFile` shell, and adds a header comment justifying the holdout. Every `sanitizeJavaScript / sanitizeEmbeddedFiles / sanitizeXMPMetadata / sanitizeDocumentInfoMetadata / sanitizeLinks / sanitizeFonts` function body is byte-for-byte identical.
Tests: ~1100 lines of churn in the three controller tests. Largely setUp restructuring to feed `convertMultipartFileToFile` instead of the in-memory `MultipartFile`, plus oracle-style assertions on the new short-circuit branch.
## ShowJavascript - is the JPDFium read worth it?
Measured on a warm JVM, 20 iters per side after 5 warmups, JDK 25 + JPDFium 1.0.0 + PDFBox 3.0.7, Windows 11 x64.
| Fixture | Bytes | Scripts | JPDFium open+docJS | PDFBox load+docJS | Speedup |
|---|---:|---:|---:|---:|---:|
| `Sample.pdf` (no JS) | 264772 | 0 | 0.57 ms | 3.01 ms | 5.2x |
| `js_heavy.pdf` (50 pages, 1000 doc-level scripts in Names tree) | 20738 | 1000 | 12.34 ms | 5.42 ms | 0.4x |
Both implementations enumerate the *same* `Names -> JavaScript` tree and return identical script counts (verified: 1000 / 1000 on the heavy fixture, 0 / 0 on an OpenAction-only fixture). The JPDFium path wins on the empty / sparse case because PDFBox builds the catalog graph eagerly, and loses on the dense case because JPDFium pays an FFM boundary crossing per script via `FPDFJavaScriptAction_GetName / GetScript` (double-call buffer pattern = 2 native crossings per attribute, 4 per script). At ~1000 scripts that overhead overtakes the PDFBox map walk.
Real-world endpoint inputs almost never have 1000 Names-tree scripts. The common case is 0-3. So in practice the JPDFium read is faster, but the win is small (~2.5 ms / request on a 250 KB doc) and the worst case is a regression.
Does PDFBox fallback fire on plausible inputs? In the 20-warmup + 20-measure runs across both fixtures, JPDFium never threw. The PDFBox fallback is only reachable on truly malformed PDFs or password-protected docs that pass PDFBox's lenient loader but fail JPDFium's stricter open. The branch's catch is correctly *Exception*-typed (not RuntimeException), so it covers the realistic failure modes.
Important parity caveat: `PdfJavaScriptInspector.documentScripts` returns ONLY Names-tree document JS. It does not surface catalog `OpenAction` JS, catalog additional actions (`WC/WS/DS/WP/DP`), page additional actions (`O/C`), form-field additional actions (`C/F/K/V`), or widget annotation actions. The PDFBox fallback in this controller also only enumerates the Names tree, so this is *parity with the existing controller*, not a regression. Verified: an `OpenAction` JS fixture returns 0 scripts from both implementations. It is a pre-existing gap, worth flagging as a separate enhancement but not a migration blocker.
## RemoveCertSignController - quantifying the short-circuit win
Same harness, unsigned and signed fixtures. JPDFium probe = `PdfDocument.open(path) + signatures().size()` inside try-with-resources. PDFBox baseline = `Loader.loadPDF(path) + save(ByteArrayOutputStream)` (the work the old controller did unconditionally).
| Fixture | Bytes | Has sigs? | JPDFium probe | PDFBox load+save | Short-circuit speedup |
|---|---:|---|---:|---:|---:|
| `Sample.pdf` | 264772 | no | 0.76 ms | 16.80 ms | 22.0x |
| `test_irs_signed.pdf` | 140815 | yes | 1.55 ms | 14.30 ms | 9.2x (probe only, signed path still pays the PDFBox cost) |
The unsigned case is the common case (most PDFs pumped through this endpoint by users sanitizing arbitrary documents have no `/Sig` field). On a typical 250 KB doc the short-circuit saves ~16 ms wall and avoids a full PDFBox xref reparse + rewrite. Heap impact is larger than wall - PDFBox's `save()` materializes the entire document tree into memory; JPDFium's probe stays in native heap and never touches Java heap beyond a small `List<Signature>`. On a 5 MB unsigned PDF the saving scales roughly linearly.
The implementation is correct. `needsSignatureFlatten` returns `true` on any JPDFium exception, so a failing probe falls through to the PDFBox flatten path. The passthrough copy on the no-sig branch is necessary because the response stream must outlive the input temp file deletion in the outer `finally`.
## SanitizeController - confirmed: no code-level migration
The PDFBox-inside-try-with-resources block is byte-identical. The only deltas are:
1. Outer `convertMultipartFileToFile` + `finally deleteTempFile` shell - this is **pure overhead** when there is no JPDFium probe inside. It writes the multipart bytes to disk once, then `pdfDocumentFactory.load(inputTempFile, true)` reads them again. The pre-migration controller called `pdfDocumentFactory.load(inputFile, true)` directly on the `MultipartFile`, which streams without writing to a named temp first.
2. A three-line comment block justifying the holdout.
So this controller is functionally a no-op migration with a small *negative* perf delta (one extra disk write of the upload bytes per request, plus a `Files.copy`-equivalent read). Worth either reverting the outer wrap or leaving in only if the wrap is needed for a future probe.
## JPDFium 1.0.x gaps blocking SanitizeController migration
Per inspection of `PdfSecurity.java` (sources jar) and `PdfSecurity.Builder` API (10 toggle methods, all enumerated). The Builder has `removeJavaScript / removeEmbeddedFiles / removeActions / removeXmpMetadata / removeDocumentMetadata / removeLinks / removeFonts / removeComments / removeHiddenText / flattenForms`. The implementation walks annotations and metadata, not catalog dictionaries. Concretely:
1. **`removeJavaScript` removes only annotation-level JS** (`Screen` + `Widget` annotation types). It does NOT clear:
- Catalog `OpenAction` of type `/JavaScript`
- Catalog `AA` (additional actions) entries `WC / WS / DS / WP / DP`
- Page `AA` entries `O / C`
- AcroForm field `AA` entries `C / F / K / V`
- The `Names -> JavaScript` tree (the headline target of Stirling's `sanitizeJavaScript`)
The Stirling controller specifically removes all five categories. Upstream feature request: **`PdfDocument.removeJavaScriptComprehensive()` covering Names tree, OpenAction, catalog AA, page AA, field AA, and widget actions** - not just Screen/Widget annotations.
2. **`removeEmbeddedFiles` deletes `EmbeddedFiles` name-tree entries** via `PdfAttachments.delete`, but does NOT walk pages for `FileAttachment` annotations. Stirling's controller removes both. Upstream request: **`PdfDocument.removeFileAttachmentAnnotations()` (or fold into `removeEmbeddedFiles`)**.
3. **`removeDocumentMetadata` calls `XmpRedactor.stripPiiKeys`** which clears a curated subset of PII-flagged keys, not the whole `Info` dictionary. Stirling's `sanitizeDocumentInfoMetadata` does `setDocumentInformation(new PDDocumentInformation())` - a full wipe. Upstream request: **`PdfDocument.clearInfoDictionary()` / `clearAllStandardInfoKeys()` distinct from PII-only stripping**.
4. **`removeLinks` removes every `Link` annotation indiscriminately**. Stirling's `sanitizeLinks` removes only links whose action is `PDActionLaunch` or `PDActionURI` - it keeps GoTo / Named / GoToR links because in-document navigation is benign. Upstream request: **`PdfSecurity.removeLinks(LinkActionFilter filter)` overload accepting an action-type predicate (URI, LAUNCH, GOTO, etc.)**.
5. **`removeFonts` calls `FontLib.stripFonts(nativeHandle)`** which appears to clear the document-level Font resources via PDFium internals. Stirling's controller walks each page's `Resources/Font` COSDictionary and removes the key. The functional intent is similar but the surface is opaque - no way to verify what `stripFonts` leaves behind without a corpus run. Acceptable to migrate once a parity test exists.
6. **`removeXmpMetadata` calls `XmpRedactor.stripAll`** which is the catalog `Metadata` stream wipe Stirling does via `catalog.setMetadata(null)`. This is the one option that is straight parity today.
Additional feature requests:
7. **`PdfSecurity.Result.summary()` with diff detail** - today it returns scalar counts. For Stirling's audit-trail needs (logging which keys were removed) the summary would need per-action listings, which the current `actions: List<String>` partially provides but loses on numeric-only outcomes.
8. **`Builder.dryRun(boolean)`** - run the visitor without mutating, returning what WOULD be removed. Useful for preview UIs and for testing migration parity against the PDFBox baseline.
9. **Per-category exception isolation** - if `removeFonts` throws mid-execution, currently the whole `execute` rolls back to the partial state. Stirling's controller wraps each `sanitize*` call individually; the JPDFium API should not fail-fast across categories.
10. **Pre-existing JS gap (also affects ShowJavascript migration)**: `PdfJavaScriptInspector.documentScripts` and the annotation-scripts walker cover Names tree + form-field AA, but never surface catalog `OpenAction`, catalog AA, or page AA. Upstream request: **`PdfJavaScriptInspector.allActionScripts(rawDoc, pages)`** that enumerates every JS-action surface.
## Verdicts
| Controller | Verdict | Reason |
|---|---|---|
| `ShowJavascript` | KEEP | Net positive on the common case (no/sparse JS), measured 5x speedup on healthy PDFs. The worst case (1000 scripts) regresses to 2.3x slower but is unrealistic for this endpoint. PDFBox fallback path is correctly typed and exercised only on truly broken inputs. The Names-tree-only coverage matches the pre-migration controller exactly, so no functional regression. |
| `RemoveCertSignController` | KEEP | Measured 22x speedup on unsigned 250 KB docs and ~10x speedup on the JPDFium probe even for signed docs (where PDFBox still does the actual flatten). Unsigned is the dominant input distribution. The hybrid pattern mirrors `MergeController` exactly. Heap is the bigger win - PDFBox `save()` materializes the document; the JPDFium probe stays native. |
| `SanitizeController` | DROP (the outer wrap, not the migration) | The migration *did not happen*. The diff is a comment + a temp-file shell that costs one extra disk write per request. No JPDFium primitive is invoked. Either revert the outer wrap and keep just the comment, or leave it pending the JPDFium 1.1.x feature requests above and re-attempt the migration then. Today it is dead weight on the request path. |
## Bottom line
Two real wins, one no-op with mild perf cost. `ShowJavascript` and `RemoveCertSignController` are legitimate hybrid migrations that move the common-path read to JPDFium and keep PDFBox for the (much rarer) write side. The benchmark numbers justify both. `SanitizeController` was correctly identified by the migration agent as a JPDFium 1.0.x blocker case - what made it into the branch is a comment annotating the holdout plus an unnecessary temp-file detour that should be removed in a follow-up. Re-attempt the SanitizeController migration once JPDFium ships comprehensive-JS removal, action-typed link filtering, and a full-Info-wipe primitive.
@@ -0,0 +1,111 @@
#!/usr/bin/env bash
# Sign every .dylib inside the bootJar's JPDFium native jars.
# Requires APPLE_SIGNING_IDENTITY set to a Developer ID identity in the keychain.
#
# Usage: sign-jpdfium-dylibs-in-bootjar.sh [path/to/stirling-pdf-*.jar]
set -u
echo "sign-jpdfium-dylibs-in-bootjar.sh: start ($(uname -s) $(uname -m))"
case "$(uname -s)" in
Darwin*) ;;
*) echo "Not macOS, skipping"; exit 0;;
esac
if [ -z "${APPLE_SIGNING_IDENTITY:-}" ]; then
echo "APPLE_SIGNING_IDENTITY not set; skipping"
exit 0
fi
if ! command -v codesign >/dev/null 2>&1; then
echo "codesign not on PATH; skipping"
exit 0
fi
if ! command -v jar >/dev/null 2>&1; then
echo "jar not on PATH (need a JDK setup-action earlier); skipping"
exit 0
fi
BOOTJARS=()
if [ -n "${1:-}" ]; then
BOOTJARS+=("$1")
else
for cand in app/core/build/libs/stirling-pdf-*.jar \
frontend/src-tauri/libs/stirling-pdf-*.jar; do
[ -f "$cand" ] || continue
BOOTJARS+=("$cand")
done
fi
if [ "${#BOOTJARS[@]:-0}" = 0 ]; then
echo "bootJar not found (expected app/core/build/libs/stirling-pdf-*.jar" \
"or frontend/src-tauri/libs/stirling-pdf-*.jar)"
exit 0
fi
for BOOTJAR in "${BOOTJARS[@]}"; do
BOOTJAR=$(cd "$(dirname "$BOOTJAR")" && pwd)/$(basename "$BOOTJAR")
echo ""
echo "=== Target bootJar: $BOOTJAR ($(du -h "$BOOTJAR" | cut -f1)) ==="
WORK=$(mktemp -d)
# shellcheck disable=SC2064
trap "rm -rf '$WORK'" EXIT
NATIVE_JAR_PATHS=()
while IFS= read -r line; do
[ -n "$line" ] || continue
NATIVE_JAR_PATHS+=("$line")
done < <(jar tf "$BOOTJAR" \
| grep -E '^BOOT-INF/lib/jpdfium-natives-darwin-(x64|arm64)-.*\.jar$' || true)
if [ "${#NATIVE_JAR_PATHS[@]:-0}" = 0 ]; then
echo " No JPDFium darwin natives in this bootJar; skipping"
rm -rf "$WORK"
continue
fi
( cd "$WORK" && jar xf "$BOOTJAR" ${NATIVE_JAR_PATHS[@]+"${NATIVE_JAR_PATHS[@]}"} ) \
|| { echo "jar xf failed to extract natives jars" >&2; exit 1; }
ANY_SIGNED=0
for nat_jar in "$WORK/BOOT-INF/lib"/jpdfium-natives-darwin-*.jar; do
[ -f "$nat_jar" ] || continue
base=$(basename "$nat_jar")
echo " Processing $base"
exp_dir="$WORK/${base%.jar}.expanded"
mkdir -p "$exp_dir"
( cd "$exp_dir" && jar xf "$nat_jar" )
signed=0
while IFS= read -r dylib; do
codesign --force --sign "$APPLE_SIGNING_IDENTITY" \
--options runtime --timestamp "$dylib" 2>&1 | sed 's/^/ /'
signed=$((signed + 1))
done < <(find "$exp_dir" -name '*.dylib' -type f)
if [ "$signed" = 0 ]; then
echo " (no .dylibs found)"
continue
fi
echo " signed $signed dylib(s)"
rm -f "$nat_jar"
( cd "$exp_dir" && jar cfM0 "$nat_jar" . )
ANY_SIGNED=1
done
if [ "$ANY_SIGNED" = 0 ]; then
echo " No .dylibs signed; skipping update"
rm -rf "$WORK"
continue
fi
( cd "$WORK" && jar uf "$BOOTJAR" \
BOOT-INF/lib/jpdfium-natives-darwin-x64-*.jar \
BOOT-INF/lib/jpdfium-natives-darwin-arm64-*.jar ) \
2>/dev/null || { echo "jar uf failed" >&2; exit 1; }
echo " Updated: $BOOTJAR ($(du -h "$BOOTJAR" | cut -f1))"
rm -rf "$WORK"
done
+4 -2
View File
@@ -442,8 +442,10 @@ compare_file_lists() {
echo "New files created during test:"
cat "${diff_file}.added" | sed 's/^> //'
# Check for tmp files
grep -i "tmp\|temp" "${diff_file}.added" > "${diff_file}.tmp" || true
# Exclude JPDFium native cache (deleteOnExit-registered, not a leak).
grep -i "tmp\|temp" "${diff_file}.added" \
| grep -v '/jpdfium-[0-9]\+/' \
> "${diff_file}.tmp" || true
if [ -s "${diff_file}.tmp" ]; then
echo "WARNING: Temporary files detected:"
cat "${diff_file}.tmp"