Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Add PDF/A conversion and compliance validation to Compliance policies (#7220)

Anthony Stirling8de9442b150c
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
index 291bf1dce6..853f8a7f8d 100644
--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
@@ -403,6 +403,7 @@ public class EndpointConfiguration {
addEndpointToGroup("Security", "redact");
addEndpointToGroup("Security", "verify-pdf");
addEndpointToGroup("Security", "accessibility-report");
+ addEndpointToGroup("Security", "validate-compliance");
addEndpointToGroup("Security", "sign");
// Adding endpoints to "Other" group
@@ -539,6 +540,7 @@ public class EndpointConfiguration {
addEndpointToGroup("Java", "verify-pdf");
addEndpointToGroup("Java", "pdf-to-ua");
addEndpointToGroup("Java", "accessibility-report");
+ addEndpointToGroup("Java", "validate-compliance");
addEndpointToGroup("Java", "flatten");
addEndpointToGroup("Java", "unlock-pdf-forms");
addEndpointToGroup("Java", "validate-signature");
@@ -612,6 +614,7 @@ public class EndpointConfiguration {
addEndpointToGroup("veraPDF", "verify-pdf");
addEndpointToGroup("veraPDF", "pdf-to-ua");
addEndpointToGroup("veraPDF", "accessibility-report");
+ addEndpointToGroup("veraPDF", "validate-compliance");
// Pdftohtml dependent endpoints
addEndpointToGroup("Pdftohtml", "pdf-to-html");
diff --git a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
index 4aa49bd26f..3cbfaf9b33 100644
--- a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
@@ -701,6 +701,17 @@ public class ExceptionUtils {
return new IOException(message);
}
+ /**
+ * A document failed the compliance standard it was checked against. Carries an error code so
+ * the policy review surface can name the failure instead of recording it as unrecognised.
+ *
+ * @param detail the whole sentence, already naming the standard and the failing rules
+ */
+ public static ComplianceNotMetException createComplianceNotMetException(String detail) {
+ String message = getMessage(ErrorCode.COMPLIANCE_NOT_MET, detail);
+ return new ComplianceNotMetException(message, ErrorCode.COMPLIANCE_NOT_MET.getCode());
+ }
+
/** Create system requirement exceptions. */
public static FfmpegRequiredException createFfmpegRequiredException() {
String message = getMessage(ErrorCode.FFMPEG_REQUIRED);
@@ -1216,6 +1227,10 @@ public class ExceptionUtils {
"error.invalidComparator",
"Invalid comparator format: only 'greater', 'equal', and 'less' are supported"),
+ // Compliance errors. The caller builds the whole sentence: only it knows the standard,
+ // profile and failing rules.
+ COMPLIANCE_NOT_MET("E074", "error.complianceNotMet", "{0}"),
+
// System errors
MD5_ALGORITHM("E080", "error.md5Algorithm", "MD5 algorithm not available"),
OUT_OF_MEMORY_DPI(
@@ -1277,6 +1292,13 @@ public class ExceptionUtils {
}
}
+ /** Exception thrown when a document fails a compliance standard it was checked against. */
+ public static class ComplianceNotMetException extends BaseAppException {
+ public ComplianceNotMetException(String message, String errorCode) {
+ super(message, null, errorCode);
+ }
+ }
+
/** Exception thrown when FFmpeg is not available on the host system. */
public static class FfmpegRequiredException extends BaseAppException {
public FfmpegRequiredException(String message, String errorCode) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateComplianceController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateComplianceController.java
new file mode 100644
index 0000000000..9cdfed2eec
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/security/ValidateComplianceController.java
@@ -0,0 +1,211 @@
+package stirling.software.SPDF.controller.api.security;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.Locale;
+import java.util.stream.Collectors;
+
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.multipart.MultipartFile;
+import org.verapdf.core.EncryptedPdfException;
+import org.verapdf.core.ModelParsingException;
+import org.verapdf.core.ValidationException;
+
+import io.swagger.v3.oas.annotations.Operation;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.SPDF.model.api.security.PDFVerificationResult;
+import stirling.software.SPDF.service.VeraPDFService;
+import stirling.software.common.annotations.api.SecurityApi;
+import stirling.software.common.model.api.PDFFile;
+import stirling.software.common.model.tool.ToolFormat;
+import stirling.software.common.model.tool.ToolIO;
+import stirling.software.common.util.ExceptionUtils;
+import stirling.software.common.util.WebResponseUtils;
+
+/**
+ * Pipeline-shaped sibling of /verify-pdf, whose JSON answer the policy executor reads as "no files"
+ * and so empties the chain. This one hands the document back, so it composes as a pipeline step.
+ *
+ * <p>Deliberately has no options. Every setting a gate could offer - which standard, whether a
+ * violation stops the run - is a way to turn it off silently, and a run that succeeds while
+ * delivering a non-compliant document is the failure this exists to prevent.
+ */
+@SecurityApi
+@RequiredArgsConstructor
+@Slf4j
+public class ValidateComplianceController {
+
+ // veraPDF marks a document without PDF/A identification metadata with this standard id.
+ private static final String NOT_PDFA_STANDARD_ID = "not-pdfa";
+
+ private static final String DEFAULT_FILENAME = "document.pdf";
+ private static final int MAX_REPORTED_FAILURES = 3;
+ private static final int MAX_FAILURE_MESSAGE_LENGTH = 120;
+ private static final int MAX_DETAIL_LENGTH = 460;
+
+ private final VeraPDFService veraPDFService;
+
+ @PostMapping(value = "/validate-compliance", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+ @ToolIO(produces = ToolFormat.PDF)
+ @Operation(
+ summary = "Check a PDF is PDF/A compliant",
+ description =
+ "Validates the document against PDF/A and returns it unchanged when it"
+ + " conforms. A document that does not - including one that declares no"
+ + " PDF/A at all - fails the request, so this composes as the last step"
+ + " of a pipeline that must not deliver a non-compliant file.")
+ public ResponseEntity<byte[]> validateCompliance(@ModelAttribute PDFFile request)
+ throws IOException {
+
+ MultipartFile file = request.getFileInput();
+
+ if (file == null || file.isEmpty()) {
+ throw ExceptionUtils.createPdfFileRequiredException();
+ }
+
+ String filename = resolveFilename(file.getOriginalFilename());
+
+ byte[] bytes;
+ List<PDFVerificationResult> results;
+ try {
+ // Read once: the same bytes feed validation and the pass-through response.
+ bytes = file.getBytes();
+ results = veraPDFService.validatePDF(new ByteArrayInputStream(bytes));
+ } catch (ValidationException | ModelParsingException e) {
+ // Typed, not a bare RuntimeException: an uncoded one is rendered as "an unexpected
+ // error occurred", losing the sentence that says which document is unreadable.
+ log.error("Could not parse '{}' for compliance validation", filename, e);
+ throw ExceptionUtils.createPdfCorruptedException("during compliance validation", e);
+ } catch (EncryptedPdfException e) {
+ log.error("Cannot validate compliance of encrypted file: {}", filename, e);
+ throw ExceptionUtils.createPdfEncryptionException(e);
+ }
+
+ List<PDFVerificationResult> checked =
+ results == null
+ ? List.of()
+ : results.stream().filter(ValidateComplianceController::isPdfa).toList();
+
+ if (!isCompliant(checked)) {
+ // Typed, not a bare IOException: only an error-coded response reaches the review
+ // surface as a compliance failure rather than an unrecognised one.
+ throw ExceptionUtils.createComplianceNotMetException(
+ buildViolationDetail(checked) + "; the run was stopped.");
+ }
+ log.info("PDF/A compliance check passed for '{}'", filename);
+
+ return WebResponseUtils.bytesToWebResponse(bytes, filename);
+ }
+
+ // The pipeline names the next step's input from this filename, and matches the next step's
+ // accepted types against its extension, so it must keep a .pdf one.
+ private static String resolveFilename(String originalFilename) {
+ if (originalFilename == null || originalFilename.isBlank()) {
+ return DEFAULT_FILENAME;
+ }
+ String filename = originalFilename.trim();
+ return filename.toLowerCase(Locale.ROOT).endsWith(".pdf") ? filename : filename + ".pdf";
+ }
+
+ // Names carry the display form ("PDF/UA-1"), ids the veraPDF flavour ("ua1"); check both.
+ private static boolean isPdfUa(PDFVerificationResult result) {
+ return contains(result.getStandardName(), "pdf/ua")
+ || contains(result.getValidationProfileName(), "pdf/ua")
+ || contains(result.getStandard(), "ua")
+ || contains(result.getValidationProfile(), "ua");
+ }
+
+ private static boolean isPdfa(PDFVerificationResult result) {
+ if (isPdfUa(result)) {
+ return false;
+ }
+ // The "not-pdfa" placeholder is a PDF/A verdict too: the document declares no PDF/A.
+ return result.isDeclaredPdfa()
+ || NOT_PDFA_STANDARD_ID.equals(result.getStandard())
+ || contains(result.getStandardName(), "pdf/a")
+ || contains(result.getValidationProfileName(), "pdf/a");
+ }
+
+ private static boolean contains(String value, String needle) {
+ return value != null && value.toLowerCase(Locale.ROOT).contains(needle);
+ }
+
+ // Fail closed: a document that never declares PDF/A is a miss, not an absence of evidence.
+ private static boolean isCompliant(List<PDFVerificationResult> checked) {
+ return !checked.isEmpty() && checked.stream().allMatch(PDFVerificationResult::isCompliant);
+ }
+
+ private static String buildViolationDetail(List<PDFVerificationResult> checked) {
+ if (checked.isEmpty()) {
+ return "Document is not PDF/A compliant: the document does not declare PDF/A";
+ }
+
+ List<PDFVerificationResult> failing =
+ checked.stream().filter(r -> !r.isCompliant()).toList();
+ int totalFailures =
+ failing.stream().mapToInt(PDFVerificationResult::getTotalFailures).sum();
+ String failures =
+ failing.stream()
+ .flatMap(r -> failuresOf(r).stream())
+ .limit(MAX_REPORTED_FAILURES)
+ .map(ValidateComplianceController::describeFailure)
+ .filter(f -> !f.isEmpty())
+ .collect(Collectors.joining(", "));
+
+ StringBuilder detail =
+ new StringBuilder("Document is not PDF/A compliant (")
+ .append(describeProfile(failing.get(0)))
+ .append("): ")
+ .append(totalFailures)
+ .append(" rule(s) failed");
+ if (!failures.isEmpty()) {
+ detail.append(" - ").append(failures);
+ }
+ return truncate(detail.toString(), MAX_DETAIL_LENGTH);
+ }
+
+ private static List<PDFVerificationResult.ValidationIssue> failuresOf(
+ PDFVerificationResult result) {
+ return result.getFailures() == null ? List.of() : result.getFailures();
+ }
+
+ private static String describeProfile(PDFVerificationResult result) {
+ if (result.getStandardName() != null && !result.getStandardName().isBlank()) {
+ return result.getStandardName();
+ }
+ if (result.getValidationProfileName() != null
+ && !result.getValidationProfileName().isBlank()) {
+ return result.getValidationProfileName();
+ }
+ if (result.getStandard() != null && !result.getStandard().isBlank()) {
+ return result.getStandard();
+ }
+ return "PDF/A";
+ }
+
+ private static String describeFailure(PDFVerificationResult.ValidationIssue issue) {
+ String ruleId = issue.getRuleId();
+ if (ruleId == null || ruleId.isBlank()) {
+ ruleId = issue.getClause();
+ }
+ String message =
+ issue.getMessage() == null
+ ? ""
+ : truncate(issue.getMessage().trim(), MAX_FAILURE_MESSAGE_LENGTH);
+ if (ruleId == null || ruleId.isBlank()) {
+ return message;
+ }
+ return message.isEmpty() ? ruleId : ruleId + ": " + message;
+ }
+
+ private static String truncate(String value, int max) {
+ return value.length() <= max ? value : value.substring(0, max - 3) + "...";
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
index 504dd36f5b..5a80adeffe 100644
--- a/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
+++ b/app/core/src/main/java/stirling/software/SPDF/exception/GlobalExceptionHandler.java
@@ -355,6 +355,26 @@ public class GlobalExceptionHandler {
ex, HttpStatus.INTERNAL_SERVER_ERROR, ErrorTypes.GHOSTSCRIPT, title, request);
}
+ /**
+ * Handle a document that failed the compliance standard it was checked against.
+ *
+ * @param ex the ComplianceNotMetException
+ * @param request the HTTP servlet request
+ * @return ProblemDetail with HTTP 422 UNPROCESSABLE_ENTITY: the request was understood and the
+ * service worked, the document simply does not meet the standard
+ */
+ @ExceptionHandler(ComplianceNotMetException.class)
+ public ResponseEntity<ProblemDetail> handleComplianceNotMet(
+ ComplianceNotMetException ex, HttpServletRequest request) {
+ logException("warn", "Compliance", request, ex, ex.getErrorCode());
+
+ String title =
+ getLocalizedMessage(
+ "error.complianceNotMet.title", ErrorTitles.COMPLIANCE_NOT_MET_DEFAULT);
+ return createProblemDetailResponse(
+ ex, HttpStatus.UNPROCESSABLE_ENTITY, ErrorTypes.COMPLIANCE_NOT_MET, title, request);
+ }
+
/**
* Handle FFmpeg dependency missing errors when media conversion endpoints are invoked.
*
@@ -1132,6 +1152,8 @@ public class GlobalExceptionHandler {
// Delegate to specific BaseAppException handlers
if (appEx instanceof PdfPasswordException) {
return handlePdfPassword((PdfPasswordException) appEx, request);
+ } else if (appEx instanceof ComplianceNotMetException complianceEx) {
+ return handleComplianceNotMet(complianceEx, request);
} else if (appEx instanceof PdfCorruptedException
|| appEx instanceof PdfEncryptionException
|| appEx instanceof OutOfMemoryDpiException) {
@@ -1459,6 +1481,7 @@ public class GlobalExceptionHandler {
static final String NOT_FOUND = "/errors/not-found";
static final String INVALID_ARGUMENT = "/errors/invalid-argument";
static final String IO_ERROR = "/errors/io-error";
+ static final String COMPLIANCE_NOT_MET = "/errors/compliance-not-met";
static final String UNEXPECTED = "/errors/unexpected";
}
@@ -1471,6 +1494,7 @@ public class GlobalExceptionHandler {
static final String PDF_CORRUPTED_DEFAULT = "PDF File Corrupted";
static final String PDF_ENCRYPTION_DEFAULT = "PDF Encryption Error";
static final String APPLICATION_DEFAULT = "Application Error";
+ static final String COMPLIANCE_NOT_MET_DEFAULT = "Compliance Standard Not Met";
static final String CBR_FORMAT_DEFAULT = "Invalid CBR File Format";
static final String CBZ_FORMAT_DEFAULT = "Invalid CBZ File Format";
static final String EML_FORMAT_DEFAULT = "Invalid EML File Format";
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/ValidateComplianceControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/ValidateComplianceControllerTest.java
new file mode 100644
index 0000000000..f1c0db30c6
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/ValidateComplianceControllerTest.java
@@ -0,0 +1,309 @@
+package stirling.software.SPDF.controller.api.security;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+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.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.MockMultipartFile;
+
+import stirling.software.SPDF.model.api.security.PDFVerificationResult;
+import stirling.software.SPDF.service.VeraPDFService;
+import stirling.software.common.model.api.PDFFile;
+import stirling.software.common.util.ExceptionUtils;
+
+@DisplayName("ValidateComplianceController Tests")
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class ValidateComplianceControllerTest {
+
+ @Mock private VeraPDFService veraPDFService;
+
+ @InjectMocks private ValidateComplianceController validateComplianceController;
+
+ private byte[] simplePdfBytes;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ doc.addPage(new PDPage());
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ doc.save(baos);
+ simplePdfBytes = baos.toByteArray();
+ }
+ }
+
+ private PDFFile request(String filename) {
+ MockMultipartFile pdfFile =
+ new MockMultipartFile(
+ "fileInput", filename, MediaType.APPLICATION_PDF_VALUE, simplePdfBytes);
+
+ PDFFile request = new PDFFile();
+ request.setFileInput(pdfFile);
+ return request;
+ }
+
+ private static PDFVerificationResult pdfaResult(boolean compliant) {
+ PDFVerificationResult result = new PDFVerificationResult();
+ result.setStandard("2b");
+ result.setStandardName(compliant ? "PDF/A-2B compliant" : "PDF/A-2B with errors");
+ result.setValidationProfile("2b");
+ result.setValidationProfileName("PDF/A-2B");
+ result.setDeclaredPdfa(true);
+ result.setCompliant(compliant);
+ if (!compliant) {
+ result.addFailure(
+ new PDFVerificationResult.ValidationIssue(
+ "6.2.11.7.2",
+ "The font is not embedded",
+ "page 1",
+ "ISO 19005-2",
+ "6.2.11.7",
+ "2"));
+ }
+ return result;
+ }
+
+ /** What VeraPDFService reports for a document carrying no PDF/A identification metadata. */
+ private static PDFVerificationResult noPdfaDeclarationResult() {
+ PDFVerificationResult result = new PDFVerificationResult();
+ result.setStandard("not-pdfa");
+ result.setStandardName("Not PDF/A (no PDF/A identification metadata)");
+ result.setCompliant(false);
+ result.setDeclaredPdfa(false);
+ result.addFailure(
+ new PDFVerificationResult.ValidationIssue(
+ null,
+ "Document does not declare PDF/A compliance in its XMP metadata.",
+ null,
+ "XMP pdfaid",
+ null,
+ null));
+ return result;
+ }
+
+ private static PDFVerificationResult pdfUaResult(boolean compliant) {
+ PDFVerificationResult result = new PDFVerificationResult();
+ result.setStandard("ua1");
+ result.setStandardName(compliant ? "PDF/UA-1 compliant" : "PDF/UA-1 with errors");
+ result.setValidationProfile("ua1");
+ result.setValidationProfileName("PDF/UA-1");
+ result.setCompliant(compliant);
+ if (!compliant) {
+ result.addFailure(
+ new PDFVerificationResult.ValidationIssue(
+ "7.1-1",
+ "The document is not tagged",
+ "catalog",
+ "ISO 14289-1",
+ "7.1",
+ "1"));
+ }
+ return result;
+ }
+
+ @Nested
+ @DisplayName("Pass-through Tests")
+ class PassThroughTests {
+
+ @Test
+ @DisplayName("Should return the document unchanged when compliant")
+ void testCompliantDocumentPassesThrough() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(true)));
+
+ ResponseEntity<byte[]> response =
+ validateComplianceController.validateCompliance(request("report.pdf"));
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ assertNotNull(response.getBody());
+ assertArrayEquals(simplePdfBytes, response.getBody());
+ assertEquals(MediaType.APPLICATION_PDF, response.getHeaders().getContentType());
+ assertEquals("report.pdf", response.getHeaders().getContentDisposition().getFilename());
+ }
+
+ @Test
+ @DisplayName("Should fall back to a .pdf filename when the original is blank")
+ void testBlankFilenameFallsBack() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(true)));
+
+ ResponseEntity<byte[]> response =
+ validateComplianceController.validateCompliance(request(""));
+
+ assertEquals(
+ "document.pdf", response.getHeaders().getContentDisposition().getFilename());
+ }
+
+ @Test
+ @DisplayName("Should ignore results that are not PDF/A verdicts")
+ void testRequestedStandardFiltersOutOtherResults() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(true), pdfUaResult(false)));
+
+ ResponseEntity<byte[]> response =
+ validateComplianceController.validateCompliance(request("tagged.pdf"));
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ assertArrayEquals(simplePdfBytes, response.getBody());
+ }
+
+ @Test
+ @DisplayName("Should give a non-pdf filename a .pdf extension")
+ void testNonPdfExtensionGetsPdfAppended() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(true)));
+
+ ResponseEntity<byte[]> response =
+ validateComplianceController.validateCompliance(request("report.txt"));
+
+ assertEquals(
+ "report.txt.pdf", response.getHeaders().getContentDisposition().getFilename());
+ }
+ }
+
+ @Nested
+ @DisplayName("Violation Tests")
+ class ViolationTests {
+
+ @Test
+ @DisplayName("Should throw IOException naming the standard and the failing rule")
+ void testNonCompliantFails() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(false)));
+
+ PDFFile request = request("report.pdf");
+
+ IOException exception =
+ assertThrows(
+ IOException.class,
+ () -> validateComplianceController.validateCompliance(request));
+
+ String message = exception.getMessage();
+ assertTrue(message.contains("PDF/A"), message);
+ assertTrue(message.contains("PDF/A-2B"), message);
+ assertTrue(message.contains("6.2.11.7.2"), message);
+ assertTrue(message.contains("The font is not embedded"), message);
+ assertTrue(message.contains("the run was stopped"), message);
+ assertTrue(message.length() < 500, "message should stay short: " + message.length());
+ }
+
+ @Test
+ @DisplayName("Should fail a non-compliant document")
+ void testNonCompliantFailsByDefault() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(false)));
+
+ PDFFile request = request("report.pdf");
+
+ IOException exception =
+ assertThrows(
+ IOException.class,
+ () -> validateComplianceController.validateCompliance(request));
+
+ assertTrue(exception.getMessage().contains("PDF/A"), exception.getMessage());
+ assertTrue(exception.getMessage().contains("6.2.11.7.2"), exception.getMessage());
+ }
+
+ @Test
+ @DisplayName("Should fail closed when PDF/A is not declared")
+ void testRequestedStandardNotDeclaredFailsClosed() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfUaResult(true)));
+
+ PDFFile request = request("report.pdf");
+
+ IOException exception =
+ assertThrows(
+ IOException.class,
+ () -> validateComplianceController.validateCompliance(request));
+
+ assertTrue(exception.getMessage().contains("PDF/A"), exception.getMessage());
+ assertTrue(exception.getMessage().contains("does not declare"), exception.getMessage());
+ }
+
+ @Test
+ @DisplayName("Should carry an error code so the failure is classified, not unrecognised")
+ void testViolationCarriesErrorCode() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(pdfaResult(false)));
+
+ PDFFile request = request("report.pdf");
+
+ ExceptionUtils.ComplianceNotMetException exception =
+ assertThrows(
+ ExceptionUtils.ComplianceNotMetException.class,
+ () -> validateComplianceController.validateCompliance(request));
+
+ assertEquals("E074", exception.getErrorCode());
+ }
+
+ @Test
+ @DisplayName("Should treat a missing PDF/A declaration as non-compliant")
+ void testNoPdfaDeclarationFails() throws Exception {
+ when(veraPDFService.validatePDF(any(InputStream.class)))
+ .thenReturn(List.of(noPdfaDeclarationResult()));
+
+ PDFFile request = request("report.pdf");
+
+ IOException exception =
+ assertThrows(
+ IOException.class,
+ () -> validateComplianceController.validateCompliance(request));
+
+ assertTrue(exception.getMessage().contains("PDF/A"), exception.getMessage());
+ assertTrue(exception.getMessage().contains("XMP metadata"), exception.getMessage());
+ }
+ }
+
+ @Nested
+ @DisplayName("Input Validation Tests")
+ class InputValidationTests {
+
+ @Test
+ @DisplayName("Should throw for null file")
+ void testNullFile() {
+ PDFFile request = new PDFFile();
+ request.setFileInput(null);
+
+ assertThrows(
+ RuntimeException.class,
+ () -> validateComplianceController.validateCompliance(request));
+ }
+
+ @Test
+ @DisplayName("Should throw for empty file")
+ void testEmptyFile() {
+ PDFFile request = new PDFFile();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput",
+ "empty.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ new byte[0]));
+
+ assertThrows(
+ RuntimeException.class,
+ () -> validateComplianceController.validateCompliance(request));
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/DownstreamProblemDetail.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/DownstreamProblemDetail.java
new file mode 100644
index 0000000000..2b2e1c11df
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/DownstreamProblemDetail.java
@@ -0,0 +1,60 @@
+package stirling.software.proprietary.failure;
+
+import org.springframework.web.client.RestClientResponseException;
+
+import lombok.extern.slf4j.Slf4j;
+
+import tools.jackson.core.JacksonException;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+/**
+ * Reads a downstream Problem Details body: the human-readable {@code detail}, and the {@code
+ * errorCode} beside it. Without these a failed run records the whole JSON body behind a status
+ * line, so what the tool actually said never reaches the review surface.
+ */
+@Slf4j
+public final class DownstreamProblemDetail {
+
+ /** Set by {@code GlobalExceptionHandler#createBaseProblemDetail}. */
+ private static final String DETAIL_PROPERTY = "detail";
+
+ /** Set by {@code GlobalExceptionHandler#createProblemDetailResponse} for a coded failure. */
+ private static final String ERROR_CODE_PROPERTY = "errorCode";
+
+ // Static because this is a utility with no state; Jackson mappers are thread-safe.
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private DownstreamProblemDetail() {}
+
+ /** The body's {@code detail}, or null when the body is absent, not JSON, or carries none. */
+ public static String detailOf(RestClientResponseException exception) {
+ return textProperty(exception, DETAIL_PROPERTY);
+ }
+
+ /**
+ * The body's {@code errorCode}, or null when the failure carries none. Lets a run surface the
+ * same code the review surface classifies on, so a client can branch on it too.
+ */
+ public static String errorCodeOf(RestClientResponseException exception) {
+ return textProperty(exception, ERROR_CODE_PROPERTY);
+ }
+
+ private static String textProperty(RestClientResponseException exception, String property) {
+ String body = exception.getResponseBodyAsString();
+ if (body == null || body.isBlank()) {
+ return null;
+ }
+ try {
+ JsonNode node = MAPPER.readTree(body).get(property);
+ if (node == null || !node.isTextual()) {
+ return null;
+ }
+ String text = node.asString().trim();
+ return text.isEmpty() ? null : text;
+ } catch (JacksonException e) {
+ log.debug("Downstream error body was not JSON; keeping the raw failure message");
+ return null;
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
index 9b507555e9..1d1568fbe5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
@@ -44,6 +44,18 @@ public enum FailureKind {
global(OPEN_IN_TOOL, OWNER, OVERFLOW),
global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+ COMPLIANCE_NOT_MET(
+ FailureStage.BLOCKED,
+ FailureSeverity.ERROR,
+ FailureRemedy.NEEDS_FILE_FIX,
+ FailureScope.FILE,
+ errorCodes("E074"),
+ fallback("This document did not meet the compliance standard the policy checks for."),
+ // No automated fix: the document itself has to change, so looking at it leads.
+ global(VIEW_FILE, OWNER, SECONDARY),
+ global(VIEW_IN_PROCESSOR, TEAM_REVIEWER, OVERFLOW),
+ global(DISMISS, ANYONE_WHO_SEES, OVERFLOW)),
+
UNKNOWN(
FailureStage.INTERNAL,
FailureSeverity.ERROR,
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
index 5368ba6c84..9e277c7dbd 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
@@ -33,6 +33,7 @@ import stirling.software.common.service.ResourceMonitor;
import stirling.software.common.service.TaskManager;
import stirling.software.common.util.ExecutorFactory;
import stirling.software.common.util.JobContext;
+import stirling.software.proprietary.failure.DownstreamProblemDetail;
import stirling.software.proprietary.failure.FailureKind;
import stirling.software.proprietary.failure.PolicyFailureRecorder;
import stirling.software.proprietary.policy.asset.PolicyAssetResolver;
@@ -419,9 +420,11 @@ public class PolicyEngine {
taskManager.setError(runId, message);
recordFailure(run, message, e);
} else {
- String message = "Policy run failed: " + e.getMessage();
+ String message = "Policy run failed: " + downstreamMessage(e);
log.error("Policy run {} failed (downstream HTTP error)", runId, e);
- run.fail(message);
+ // Carry the tool's own error code onto the run, so a client sees the same
+ // code the review surface classifies the failure on.
+ run.failWithCode(message, DownstreamProblemDetail.errorCodeOf(e), null);
taskManager.setError(runId, message);
recordFailure(run, message, e);
}
@@ -464,6 +467,15 @@ public class PolicyEngine {
return null;
}
+ /**
+ * What a downstream tool said, preferring its Problem Details {@code detail} over the raw
+ * exception text, which buries that sentence inside the serialised body.
+ */
+ private static String downstreamMessage(RestClientResponseException e) {
+ String detail = DownstreamProblemDetail.detailOf(e);
+ return detail != null ? detail : e.getMessage();
+ }
+
/**
* Record why a run failed. Called after the run's own state transition and task-manager update,
* so a recording problem cannot change the outcome the caller observes.
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/DownstreamProblemDetailTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/DownstreamProblemDetailTest.java
new file mode 100644
index 0000000000..66e609e3d2
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/DownstreamProblemDetailTest.java
@@ -0,0 +1,77 @@
+package stirling.software.proprietary.failure;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.nio.charset.StandardCharsets;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.client.HttpServerErrorException;
+
+/**
+ * Tests for {@link DownstreamProblemDetail}. Fixtures are real Problem Details bodies, since the
+ * whole point is reading what {@code GlobalExceptionHandler} actually writes.
+ */
+@DisplayName("reading a downstream problem detail")
+class DownstreamProblemDetailTest {
+
+ private static HttpServerErrorException response(String body) {
+ return HttpServerErrorException.create(
+ HttpStatus.INTERNAL_SERVER_ERROR,
+ "Internal Server Error",
+ new HttpHeaders(),
+ body == null ? new byte[0] : body.getBytes(StandardCharsets.UTF_8),
+ StandardCharsets.UTF_8);
+ }
+
+ @Test
+ void returnsTheDetailSentence() {
+ String body =
+ """
+ {"type":"/errors/application","title":"Application error","status":500,\
+ "detail":"Document is not PDF/A compliant (PDF/A-2B): 1 rule(s) failed",\
+ "errorCode":"E074"}""";
+
+ assertThat(DownstreamProblemDetail.detailOf(response(body)))
+ .isEqualTo("Document is not PDF/A compliant (PDF/A-2B): 1 rule(s) failed");
+ }
+
+ @Test
+ void returnsNullWhenTheBodyCarriesNoDetail() {
+ assertThat(DownstreamProblemDetail.detailOf(response("{\"status\":500}"))).isNull();
+ }
+
+ @Test
+ void returnsNullWhenTheBodyIsNotJson() {
+ assertThat(DownstreamProblemDetail.detailOf(response("<html>gateway timeout</html>")))
+ .isNull();
+ }
+
+ @Test
+ void returnsNullWhenThereIsNoBody() {
+ assertThat(DownstreamProblemDetail.detailOf(response(null))).isNull();
+ }
+
+ @Test
+ void returnsTheErrorCodeBesideTheDetail() {
+ String body =
+ """
+ {"type":"/errors/compliance-not-met","status":422,\
+ "detail":"Document is not PDF/A compliant","errorCode":"E074"}""";
+
+ assertThat(DownstreamProblemDetail.errorCodeOf(response(body))).isEqualTo("E074");
+ }
+
+ @Test
+ void returnsNullWhenTheFailureCarriesNoErrorCode() {
+ assertThat(DownstreamProblemDetail.errorCodeOf(response("{\"detail\":\"boom\"}"))).isNull();
+ }
+
+ @Test
+ void returnsNullErrorCodeWhenTheBodyIsNotJson() {
+ assertThat(DownstreamProblemDetail.errorCodeOf(response("<html>bad gateway</html>")))
+ .isNull();
+ }
+}
diff --git a/engine/scripts/generate_tool_models.py b/engine/scripts/generate_tool_models.py
index c3cd9e7267..713073b695 100644
--- a/engine/scripts/generate_tool_models.py
+++ b/engine/scripts/generate_tool_models.py
@@ -139,6 +139,7 @@ class ToolDiscovery:
"/api/v1/security/get-info-on-pdf",
"/api/v1/security/verify-pdf",
"/api/v1/security/validate-signature",
+ "/api/v1/security/validate-compliance",
"/api/v1/misc/list-attachments",
"/api/v1/misc/show-javascript",
"/api/v1/misc/decompress-pdf",
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 89083f5e85..b9d481e21d 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7033,6 +7033,11 @@ dismiss = "Dismiss overlay"
enforcingTitle = "Enforcing policy..."
viewAnyway = "View file (policy still enforcing)"
+[policyOption]
+pdfa-1 = "PDF/A-1b"
+pdfa-2b = "PDF/A-2b"
+pdfa-3b = "PDF/A-3b"
+
[portal]
comingSoon = "Coming soon"
@@ -8103,6 +8108,10 @@ source = "Source"
type = "Type"
user = "User"
+[portal.failures.kind.complianceNotMet]
+description = "The compliance check refused this document because it does not meet the standard the policy validates against. The violation is shown below."
+title = "Compliance standard not met"
+
[portal.failures.kind.inputPasswordProtected]
description = "Your file is password protected, so the run could not read it."
title = "Password-protected document"
@@ -8780,7 +8789,7 @@ desc = "Identify each document's type on upload and tag its metadata for filing
label = "Classification"
[portal.policies.categories.compliance]
-desc = "Enforce HIPAA, GDPR, SOC 2, or FedRAMP requirements on every document."
+desc = "Strip hidden data, convert to PDF/A for archiving, and validate every document against the standard before it is delivered."
label = "Compliance"
[portal.policies.categories.ingestion]
@@ -8810,18 +8819,12 @@ summary = "Classifies every uploaded document against your team's labels and tag
1 = "Tag metadata"
[portal.policies.config.compliance]
-summary = "Validates documents against regulatory frameworks before they leave the system."
-
-[portal.policies.config.compliance.fields]
-accessLog = "Access log"
-auditTrail = "Audit trail"
-frameworks = "Frameworks"
-onViolation = "When non-compliant"
+summary = "Strips hidden data, converts to the PDF/A archival format, and validates the result against the standard."
[portal.policies.config.compliance.rules]
-0 = "Framework scan"
-1 = "Enforce action"
-2 = "Audit trail"
+0 = "Strip hidden data"
+1 = "Convert to PDF/A"
+2 = "Validate compliance"
[portal.policies.config.ingestion]
summary = "Classifies documents, extracts structured data, enforces naming, and normalizes pages."
@@ -8836,6 +8839,10 @@ minConfidence = "Min confidence"
2 = "Name"
3 = "Normalize"
+[portal.policies.config.pdfa.fields.outputFormat]
+help = "PDF/A-2b suits most archives. PDF/A-1b is the strictest and most widely accepted; PDF/A-3b additionally allows attachments."
+label = "Archival profile"
+
[portal.policies.config.purview]
label = "Apply a Microsoft Purview sensitivity label"
@@ -8936,7 +8943,9 @@ classifyAndLabel = "Classify"
compressPdf = "Compress"
flatten = "Flatten"
ocrPdf = "OCR"
+pdfa = "Convert to PDF/A"
sanitizePdf = "Remove JavaScript"
+validateCompliance = "Validate compliance"
[portal.policies.operations]
change = "Change what this step does"
@@ -9153,6 +9162,10 @@ saveChanges = "Save changes"
desc = "Identifies the document's type from your team's labels and tags it, so it files and searches by category."
label = "Classify the document"
+[portal.policies.wizard.capability.complianceCheck]
+desc = "Validates the finished document against PDF/A and stops the run if it does not hold up."
+label = "Check the document meets the standard"
+
[portal.policies.wizard.capability.compress]
desc = "Compresses the document to a smaller file size."
label = "Reduce file size"
@@ -9165,6 +9178,10 @@ label = "Flatten the document"
desc = "Runs OCR so scanned pages become selectable, searchable text."
label = "Make text searchable"
+[portal.policies.wizard.capability.pdfa]
+desc = "Rewrites the document in the ISO archival format, embedding its fonts and colour profiles so it still renders the same years from now. Invalidates digital signatures."
+label = "Convert to PDF/A for archiving"
+
[portal.policies.wizard.capability.redact]
desc = "Finds and blacks out sensitive details — like Social Security and card numbers — so they can't be read."
label = "Redact sensitive information"
diff --git a/frontend/editor/src/core/i18n/translationAudit.ts b/frontend/editor/src/core/i18n/translationAudit.ts
index 0f1a856672..44b283ee5f 100644
--- a/frontend/editor/src/core/i18n/translationAudit.ts
+++ b/frontend/editor/src/core/i18n/translationAudit.ts
@@ -108,6 +108,9 @@ export const I18N_PROJECTS: TranslationProject[] = [
// "portal.policies.operations" - the shape heuristic treats that interpolation as one
// segment, so this whole catalogue-driven family is matched here instead.
/^portal\.policies\.operations\./,
+ // Failure-kind copy is keyed off the server's FailureKind enum and arrives as data, so no
+ // frontend source names it. FailureKindTest asserts every kind has copy here.
+ /^portal\.failures\.kind\./,
// Server-sent keys rendered with t(thatKey), so nothing in source names them.
/^portal\.failures\.disabled\./,
/^portal\.failures\.action\./,
diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.ts
index fe77b94c49..aba6746e1b 100644
--- a/frontend/editor/src/core/types/toolApiTypes.ts
+++ b/frontend/editor/src/core/types/toolApiTypes.ts
@@ -1356,6 +1356,7 @@ export interface SecurityCertSignValidateCertificateRequest {
}
export type SecurityGetInfoOnPdfRequest = Record<string, never>;
export type SecurityRemoveCertSignRequest = Record<string, never>;
+export type SecurityValidateComplianceRequest = Record<string, never>;
export interface SignPDFWithCertRequest {
/**
* The alias of the certificate to sign with. Required for WINDOWS_STORE and recommended for PKCS11 tokens holding multiple certificates.
@@ -1599,6 +1600,7 @@ export type ToolEndpoint =
| "/api/v1/security/remove-password"
| "/api/v1/security/sanitize-pdf"
| "/api/v1/security/timestamp-pdf"
+ | "/api/v1/security/validate-compliance"
| "/api/v1/security/validate-signature"
| "/api/v1/security/verify-pdf";
@@ -1703,6 +1705,7 @@ export interface ToolApiParams {
"/api/v1/security/remove-password": PDFPasswordRequest;
"/api/v1/security/sanitize-pdf": SanitizePdfRequest;
"/api/v1/security/timestamp-pdf": TimestampPdfRequest;
+ "/api/v1/security/validate-compliance": SecurityValidateComplianceRequest;
"/api/v1/security/validate-signature": SignatureValidationRequest;
"/api/v1/security/verify-pdf": PDFVerificationRequest;
}
@@ -1808,6 +1811,7 @@ export const TOOL_ENDPOINTS = [
"/api/v1/security/remove-password",
"/api/v1/security/sanitize-pdf",
"/api/v1/security/timestamp-pdf",
+ "/api/v1/security/validate-compliance",
"/api/v1/security/validate-signature",
"/api/v1/security/verify-pdf",
] as const satisfies readonly ToolEndpoint[];
diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.ts
index f67349917c..9d62cb086b 100644
--- a/frontend/editor/src/core/types/toolIO.ts
+++ b/frontend/editor/src/core/types/toolIO.ts
@@ -724,6 +724,11 @@ export const TOOL_IO: ToolIOTable = {
produces: "PDF",
arity: "SISO",
},
+ "/api/v1/security/validate-compliance": {
+ accepts: ["PDF"],
+ produces: "PDF",
+ arity: "SISO",
+ },
"/api/v1/security/validate-signature": {
accepts: ["PDF"],
produces: "JSON",
diff --git a/frontend/editor/src/core/ui/ToggleSwitch.tsx b/frontend/editor/src/core/ui/ToggleSwitch.tsx
index 5c2c715633..d617f12c9a 100644
--- a/frontend/editor/src/core/ui/ToggleSwitch.tsx
+++ b/frontend/editor/src/core/ui/ToggleSwitch.tsx
@@ -10,6 +10,8 @@ export interface ToggleSwitchProps {
"aria-labelledby"?: string;
/** Optional helper text rendered next to the label. */
description?: string;
+ /** Accessible name when the label lives outside the switch (e.g. a SettingsRow's label). */
+ "aria-label"?: string;
disabled?: boolean;
size?: "sm" | "md";
id?: string;
@@ -29,6 +31,7 @@ export function ToggleSwitch({
label,
"aria-labelledby": ariaLabelledBy,
description,
+ "aria-label": ariaLabel,
disabled,
size = "md",
id,
@@ -49,6 +52,7 @@ export function ToggleSwitch({
aria-labelledby={ariaLabelledBy}
checked={checked}
disabled={disabled}
+ aria-label={label ? undefined : ariaLabel}
onChange={(e) => onChange(e.target.checked)}
/>
<span className="sui-toggle__track" aria-hidden>
diff --git a/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.stories.tsx b/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.stories.tsx
index fff50a5223..02e3758004 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.stories.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelineTemplateCard.stories.tsx
@@ -6,7 +6,7 @@ import {
import { PipelineTemplateCard } from "@portal/components/pipelines/PipelineTemplateCard";
const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
-const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;
+const routing = POLICY_CATEGORIES.find((c) => c.id === "routing")!;
const meta: Meta<typeof PipelineTemplateCard> = {
title: "Portal/Pipelines/PipelineTemplateCard",
@@ -37,8 +37,8 @@ export const Locked: Story = {
export const ComingSoon: Story = {
args: {
entry: {
- category: compliance,
- config: POLICY_CONFIG.compliance,
+ category: routing,
+ config: POLICY_CONFIG.routing,
policy: null,
},
},
diff --git a/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsx
index 685fa49ffb..b21a800a08 100644
--- a/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsx
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import { FormField, Input, Select } from "@app/ui";
import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";
+import "@portal/views/Policies.css";
/**
* Configures the Purview labelling step: which tenant, and which label.
@@ -30,8 +31,10 @@ export function PolicyPurviewConfig({
const set = (key: keyof PurviewLabelParams, value: string) =>
onChange({ ...parameters, [key]: value });
+ // Not `capability-config`: the wizard already wraps this in one, and repeating the class draws
+ // its dashed divider twice.
return (
- <div className="portal-policies__capability-config">
+ <div className="portal-policies__capability-settings">
<FormField
label={t("portal.policies.config.purview.fields.connection")}
required
diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.stories.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.stories.tsx
index bf68a1ffe1..fb2b1a2ed0 100644
--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.stories.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.stories.tsx
@@ -11,6 +11,7 @@ const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
const classification = POLICY_CATEGORIES.find(
(c) => c.id === "classification",
)!;
+const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;
const meta: Meta<typeof PolicySetupWizard> = {
title: "Portal/Policies/PolicySetupWizard",
@@ -61,3 +62,17 @@ export const Classification: Story = {
},
},
};
+
+/**
+ * Compliance: the longest preset chain, and the only one whose steps carry inline settings of
+ * their own (the archival profile and the gate's standard/verdict).
+ */
+export const Compliance: Story = {
+ args: {
+ entry: {
+ category: compliance,
+ config: POLICY_CONFIG.compliance,
+ policy: null,
+ },
+ },
+};
diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
index 896ba8440c..f65d2c182b 100644
--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
@@ -45,8 +45,6 @@ const securityConfig = POLICY_CONFIG.security;
const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;
const complianceConfig = POLICY_CONFIG.compliance;
-const PURVIEW_LABEL = "Apply a Microsoft Purview sensitivity label";
-
function editEntry(steps: PipelineStep[]): CatalogueEntry {
const policy: DecoratedPolicy = {
category: security,
@@ -141,53 +139,6 @@ describe("PolicySetupWizard", () => {
expect(result.extraOptions).toEqual({ automation: { name: "x" } });
});
- it("hides the Purview step when no Purview tenant is connected", async () => {
- fetchIntegrations.mockResolvedValue([]);
- const entry: CatalogueEntry = {
- category: compliance,
- config: complianceConfig,
- policy: null,
- };
-
- render(
- <PolicySetupWizard
- entry={entry}
- onClose={vi.fn()}
- onSubmit={vi.fn()}
- onCustomise={vi.fn()}
- />,
- );
-
- // Sanitize is in the same chain and always shows, so once it renders the chain has loaded.
- await screen.findByText("Strip active content");
- // The Purview option can only fail without a connection, so it is not offered at all.
- expect(screen.queryByText(PURVIEW_LABEL)).toBeNull();
- });
-
- it("offers the Purview step once a Purview connection exists", async () => {
- fetchIntegrations.mockResolvedValue([
- { id: 1, name: "Corp Purview", integrationType: "PURVIEW", config: {} },
- ]);
- const entry: CatalogueEntry = {
- category: compliance,
- config: complianceConfig,
- policy: null,
- };
-
- render(
- <PolicySetupWizard
- entry={entry}
- onClose={vi.fn()}
- onSubmit={vi.fn()}
- onCustomise={vi.fn()}
- />,
- );
-
- await waitFor(() =>
- expect(screen.getByText(PURVIEW_LABEL)).toBeInTheDocument(),
- );
- });
-
it("seeds the preset chain for a new policy (redact + sanitize on, watermark off)", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
const entry: CatalogueEntry = {
@@ -292,4 +243,47 @@ describe("PolicySetupWizard", () => {
const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
expect(result.required).toBe(true);
});
+
+ it("seeds the compliance chain so the gate judges the delivered document", async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const entry: CatalogueEntry = {
+ category: compliance,
+ config: complianceConfig,
+ policy: null,
+ };
+
+ render(
+ <PolicySetupWizard
+ entry={entry}
+ onClose={vi.fn()}
+ onSubmit={onSubmit}
+ onCustomise={vi.fn()}
+ />,
+ );
+ expect(
+ await screen.findByText("Convert to PDF/A for archiving"),
+ ).toBeInTheDocument();
+ // PDF/UA is not offered: conforming needs per-figure alt text nothing in the product can
+ // supply, so a gate pointed at it would fail every run.
+ expect(screen.queryByText(/PDF\/UA/)).toBeNull();
+ await submitWizard(ENABLE);
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());
+ const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
+ // Flatten is absent: it rasterises pages, which would leave the archive without a text layer.
+ expect(result.steps.map((s) => s.operation)).toEqual([
+ "/api/v1/security/sanitize-pdf",
+ "/api/v1/convert/pdf/pdfa",
+ "/api/v1/security/validate-compliance",
+ ]);
+ // Both metadata streams go, but fonts stay - PDF/A needs them embedded.
+ expect(result.steps[0].parameters).toMatchObject({
+ removeMetadata: true,
+ removeXMPMetadata: true,
+ removeFonts: false,
+ });
+ expect(result.steps[1].parameters).toMatchObject({
+ outputFormat: "pdfa-2b",
+ });
+ });
});
diff --git a/frontend/editor/src/portal/views/Policies.css b/frontend/editor/src/portal/views/Policies.css
index 8d1ebbe09f..f67ea4d7bd 100644
--- a/frontend/editor/src/portal/views/Policies.css
+++ b/frontend/editor/src/portal/views/Policies.css
@@ -93,6 +93,15 @@
margin-top: 0.75rem;
}
+/* A capability's revealed settings. Neither FormField nor SettingsRow carries an
+ * outer margin, so without this the controls butt straight into each other. */
+.portal-policies__capability-config,
+.portal-policies__capability-settings {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
+
.portal-policies__link {
border: none;
background: none;
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyPdfaConfig.stories.tsx b/frontend/editor/src/proprietary/components/policies/PolicyPdfaConfig.stories.tsx
new file mode 100644
index 0000000000..f4608fcca4
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/PolicyPdfaConfig.stories.tsx
@@ -0,0 +1,31 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { PolicyPdfaConfig } from "@app/components/policies/PolicyPdfaConfig";
+import {
+ pdfaDefaultParameters,
+ type PdfaPolicyParameters,
+} from "@app/policies/pdfaOperation";
+
+const meta: Meta<typeof PolicyPdfaConfig> = {
+ title: "Policies/PolicyPdfaConfig",
+ component: PolicyPdfaConfig,
+ parameters: { layout: "padded" },
+};
+export default meta;
+type Story = StoryObj<typeof PolicyPdfaConfig>;
+
+/** Renders the config and keeps its parameters in local state, exercising onChange. */
+function Controlled({ parameters }: { parameters: PdfaPolicyParameters }) {
+ const [value, setValue] = useState(parameters);
+ return <PolicyPdfaConfig parameters={value} onChange={setValue} />;
+}
+
+/** The preset a fresh compliance policy seeds: PDF/A-2b, conversion shortfalls allowed. */
+export const Default: Story = {
+ render: () => <Controlled parameters={pdfaDefaultParameters} />,
+};
+
+/** The strictest archival profile. */
+export const StrictestProfile: Story = {
+ render: () => <Controlled parameters={{ outputFormat: "pdfa-1" }} />,
+};
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyPdfaConfig.tsx b/frontend/editor/src/proprietary/components/policies/PolicyPdfaConfig.tsx
new file mode 100644
index 0000000000..4f8ab8e416
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/PolicyPdfaConfig.tsx
@@ -0,0 +1,46 @@
+import { useTranslation } from "react-i18next";
+import { FormField, Select } from "@app/ui";
+import {
+ PDFA_OUTPUT_FORMATS,
+ type PdfaOutputFormat,
+ type PdfaPolicyParameters,
+} from "@app/policies/pdfaOperation";
+import "@app/components/policies/PolicySetupWizard.css";
+
+/** Configures the PDF/A step: which archival profile to convert to. */
+interface PolicyPdfaConfigProps {
+ parameters: PdfaPolicyParameters;
+ onChange: (parameters: PdfaPolicyParameters) => void;
+}
+
+export function PolicyPdfaConfig({
+ parameters,
+ onChange,
+}: PolicyPdfaConfigProps) {
+ const { t } = useTranslation();
+
+ // Not `capability-config`: the wizard already wraps this in one, and repeating the class draws
+ // its dashed divider twice.
+ return (
+ <div className="portal-policies__capability-settings">
+ <FormField
+ label={t("portal.policies.config.pdfa.fields.outputFormat.label")}
+ helperText={t("portal.policies.config.pdfa.fields.outputFormat.help")}
+ >
+ <Select
+ value={parameters.outputFormat}
+ options={PDFA_OUTPUT_FORMATS.map((format) => ({
+ value: format,
+ label: t(`policyOption.${format}`, format),
+ }))}
+ onChange={(value) =>
+ onChange({
+ ...parameters,
+ outputFormat: (value as PdfaOutputFormat) ?? "pdfa-2b",
+ })
+ }
+ />
+ </FormField>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css
index a0454174ab..6e72c8c4af 100644
--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css
+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.css
@@ -69,3 +69,12 @@
padding-top: 0.75rem;
margin-top: 0.75rem;
}
+
+/* A capability's revealed settings. Neither FormField nor SettingsRow carries an
+ * outer margin, so without this the controls butt straight into each other. */
+.portal-policies__capability-config,
+.portal-policies__capability-settings {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
index 703682a671..6662fcfef7 100644
--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
+++ b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
@@ -22,6 +22,7 @@ import { resolveRunOn } from "@app/policies/runOn";
import { PolicyCategoryBadge } from "@app/components/policies/PolicyCategoryBadge";
import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";
import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";
+import { PolicyPdfaConfig } from "@app/components/policies/PolicyPdfaConfig";
import { ClassificationLabelsSection } from "@app/components/policies/ClassificationLabelsSection";
import "@app/components/policies/PolicySetupWizard.css";
@@ -149,6 +150,20 @@ const CAPABILITY_META: Record<
descKey: "portal.policies.wizard.capability.compress.desc",
descEn: "Compresses the document to a smaller file size.",
},
+ pdfa: {
+ labelKey: "portal.policies.wizard.capability.pdfa.label",
+ labelEn: "Convert to PDF/A for archiving",
+ descKey: "portal.policies.wizard.capability.pdfa.desc",
+ descEn:
+ "Rewrites the document in the ISO archival format, embedding its fonts and colour profiles so it still renders the same years from now. Invalidates digital signatures.",
+ },
+ complianceCheck: {
+ labelKey: "portal.policies.wizard.capability.complianceCheck.label",
+ labelEn: "Check the document meets the standard",
+ descKey: "portal.policies.wizard.capability.complianceCheck.desc",
+ descEn:
+ "Validates the finished document against PDF/A and stops the run if it does not hold up.",
+ },
classify: {
labelKey: "portal.policies.wizard.capability.classify.label",
labelEn: "Classify the document",
@@ -450,7 +465,7 @@ function PolicySetupWizardBody({
onChange={(checked) =>
setToolEnabled(tl.toolId, checked)
}
- label=""
+ aria-label={label}
/>
}
/>
@@ -472,6 +487,12 @@ function PolicySetupWizardBody({
}
/>
)}
+ {tl.toolId === "pdfa" && (
+ <PolicyPdfaConfig
+ parameters={tl.params}
+ onChange={(params) => setToolParams("pdfa", params)}
+ />
+ )}
{tl.toolId === "purviewApplyLabel" &&
purviewConfig?.({
parameters: tl.params,
diff --git a/frontend/editor/src/proprietary/policies/catalog.ts b/frontend/editor/src/proprietary/policies/catalog.ts
index a8e31f14f1..cf9537aa86 100644
--- a/frontend/editor/src/proprietary/policies/catalog.ts
+++ b/frontend/editor/src/proprietary/policies/catalog.ts
@@ -3,7 +3,11 @@
* and the editor's folder-processing setup both read it.
*/
-import { policyStep, type PolicyToolStep } from "@app/policies/operations";
+import {
+ policyStep,
+ type PolicyToolStep,
+ type UntypedPolicyEndpoint,
+} from "@app/policies/operations";
import type { ToolEndpoint } from "@app/types/toolApiTypes";
import type { WirePipelineStep } from "@app/policies/types";
@@ -102,7 +106,7 @@ export interface CatalogueEntry {
}
const ENDPOINT_LABELS: Partial<
- Record<ToolEndpoint | "/api/v1/ai/tools/classify-and-label", string>
+ Record<ToolEndpoint | UntypedPolicyEndpoint, string>
> = {
"/api/v1/security/auto-redact": "portal.policies.endpoints.autoRedact",
"/api/v1/security/sanitize-pdf": "portal.policies.endpoints.sanitizePdf",
@@ -110,6 +114,9 @@ const ENDPOINT_LABELS: Partial<
"/api/v1/misc/ocr-pdf": "portal.policies.endpoints.ocrPdf",
"/api/v1/misc/flatten": "portal.policies.endpoints.flatten",
"/api/v1/misc/compress-pdf": "portal.policies.endpoints.compressPdf",
+ "/api/v1/convert/pdf/pdfa": "portal.policies.endpoints.pdfa",
+ "/api/v1/security/validate-compliance":
+ "portal.policies.endpoints.validateCompliance",
"/api/v1/ai/tools/classify-and-label":
"portal.policies.endpoints.classifyAndLabel",
};
@@ -159,7 +166,6 @@ export const POLICY_CATEGORIES: PolicyCategory[] = [
label: "portal.policies.categories.compliance.label",
tone: "amber",
desc: "portal.policies.categories.compliance.desc",
- comingSoon: true,
},
{
id: "routing",
@@ -245,44 +251,22 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
"portal.policies.config.compliance.rules.2",
],
scopeLabel: "portal.policies.config.scopeAll",
+ // Gate last, so it judges the document that actually ships. No flatten step: it rasterises
+ // whole pages, and an archive without a text layer is not an archive. Nothing writes to the
+ // document between the conversion and the gate, so what the gate passes is what was converted.
defaultOperations: [
- policyStep("sanitize"),
- policyStep("flatten"),
- policyStep("purviewApplyLabel"),
- ],
- fields: [
- {
- label: "portal.policies.config.compliance.fields.frameworks",
- key: "frameworks",
- type: "chips",
- value: ["hipaa"],
- options: ["hipaa", "gdpr", "soc2", "fedramp", "pciDss", "iso27001"],
- },
- {
- label: "portal.policies.config.compliance.fields.onViolation",
- key: "onViolation",
- type: "select",
- value: "flagForReview",
- options: [
- "flagForReview",
- "blockExport",
- "autoRedactPhi",
- "quarantineDocument",
- ],
- },
- {
- label: "portal.policies.config.compliance.fields.auditTrail",
- key: "auditTrail",
- type: "toggle",
- value: true,
- },
- {
- label: "portal.policies.config.compliance.fields.accessLog",
- key: "accessLog",
- type: "toggle",
- value: true,
- },
+ // Hidden data is the usual disclosure route: strip scripts, attachments and both metadata
+ // streams. Fonts stay - PDF/A requires them embedded.
+ policyStep("sanitize", {
+ removeMetadata: true,
+ removeXMPMetadata: true,
+ }),
+ policyStep("pdfa"),
+ policyStep("complianceCheck"),
],
+ // No policy-level settings: what this policy does is the step chain, and nothing on the
+ // backend reads fieldValues, so a framework picker here could only ever be decoration.
+ fields: [],
},
routing: {
summary: "portal.policies.config.routing.summary",
diff --git a/frontend/editor/src/proprietary/policies/operations.test.ts b/frontend/editor/src/proprietary/policies/operations.test.ts
index c0aa97e153..0cfe3fa352 100644
--- a/frontend/editor/src/proprietary/policies/operations.test.ts
+++ b/frontend/editor/src/proprietary/policies/operations.test.ts
@@ -16,10 +16,12 @@ describe("POLICY_OPERATIONS", () => {
// The catalogue uses these across all categories; each must be wired.
expect(ALL_TOOL_IDS.sort()).toEqual([
"classify",
+ "complianceCheck",
"compress",
"externalApiCall",
"flatten",
"ocr",
+ "pdfa",
"purviewApplyLabel",
"purviewReadLabel",
"redact",
@@ -41,6 +43,10 @@ describe("POLICY_OPERATIONS", () => {
expect(policyEndpoint("ocr")).toBe("/api/v1/misc/ocr-pdf");
expect(policyEndpoint("flatten")).toBe("/api/v1/misc/flatten");
expect(policyEndpoint("compress")).toBe("/api/v1/misc/compress-pdf");
+ expect(policyEndpoint("pdfa")).toBe("/api/v1/convert/pdf/pdfa");
+ expect(policyEndpoint("complianceCheck")).toBe(
+ "/api/v1/security/validate-compliance",
+ );
});
test("policyToolIdForEndpoint maps endpoints back, and rejects non-policy ones", () => {
@@ -115,3 +121,39 @@ describe("wire conversion", () => {
).toBeNull();
});
});
+
+describe("compliance steps", () => {
+ test("pdfa sends the archival profile the backend expects", () => {
+ const wire = policyStepToWire(
+ policyStep("pdfa", { outputFormat: "pdfa-3b" }),
+ );
+ expect(wire.operation).toBe("/api/v1/convert/pdf/pdfa");
+ expect(wire.parameters).toEqual({ outputFormat: "pdfa-3b" });
+ });
+
+ test("pdfa clamps a stored profile this policy UI no longer offers", () => {
+ // PDF/X is a print standard the compliance picker does not list; a hand-edited or legacy
+ // step naming it must not round-trip back into the archival picker.
+ const back = policyStepFromWire({
+ operation: "/api/v1/convert/pdf/pdfa",
+ parameters: { outputFormat: "pdfx" },
+ });
+ expect(back?.toolId).toBe("pdfa");
+ if (back?.toolId === "pdfa") {
+ expect(back.params.outputFormat).toBe("pdfa-2b");
+ }
+ });
+
+ test("the compliance gate carries no options to get wrong", () => {
+ expect(policyStep("complianceCheck").params).toEqual({});
+ });
+
+ test("the gate drops any stored options a hand-edited step carries", () => {
+ const back = policyStepFromWire({
+ operation: "/api/v1/security/validate-compliance",
+ parameters: { standard: "pdfua", onViolation: "ignore" },
+ });
+ expect(back?.toolId).toBe("complianceCheck");
+ expect(back?.params).toEqual({});
+ });
+});
diff --git a/frontend/editor/src/proprietary/policies/operations.ts b/frontend/editor/src/proprietary/policies/operations.ts
index 092d8b50de..b8d974ff70 100644
--- a/frontend/editor/src/proprietary/policies/operations.ts
+++ b/frontend/editor/src/proprietary/policies/operations.ts
@@ -4,7 +4,10 @@
* policy - the catalogue can't reference an untyped operation.
*/
-import { describeToolOperation } from "@app/hooks/tools/shared/toolOperationDescriptor";
+import {
+ describeToolOperation,
+ type BidirectionalToolConfig,
+} from "@app/hooks/tools/shared/toolOperationDescriptor";
import { redactOperationConfig } from "@app/hooks/tools/redact/useRedactOperation";
import { sanitizeOperationConfig } from "@app/hooks/tools/sanitize/useSanitizeOperation";
import { timestampPdfOperationConfig } from "@app/hooks/tools/timestampPdf/useTimestampPdfOperation";
@@ -12,6 +15,7 @@ import { addWatermarkOperationConfig } from "@app/hooks/tools/addWatermark/useAd
import { ocrOperationConfig } from "@app/hooks/tools/ocr/useOCROperation";
import { flattenOperationConfig } from "@app/hooks/tools/flatten/useFlattenOperation";
import { compressOperationConfig } from "@app/hooks/tools/compress/useCompressOperation";
+import { pdfaOperationConfig } from "@app/policies/pdfaOperation";
import type { ToolEndpoint } from "@app/types/toolApiTypes";
import type { WirePipelineStep } from "@app/policies/types";
@@ -89,6 +93,21 @@ function describeIntegrationOperation<TParams extends Record<string, string>>(
};
}
+const COMPLIANCE_CHECK_ENDPOINT =
+ "/api/v1/security/validate-compliance" satisfies ToolEndpoint;
+
+// Annotated rather than inferred, as pdfaOperationConfig is: an unannotated object literal widens
+// `endpoint` to string, which no longer satisfies describeToolOperation's `CE extends ToolEndpoint`.
+const complianceCheckOperationConfig: BidirectionalToolConfig<
+ Record<string, never>,
+ typeof COMPLIANCE_CHECK_ENDPOINT
+> = {
+ endpoint: COMPLIANCE_CHECK_ENDPOINT,
+ defaultParameters: {},
+ toApiParams: () => ({}),
+ fromApiParams: () => ({}),
+};
+
export const POLICY_OPERATIONS = {
redact: describeToolOperation(
"/api/v1/security/auto-redact",
@@ -117,6 +136,14 @@ export const POLICY_OPERATIONS = {
"/api/v1/misc/compress-pdf",
compressOperationConfig,
),
+ // Long-term archival format: embeds fonts and colour profiles so the document still renders the
+ // same decades from now, which is what a retention or archival requirement actually asks for.
+ pdfa: describeToolOperation("/api/v1/convert/pdf/pdfa", pdfaOperationConfig),
+ // The gate: no options, so a stored step carries nothing that could drift.
+ complianceCheck: describeToolOperation(
+ "/api/v1/security/validate-compliance",
+ complianceCheckOperationConfig,
+ ),
classify: describeAiToolOperation("/api/v1/ai/tools/classify-and-label"),
purviewApplyLabel: describeIntegrationOperation(
"/api/v1/integration/purview-apply-label",
diff --git a/frontend/editor/src/proprietary/policies/pdfaOperation.ts b/frontend/editor/src/proprietary/policies/pdfaOperation.ts
new file mode 100644
index 0000000000..edc43451c1
--- /dev/null
+++ b/frontend/editor/src/proprietary/policies/pdfaOperation.ts
@@ -0,0 +1,58 @@
+/**
+ * Policy-facing binding for the PDF/A endpoint. The Convert tool's config spans every conversion;
+ * a policy step needs only these two parameters, typed against the generated request model.
+ */
+
+import type { BidirectionalToolConfig } from "@app/hooks/tools/shared/toolOperationDescriptor";
+import type { ToolApiParams, ToolEndpoint } from "@app/types/toolApiTypes";
+
+const ENDPOINT = "/api/v1/convert/pdf/pdfa" satisfies ToolEndpoint;
+type PdfaApiParams = ToolApiParams[typeof ENDPOINT];
+
+/**
+ * Archival profiles only. The endpoint also converts to PDF/X, but that is a print-production
+ * standard with no bearing on a compliance policy, so it is not offered here.
+ */
+export const PDFA_OUTPUT_FORMATS = [
+ "pdfa-1",
+ "pdfa-2b",
+ "pdfa-3b",
+] as const satisfies readonly PdfaApiParams["outputFormat"][];
+
+export type PdfaOutputFormat = (typeof PDFA_OUTPUT_FORMATS)[number];
+
+export interface PdfaPolicyParameters {
+ outputFormat: PdfaOutputFormat;
+}
+
+/** PDF/A-2b: the widest-supported archival profile, and what most retention policies ask for. */
+export const pdfaDefaultParameters: PdfaPolicyParameters = {
+ outputFormat: "pdfa-2b",
+};
+
+function toOutputFormat(value: unknown): PdfaOutputFormat {
+ return (PDFA_OUTPUT_FORMATS as readonly string[]).includes(value as string)
+ ? (value as PdfaOutputFormat)
+ : pdfaDefaultParameters.outputFormat;
+}
+
+// Annotated rather than inferred: an unannotated object literal widens `endpoint` to string, which
+// no longer satisfies describeToolOperation's `CE extends ToolEndpoint`.
+export const pdfaOperationConfig: BidirectionalToolConfig<
+ PdfaPolicyParameters,
+ typeof ENDPOINT
+> = {
+ endpoint: ENDPOINT,
+ defaultParameters: pdfaDefaultParameters,
+ // `strict` is left unset: it re-runs the same veraPDF check the compliance gate runs on the
+ // finished document, so asking for it here would only duplicate that verdict with a worse one -
+ // an uncoded 400 rather than the gate's classified failure.
+ toApiParams: (parameters: PdfaPolicyParameters): PdfaApiParams => ({
+ outputFormat: parameters.outputFormat,
+ }),
+ // A stored step may name a profile this policy UI no longer offers (or nothing at all); clamp to
+ // a known archival profile rather than re-sending a value the picker cannot render.
+ fromApiParams: (apiParams: PdfaApiParams): Partial<PdfaPolicyParameters> => ({
+ outputFormat: toOutputFormat(apiParams.outputFormat),
+ }),
+};
diff --git a/frontend/editor/src/proprietary/policies/runOn.test.ts b/frontend/editor/src/proprietary/policies/runOn.test.ts
index db72603215..27342768db 100644
--- a/frontend/editor/src/proprietary/policies/runOn.test.ts
+++ b/frontend/editor/src/proprietary/policies/runOn.test.ts
@@ -2,12 +2,14 @@ import { describe, it, expect } from "vitest";
import { defaultRunOn, resolveRunOn } from "@app/policies/runOn";
describe("defaultRunOn", () => {
- it("defaults Security to export", () => {
+ it("defaults Security and Compliance to export", () => {
expect(defaultRunOn("security")).toBe("export");
+ // Compliance is an archival gate: it judges the document that ships.
+ expect(defaultRunOn("compliance")).toBe("export");
});
it("defaults any other, unknown or missing category to upload", () => {
- for (const id of ["classification", "compliance", "nope", "", undefined]) {
+ for (const id of ["classification", "nope", "", undefined]) {
expect(defaultRunOn(id)).toBe("upload");
}
});
diff --git a/frontend/editor/src/proprietary/policies/runOn.ts b/frontend/editor/src/proprietary/policies/runOn.ts
index f47d2be9e6..456e092cdb 100644
--- a/frontend/editor/src/proprietary/policies/runOn.ts
+++ b/frontend/editor/src/proprietary/policies/runOn.ts
@@ -4,6 +4,9 @@ export type PolicyRunOn = "upload" | "export";
const DEFAULT_RUN_ON: Record<string, PolicyRunOn> = {
security: "export",
+ // Compliance is an archival gate: convert to PDF/A and validate the document
+ // that actually ships, so it enforces on export like security.
+ compliance: "export",
};
export function defaultRunOn(policyKey: string | undefined): PolicyRunOn {