Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
318aa054da | ||
|
|
3fb94dde64 | ||
|
|
6ed67c41d4 | ||
|
|
8bffa536fe | ||
|
|
5acaa487fd | ||
|
|
bcbdd8d537 | ||
|
|
2de02ba145 | ||
|
|
2f1fe2c80c | ||
|
|
1051f28c52 | ||
|
|
29ccbf7ae6 | ||
|
|
007c8e17de | ||
|
|
81dbb29be3 | ||
|
|
caef0477a9 | ||
|
|
7682a0dd54 | ||
|
|
f90ed4657a | ||
|
|
a6c7a68242 | ||
|
|
a184b394d6 | ||
|
|
302d04c201 | ||
|
|
68ae9d52fb | ||
|
|
6552ba905c | ||
|
|
ee36b6f616 | ||
|
|
627091f8df | ||
|
|
67a37d3291 | ||
|
|
4b6d4885f4 | ||
|
|
2a151b65f7 | ||
|
|
9458fcd0e2 | ||
|
|
1e8c41425b | ||
|
|
b3277a18c8 | ||
|
|
5ca1586976 | ||
|
|
ce47a4e3af | ||
|
|
859a2d97c2 | ||
|
|
a422deecdb | ||
|
|
7f8f09c899 | ||
|
|
96920b1186 | ||
|
|
3626319685 | ||
|
|
755f270a31 | ||
|
|
6e1a7454ca |
+70
-34
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+51
-22
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+124
-172
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
+175
-223
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user