Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1143a8aba3 | ||
|
|
baf33b6844 | ||
|
|
776749277c | ||
|
|
41b1b89fcb | ||
|
|
4d4e994562 | ||
|
|
2b118556f3 | ||
|
|
fbaff56d1c | ||
|
|
a1b15e0570 | ||
|
|
76549288a9 | ||
|
|
b5d0c4a5ed | ||
|
|
8bfcf6eb7e | ||
|
|
b019f9b570 | ||
|
|
38ccea074c | ||
|
|
a7307ff393 | ||
|
|
72729e99c1 | ||
|
|
5fba2720f0 | ||
|
|
01a1ef8c44 | ||
|
|
8535c7e9ac | ||
|
|
cca3f42623 | ||
|
|
1b7ffcdbac | ||
|
|
67a0ca6110 | ||
|
|
8e4b2e2fc6 | ||
|
|
3c93457021 |
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
|
||||
pkgname=stirling-pdf-desktop
|
||||
pkgver=2.14.1
|
||||
pkgver=2.14.2
|
||||
pkgrel=1
|
||||
pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"
|
||||
arch=('x86_64')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
|
||||
pkgname=stirling-pdf-server-bin
|
||||
pkgver=2.14.1
|
||||
pkgver=2.14.2
|
||||
pkgrel=1
|
||||
pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"
|
||||
arch=('any')
|
||||
|
||||
@@ -510,6 +510,7 @@ jobs:
|
||||
# cargo output unsigned, so checking it produces false negatives.
|
||||
- name: Verify Windows Code Signature
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
timeout-minutes: 15
|
||||
shell: pwsh
|
||||
run: |
|
||||
$allSigned = $true
|
||||
@@ -531,11 +532,26 @@ jobs:
|
||||
|
||||
# Extract MSI and verify the inner exe (the file that actually gets installed).
|
||||
# This is the critical check - AV flags the installed exe at runtime.
|
||||
# Use lessmsi, not `msiexec /a`: msiexec serializes on the global
|
||||
# _MSIExecute mutex and hangs forever on hosted runners when another
|
||||
# installer is busy. lessmsi reads MSI tables directly - no mutex, no service.
|
||||
$msi = $msiFiles[0].FullName
|
||||
$extractDir = Join-Path $env:RUNNER_TEMP "msi-verify"
|
||||
if (Test-Path $extractDir) { Remove-Item $extractDir -Recurse -Force }
|
||||
$proc = Start-Process msiexec.exe -ArgumentList '/a', $msi, '/qn', "TARGETDIR=$extractDir" -Wait -PassThru -NoNewWindow
|
||||
if ($proc.ExitCode -eq 0) {
|
||||
New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
|
||||
|
||||
choco install lessmsi -y --no-progress --limit-output | Out-Null
|
||||
|
||||
# Bound the extraction and kill on hang (defence in depth over timeout-minutes).
|
||||
$proc = Start-Process lessmsi -ArgumentList 'x', "`"$msi`"", "`"$extractDir\`"" -PassThru -NoNewWindow
|
||||
if (-not $proc.WaitForExit(120000)) {
|
||||
try { $proc.Kill() } catch {}
|
||||
Write-Host "[ERROR] MSI extraction timed out after 120s"
|
||||
$allSigned = $false
|
||||
} elseif ($proc.ExitCode -ne 0) {
|
||||
Write-Host "[ERROR] Failed to extract MSI for verification (exit code: $($proc.ExitCode))"
|
||||
$allSigned = $false
|
||||
} else {
|
||||
$innerExe = Get-ChildItem -Path $extractDir -Filter "stirling-pdf.exe" -Recurse -File | Select-Object -First 1
|
||||
if ($innerExe) {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $innerExe.FullName
|
||||
@@ -548,9 +564,6 @@ jobs:
|
||||
Write-Host "[ERROR] Could not find stirling-pdf.exe inside MSI"
|
||||
$allSigned = $false
|
||||
}
|
||||
} else {
|
||||
Write-Host "[ERROR] Failed to extract MSI for verification (exit code: $($proc.ExitCode))"
|
||||
$allSigned = $false
|
||||
}
|
||||
|
||||
if (-not $allSigned) {
|
||||
@@ -800,7 +813,11 @@ jobs:
|
||||
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
|
||||
with:
|
||||
tag_name: v${{ needs.determine-matrix.outputs.version }}
|
||||
generate_release_notes: true
|
||||
# Don't regenerate/append notes on re-runs, and don't force this into the
|
||||
# "Latest" slot - leave the release body and latest marker as they are.
|
||||
generate_release_notes: false
|
||||
append_body: false
|
||||
make_latest: false
|
||||
fail_on_unmatched_files: true
|
||||
# Installers + updater payloads + manifest. .sig contents are embedded
|
||||
# in latest.json so the .sig files themselves are not uploaded.
|
||||
|
||||
@@ -308,6 +308,106 @@ public class ApplicationProperties {
|
||||
* explicitly requests it via {@code AiEngineClient.postWithTimeout}.
|
||||
*/
|
||||
private int longRunningTimeoutSeconds = 600;
|
||||
|
||||
/** Timeout (seconds) for the SSE stream held open by long-running orchestrator runs. */
|
||||
private int streamTimeoutSeconds = 1800;
|
||||
|
||||
/**
|
||||
* Whether the processor pushes admin/settings-derived AI config (models, keys, RAG, limits)
|
||||
* to the engine's {@code POST /api/v1/config} on startup and after a save. True lets a
|
||||
* self-hosted admin drive the engine from the UI. Environment-driven deployments pin this
|
||||
* false (SaaS does in application-saas.properties) so the engine stays entirely
|
||||
* env-controlled and the processor never overrides its config.
|
||||
*/
|
||||
private boolean pushConfigToEngine = true;
|
||||
|
||||
/** Model + provider selection, forwarded to the engine per-request. */
|
||||
private Models models = new Models();
|
||||
|
||||
/** Retrieval-augmented-generation (RAG) knobs, forwarded to the engine per-request. */
|
||||
private Rag rag = new Rag();
|
||||
|
||||
/** Request size / cost guardrails. */
|
||||
private Limits limits = new Limits();
|
||||
|
||||
/** Per-capability on/off switches so an admin can disable individual AI tools. */
|
||||
private Features features = new Features();
|
||||
|
||||
@Data
|
||||
public static class Models {
|
||||
/** Provider driving the model strings: 'anthropic', 'openai', 'ollama', or 'custom'. */
|
||||
private String provider = "anthropic";
|
||||
|
||||
/** High-quality tier model name (without provider prefix), e.g. 'claude-haiku-4-5'. */
|
||||
private String smartModel = "claude-haiku-4-5";
|
||||
|
||||
/** Cheap/fast tier model name (without provider prefix). */
|
||||
private String fastModel = "claude-haiku-4-5";
|
||||
|
||||
private int smartMaxTokens = 8192;
|
||||
private int fastMaxTokens = 2048;
|
||||
|
||||
/**
|
||||
* API key for the selected provider. Secret - masked in the admin API and overridable
|
||||
* by the engine's own provider env var (e.g. ANTHROPIC_API_KEY) in environment-driven
|
||||
* deployments. Empty means the engine falls back to its native env credentials.
|
||||
*/
|
||||
private String apiKey = "";
|
||||
|
||||
/**
|
||||
* OpenAI-compatible base URL for 'ollama' / 'custom' providers (e.g.
|
||||
* http://ollama:11434/v1). Ignored for anthropic/openai. SSRF-sensitive - admin only.
|
||||
*/
|
||||
private String baseUrl = "";
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Rag {
|
||||
/**
|
||||
* Embedding provider: 'voyageai', 'openai', 'ollama', or 'custom' (OpenAI-compatible).
|
||||
*/
|
||||
private String embeddingProvider = "voyageai";
|
||||
|
||||
/** Embedding model name (without provider prefix), e.g. 'voyage-4'. */
|
||||
private String embeddingModel = "voyage-4";
|
||||
|
||||
/**
|
||||
* Secret API key for the embedding provider; masked + env-overridable like
|
||||
* models.apiKey.
|
||||
*/
|
||||
private String embeddingApiKey = "";
|
||||
|
||||
/**
|
||||
* OpenAI-compatible base URL for 'ollama' / 'custom' embedding providers (e.g.
|
||||
* http://ollama:11434/v1). Ignored for voyageai/openai. SSRF-sensitive - admin only.
|
||||
*/
|
||||
private String embeddingBaseUrl = "";
|
||||
|
||||
/** How many chunks retrieval returns per search. */
|
||||
private int topK = 20;
|
||||
|
||||
/** Per-run cap on knowledge-search tool calls before the agent must answer. */
|
||||
private int maxSearches = 5;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Limits {
|
||||
private int maxPages = 200;
|
||||
private int maxCharacters = 200000;
|
||||
|
||||
/** Process-wide cap on concurrent model API calls (engine restart to apply). */
|
||||
private int modelMaxConcurrency = 32;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Features {
|
||||
private boolean chat = true;
|
||||
private boolean documentQuestions = true;
|
||||
private boolean createPdf = true;
|
||||
private boolean mathAuditor = true;
|
||||
private boolean pdfComment = true;
|
||||
private boolean classify = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+13
-1
@@ -336,7 +336,19 @@ public class ConfigController {
|
||||
configData.put("premiumEnabled", applicationProperties.getPremium().isEnabled());
|
||||
|
||||
// AI Engine settings
|
||||
configData.put("aiEngineEnabled", applicationProperties.getAiEngine().isEnabled());
|
||||
ApplicationProperties.AiEngine aiEngineConfig = applicationProperties.getAiEngine();
|
||||
configData.put("aiEngineEnabled", aiEngineConfig.isEnabled());
|
||||
// Per-capability flags let the UI hide individual AI tools an admin has turned off.
|
||||
ApplicationProperties.AiEngine.Features aiFeatures = aiEngineConfig.getFeatures();
|
||||
configData.put(
|
||||
"aiFeatures",
|
||||
Map.ofEntries(
|
||||
Map.entry("chat", aiFeatures.isChat()),
|
||||
Map.entry("documentQuestions", aiFeatures.isDocumentQuestions()),
|
||||
Map.entry("createPdf", aiFeatures.isCreatePdf()),
|
||||
Map.entry("mathAuditor", aiFeatures.isMathAuditor()),
|
||||
Map.entry("pdfComment", aiFeatures.isPdfComment()),
|
||||
Map.entry("classify", aiFeatures.isClassify())));
|
||||
|
||||
// Timestamp TSA settings — single source of truth for presets + admin URLs
|
||||
ApplicationProperties.Security.Timestamp tsConfig =
|
||||
|
||||
+99
-151
@@ -5,12 +5,8 @@ import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
@@ -26,7 +22,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import stirling.software.SPDF.model.PDFText;
|
||||
import stirling.software.SPDF.model.api.security.ManualRedactPdfRequest;
|
||||
import stirling.software.SPDF.pdf.parser.PageImageLocator;
|
||||
import stirling.software.SPDF.pdf.redaction.RedactionPipeline;
|
||||
import stirling.software.common.model.api.security.RedactionArea;
|
||||
import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.common.util.PdfUtils;
|
||||
@@ -43,18 +38,15 @@ class ManualRedactionService {
|
||||
|
||||
private final TempFileManager tempFileManager;
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Area and page redaction
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
AreaRedactionResult redactAreas(
|
||||
List<RedactionArea> redactionAreas, PDDocument document, PDPageTree allPages)
|
||||
void redactAreas(List<RedactionArea> redactionAreas, PDDocument document, PDPageTree allPages)
|
||||
throws IOException {
|
||||
|
||||
Set<String> capturedStrings = new LinkedHashSet<>();
|
||||
Map<Integer, List<PDRectangle>> rectsByPage = new HashMap<>();
|
||||
Set<Integer> forceRasterPages = new LinkedHashSet<>();
|
||||
|
||||
if (redactionAreas == null || redactionAreas.isEmpty()) {
|
||||
return new AreaRedactionResult(rectsByPage, forceRasterPages, capturedStrings);
|
||||
return;
|
||||
}
|
||||
|
||||
Map<Integer, List<RedactionArea>> redactionsByPage = new HashMap<>();
|
||||
@@ -82,57 +74,57 @@ class ManualRedactionService {
|
||||
continue;
|
||||
}
|
||||
|
||||
int pageIndex = pageNumber - 1;
|
||||
PDPage page = allPages.get(pageIndex);
|
||||
float pageHeight = page.getBBox().getHeight();
|
||||
PDPage page = allPages.get(pageNumber - 1);
|
||||
|
||||
// Group rects by their decoded colour so each area keeps its own overlay tint.
|
||||
Map<Color, List<PDRectangle>> byColor = new LinkedHashMap<>();
|
||||
List<PDRectangle> allRects = new ArrayList<>();
|
||||
for (RedactionArea area : areasForPage) {
|
||||
float x = area.getX().floatValue();
|
||||
float y = area.getY().floatValue();
|
||||
float width = area.getWidth().floatValue();
|
||||
float height = area.getHeight().floatValue();
|
||||
// Request coords are top-left origin; convert to PDF user space (bottom-left).
|
||||
float pdfY = pageHeight - y - height;
|
||||
PDRectangle rect = new PDRectangle(x, pdfY, width, height);
|
||||
allRects.add(rect);
|
||||
byColor.computeIfAbsent(decodeOrDefault(area.getColor()), k -> new ArrayList<>())
|
||||
.add(rect);
|
||||
}
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||
|
||||
for (Map.Entry<Color, List<PDRectangle>> colorEntry : byColor.entrySet()) {
|
||||
Map<Integer, List<PDRectangle>> singlePage = new HashMap<>();
|
||||
singlePage.put(pageIndex, colorEntry.getValue());
|
||||
RedactionPipeline.RedactionResult result =
|
||||
RedactionPipeline.redactAreas(document, singlePage, colorEntry.getKey());
|
||||
capturedStrings.addAll(result.getCapturedStrings());
|
||||
forceRasterPages.addAll(result.getForceRasterPages());
|
||||
contentStream.saveGraphicsState();
|
||||
for (RedactionArea redactionArea : areasForPage) {
|
||||
Color redactColor = decodeOrDefault(redactionArea.getColor());
|
||||
|
||||
contentStream.setNonStrokingColor(redactColor);
|
||||
|
||||
float x = redactionArea.getX().floatValue();
|
||||
float y = redactionArea.getY().floatValue();
|
||||
float width = redactionArea.getWidth().floatValue();
|
||||
float height = redactionArea.getHeight().floatValue();
|
||||
|
||||
float pdfY = page.getBBox().getHeight() - y - height;
|
||||
|
||||
contentStream.addRect(x, pdfY, width, height);
|
||||
contentStream.fill();
|
||||
}
|
||||
contentStream.restoreGraphicsState();
|
||||
}
|
||||
rectsByPage.put(pageIndex, allRects);
|
||||
}
|
||||
|
||||
log.debug(
|
||||
"Manual area redaction captured {} text run(s) across {} page(s)",
|
||||
capturedStrings.size(),
|
||||
rectsByPage.size());
|
||||
return new AreaRedactionResult(rectsByPage, forceRasterPages, capturedStrings);
|
||||
}
|
||||
|
||||
List<Integer> redactPages(
|
||||
ManualRedactPdfRequest request, PDDocument document, PDPageTree allPages)
|
||||
void redactPages(ManualRedactPdfRequest request, PDDocument document, PDPageTree allPages)
|
||||
throws IOException {
|
||||
|
||||
Color redactColor = decodeOrDefault(request.getPageRedactionColor());
|
||||
List<Integer> pageIndexes = getPageNumbers(request, allPages.getCount());
|
||||
List<Integer> pageNumbers = getPageNumbers(request, allPages.getCount());
|
||||
|
||||
// Whole-page wipe: drop the content stream, resources and annotations, then fill.
|
||||
RedactionPipeline.redactWholePages(document, pageIndexes, redactColor);
|
||||
return new ArrayList<>(pageIndexes);
|
||||
for (Integer pageNumber : pageNumbers) {
|
||||
PDPage page = allPages.get(pageNumber);
|
||||
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||
contentStream.setNonStrokingColor(redactColor);
|
||||
|
||||
PDRectangle box = page.getBBox();
|
||||
contentStream.addRect(0, 0, box.getWidth(), box.getHeight());
|
||||
contentStream.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Overlay drawing
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
void redactFoundText(
|
||||
PDDocument document,
|
||||
@@ -166,10 +158,7 @@ class ManualRedactionService {
|
||||
|
||||
try {
|
||||
contentStream.setNonStrokingColor(redactColor);
|
||||
// TextPosition coords are relative to the CropBox origin.
|
||||
PDRectangle crop = page.getCropBox();
|
||||
float cropX = crop.getLowerLeftX();
|
||||
float cropY = crop.getLowerLeftY();
|
||||
PDRectangle pageBox = page.getBBox();
|
||||
|
||||
for (PDFText block : pageBlocks) {
|
||||
float padding =
|
||||
@@ -190,8 +179,8 @@ class ManualRedactionService {
|
||||
}
|
||||
|
||||
contentStream.addRect(
|
||||
cropX + boxX,
|
||||
cropY + crop.getHeight() - block.getY2() - padding,
|
||||
boxX,
|
||||
pageBox.getHeight() - block.getY2() - padding,
|
||||
boxWidth,
|
||||
block.getY2() - block.getY1() + 2 * padding);
|
||||
}
|
||||
@@ -203,8 +192,8 @@ class ManualRedactionService {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove annotations whose bounding rect overlaps a redacted block, to prevent users
|
||||
// from hovering over redacted URLs and seeing the underlying destination.
|
||||
// Remove annotations whose bounding rect overlaps a redacted block, to prevent
|
||||
// users from hovering over redacted URLs and seeing the underlying destination.
|
||||
try {
|
||||
float pageH = page.getBBox().getHeight();
|
||||
List<PDAnnotation> kept = new ArrayList<>();
|
||||
@@ -258,19 +247,14 @@ class ManualRedactionService {
|
||||
continue;
|
||||
}
|
||||
PDPage page = pages.get(pageIdx);
|
||||
PDRectangle crop = page.getCropBox();
|
||||
float cropX = crop.getLowerLeftX();
|
||||
float cropY = crop.getLowerLeftY();
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||
cs.saveGraphicsState();
|
||||
cs.setNonStrokingColor(color);
|
||||
for (float[] box : entry.getValue()) {
|
||||
// Box coords are CropBox-relative; offset by the CropBox origin
|
||||
// (cropbox-overlay).
|
||||
float x1 = box[1], y1 = box[2], x2 = box[3], y2 = box[4];
|
||||
cs.addRect(cropX + x1, cropY + y1, x2 - x1, y2 - y1);
|
||||
cs.addRect(x1, y1, x2 - x1, y2 - y1);
|
||||
}
|
||||
cs.fill();
|
||||
cs.restoreGraphicsState();
|
||||
@@ -278,7 +262,9 @@ class ManualRedactionService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Page element extraction
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns bounding boxes for every text line and image on {@code page} in PDF user-space
|
||||
@@ -302,7 +288,9 @@ class ManualRedactionService {
|
||||
return boxes;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Finalization
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
TempFile finalizeRedaction(
|
||||
PDDocument document,
|
||||
@@ -310,37 +298,7 @@ class ManualRedactionService {
|
||||
String colorString,
|
||||
float customPadding,
|
||||
Boolean convertToImage,
|
||||
boolean isTextRemovalMode,
|
||||
Set<String> literalTargets,
|
||||
List<Pattern> patterns)
|
||||
throws IOException {
|
||||
return finalizeRedaction(
|
||||
document,
|
||||
allFoundTextsByPage,
|
||||
colorString,
|
||||
customPadding,
|
||||
convertToImage,
|
||||
isTextRemovalMode,
|
||||
literalTargets,
|
||||
patterns,
|
||||
Collections.emptySet());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param geometricRasterPages 0-based pages carrying a range / image-box redaction, whose
|
||||
* covered content (text under an overlay, or an image) is not text-removable and so must be
|
||||
* rasterised to guarantee removal.
|
||||
*/
|
||||
TempFile finalizeRedaction(
|
||||
PDDocument document,
|
||||
Map<Integer, List<PDFText>> allFoundTextsByPage,
|
||||
String colorString,
|
||||
float customPadding,
|
||||
Boolean convertToImage,
|
||||
boolean isTextRemovalMode,
|
||||
Set<String> literalTargets,
|
||||
List<Pattern> patterns,
|
||||
Set<Integer> geometricRasterPages)
|
||||
boolean isTextRemovalMode)
|
||||
throws IOException {
|
||||
|
||||
List<PDFText> allFoundTexts = new ArrayList<>();
|
||||
@@ -351,84 +309,74 @@ class ManualRedactionService {
|
||||
if (!allFoundTexts.isEmpty()) {
|
||||
Color redactColor = decodeOrDefault(colorString);
|
||||
redactFoundText(document, allFoundTexts, customPadding, redactColor, isTextRemovalMode);
|
||||
cleanDocumentMetadata(document);
|
||||
}
|
||||
|
||||
byte[] outputBytes;
|
||||
if (Boolean.TRUE.equals(convertToImage)) {
|
||||
try (PDDocument convertedPdf = PdfUtils.convertPdfToPdfImage(document)) {
|
||||
// Convert-to-image physically removes all text, so verification is a plain save.
|
||||
outputBytes =
|
||||
RedactionPipeline.finalize(
|
||||
convertedPdf, Collections.emptySet(), Collections.emptyList());
|
||||
cleanDocumentMetadata(convertedPdf);
|
||||
|
||||
TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
|
||||
try {
|
||||
convertedPdf.save(tempOut.getFile());
|
||||
} catch (IOException e) {
|
||||
tempOut.close();
|
||||
throw e;
|
||||
}
|
||||
|
||||
log.info(
|
||||
"Redaction finalized (image mode): {} pages ➜ {} KB",
|
||||
convertedPdf.getNumberOfPages(),
|
||||
tempOut.getFile().length() / 1024);
|
||||
|
||||
return tempOut;
|
||||
}
|
||||
} else {
|
||||
// Strip matched glyphs, then scrub/verify/rasterise via finalize.
|
||||
RedactionPipeline.redactLiteralTerms(document, literalTargets, patterns);
|
||||
outputBytes = RedactionPipeline.finalize(document, literalTargets, patterns);
|
||||
// Geometric (range/image-box) redactions can't be text-removed; rasterise their pages.
|
||||
outputBytes =
|
||||
RedactionPipeline.rasteriseSpecificPages(
|
||||
outputBytes, geometricRasterPages, literalTargets, patterns);
|
||||
}
|
||||
|
||||
return writeBytes(outputBytes, document.getNumberOfPages());
|
||||
}
|
||||
|
||||
/** Finalize a manual redaction; forced + verified-leaking pages are rasterised. */
|
||||
TempFile finalizeManual(
|
||||
PDDocument document, AreaRedactionResult areaResult, Boolean convertToImage)
|
||||
throws IOException {
|
||||
|
||||
byte[] outputBytes;
|
||||
if (Boolean.TRUE.equals(convertToImage)) {
|
||||
try (PDDocument convertedPdf = PdfUtils.convertPdfToPdfImage(document)) {
|
||||
outputBytes =
|
||||
RedactionPipeline.finalize(
|
||||
convertedPdf, Collections.emptySet(), Collections.emptyList());
|
||||
}
|
||||
} else {
|
||||
outputBytes =
|
||||
RedactionPipeline.finalizeAreas(
|
||||
document,
|
||||
areaResult.rectsByPage,
|
||||
areaResult.forceRasterPages,
|
||||
areaResult.capturedStrings);
|
||||
}
|
||||
|
||||
return writeBytes(outputBytes, document.getNumberOfPages());
|
||||
}
|
||||
|
||||
private TempFile writeBytes(byte[] outputBytes, int pageCount) throws IOException {
|
||||
TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
|
||||
try {
|
||||
java.nio.file.Files.write(tempOut.getFile().toPath(), outputBytes);
|
||||
document.save(tempOut.getFile());
|
||||
} catch (IOException e) {
|
||||
tempOut.close();
|
||||
throw e;
|
||||
}
|
||||
|
||||
log.info("Redaction finalized: {} pages -> {} KB", pageCount, outputBytes.length / 1024);
|
||||
log.info(
|
||||
"Redaction finalized: {} pages ➜ {} KB",
|
||||
document.getNumberOfPages(),
|
||||
tempOut.getFile().length() / 1024);
|
||||
|
||||
return tempOut;
|
||||
}
|
||||
|
||||
// Utilities
|
||||
private void cleanDocumentMetadata(PDDocument document) {
|
||||
try {
|
||||
var documentInfo = document.getDocumentInformation();
|
||||
if (documentInfo != null) {
|
||||
documentInfo.setAuthor(null);
|
||||
documentInfo.setSubject(null);
|
||||
documentInfo.setKeywords(null);
|
||||
documentInfo.setModificationDate(java.util.Calendar.getInstance());
|
||||
log.debug("Cleaned document metadata for security");
|
||||
}
|
||||
|
||||
/** Redaction rectangles, pages to force-rasterise, and the text captured under the rects. */
|
||||
static final class AreaRedactionResult {
|
||||
final Map<Integer, List<PDRectangle>> rectsByPage;
|
||||
final Set<Integer> forceRasterPages;
|
||||
final Set<String> capturedStrings;
|
||||
if (document.getDocumentCatalog() != null) {
|
||||
try {
|
||||
document.getDocumentCatalog().setMetadata(null);
|
||||
} catch (Exception e) {
|
||||
log.debug("Could not clear XMP metadata: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
AreaRedactionResult(
|
||||
Map<Integer, List<PDRectangle>> rectsByPage,
|
||||
Set<Integer> forceRasterPages,
|
||||
Set<String> capturedStrings) {
|
||||
this.rectsByPage = rectsByPage;
|
||||
this.forceRasterPages = forceRasterPages;
|
||||
this.capturedStrings = capturedStrings;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to clean document metadata: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Utilities
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
static Color decodeOrDefault(String hex) {
|
||||
if (hex == null) {
|
||||
return Color.BLACK;
|
||||
|
||||
+30
-54
@@ -1,15 +1,9 @@
|
||||
package stirling.software.SPDF.controller.api.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPageTree;
|
||||
@@ -35,13 +29,13 @@ import stirling.software.SPDF.model.api.security.RedactExecuteRequest.ImageBox;
|
||||
import stirling.software.SPDF.model.api.security.RedactExecuteRequest.RedactStyle;
|
||||
import stirling.software.SPDF.model.api.security.RedactExecuteRequest.TextRange;
|
||||
import stirling.software.SPDF.model.api.security.RedactPdfRequest;
|
||||
import stirling.software.SPDF.pdf.redaction.RedactionPipeline;
|
||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||
import stirling.software.common.annotations.api.SecurityApi;
|
||||
import stirling.software.common.enumeration.ResourceWeight;
|
||||
import stirling.software.common.model.api.security.RedactionArea;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
import stirling.software.common.util.PdfUtils;
|
||||
import stirling.software.common.util.TempFile;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.common.util.WebResponseUtils;
|
||||
@@ -99,24 +93,33 @@ public class RedactController {
|
||||
throws IOException {
|
||||
|
||||
MultipartFile file = request.getFileInput();
|
||||
String filename =
|
||||
removeFileExtension(
|
||||
Objects.requireNonNull(
|
||||
Filenames.toSimpleFileName(file.getOriginalFilename())))
|
||||
+ "_redacted.pdf";
|
||||
|
||||
try (PDDocument document = pdfDocumentFactory.load(file)) {
|
||||
PDPageTree allPages = document.getDocumentCatalog().getPages();
|
||||
|
||||
// Whole-page wipes drop content; areas drop glyphs + overlay, verified later.
|
||||
manualRedactionService.redactPages(request, document, allPages);
|
||||
ManualRedactionService.AreaRedactionResult areaResult =
|
||||
manualRedactionService.redactAreas(request.getRedactions(), document, allPages);
|
||||
manualRedactionService.redactAreas(request.getRedactions(), document, allPages);
|
||||
|
||||
TempFile out =
|
||||
manualRedactionService.finalizeManual(
|
||||
document, areaResult, request.getConvertPDFToImage());
|
||||
return WebResponseUtils.pdfFileToWebResponse(out, filename);
|
||||
if (Boolean.TRUE.equals(request.getConvertPDFToImage())) {
|
||||
try (PDDocument convertedPdf = PdfUtils.convertPdfToPdfImage(document)) {
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
convertedPdf,
|
||||
removeFileExtension(
|
||||
Objects.requireNonNull(
|
||||
Filenames.toSimpleFileName(
|
||||
file.getOriginalFilename())))
|
||||
+ "_redacted.pdf",
|
||||
tempFileManager);
|
||||
}
|
||||
}
|
||||
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
removeFileExtension(
|
||||
Objects.requireNonNull(
|
||||
Filenames.toSimpleFileName(file.getOriginalFilename())))
|
||||
+ "_redacted.pdf",
|
||||
tempFileManager);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,32 +188,9 @@ public class RedactController {
|
||||
request.getFileInput().getOriginalFilename())))
|
||||
+ "_redacted.pdf";
|
||||
|
||||
Set<String> literalTargets =
|
||||
Arrays.stream(listOfText)
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
List<Pattern> compiledPatterns =
|
||||
RedactionPipeline.buildPatterns(listOfText, useRegex, wholeWordSearchBool);
|
||||
// Bare literals match substrings; regex/whole-word rely on compiled patterns.
|
||||
Set<String> verificationTargets =
|
||||
(useRegex || wholeWordSearchBool) ? Collections.emptySet() : literalTargets;
|
||||
|
||||
if (allFoundTextsByPage.isEmpty()) {
|
||||
// No page hit, but the target may live in a bookmark/annotation/form/JS carrier, so
|
||||
// still run the scrub + verify path rather than just wiping metadata.
|
||||
log.info("No page text matched; scrubbing catalog carriers and verifying");
|
||||
TempFile finalized =
|
||||
manualRedactionService.finalizeRedaction(
|
||||
document,
|
||||
Collections.emptyMap(),
|
||||
request.getRedactColor(),
|
||||
request.getCustomPadding(),
|
||||
request.getConvertPDFToImage(),
|
||||
true,
|
||||
verificationTargets,
|
||||
compiledPatterns);
|
||||
return WebResponseUtils.pdfFileToWebResponse(finalized, filename);
|
||||
log.info("No text found matching redaction patterns");
|
||||
return WebResponseUtils.pdfDocToWebResponse(document, filename, tempFileManager);
|
||||
}
|
||||
|
||||
boolean fallbackToBoxOnlyMode;
|
||||
@@ -231,8 +211,7 @@ public class RedactController {
|
||||
|
||||
if (fallbackToBoxOnlyMode) {
|
||||
log.warn(
|
||||
"Font compatibility issue in placeholder pass; the true-removal pass and "
|
||||
+ "verification still guarantee the target is gone.");
|
||||
"Font compatibility issues detected. Using box-only redaction mode for better reliability.");
|
||||
|
||||
fallbackDocument = pdfDocumentFactory.load(request.getFileInput());
|
||||
|
||||
@@ -247,9 +226,7 @@ public class RedactController {
|
||||
request.getRedactColor(),
|
||||
request.getCustomPadding(),
|
||||
request.getConvertPDFToImage(),
|
||||
false,
|
||||
verificationTargets,
|
||||
compiledPatterns);
|
||||
false);
|
||||
|
||||
return WebResponseUtils.pdfFileToWebResponse(finalized, filename);
|
||||
}
|
||||
@@ -261,9 +238,7 @@ public class RedactController {
|
||||
request.getRedactColor(),
|
||||
request.getCustomPadding(),
|
||||
request.getConvertPDFToImage(),
|
||||
true,
|
||||
verificationTargets,
|
||||
compiledPatterns);
|
||||
true);
|
||||
|
||||
return WebResponseUtils.pdfFileToWebResponse(finalized, filename);
|
||||
|
||||
@@ -272,10 +247,11 @@ public class RedactController {
|
||||
throw new RuntimeException("Failed to perform PDF redaction: " + e.getMessage(), e);
|
||||
|
||||
} finally {
|
||||
// Both are distinct PDDocument handles.
|
||||
if (document != null) {
|
||||
try {
|
||||
document.close();
|
||||
if (fallbackDocument == null) {
|
||||
document.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to close main document: {}", e.getMessage());
|
||||
}
|
||||
|
||||
+29
-55
@@ -7,11 +7,8 @@ import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
@@ -33,7 +30,6 @@ import stirling.software.SPDF.model.api.security.RedactExecuteRequest.RedactStyl
|
||||
import stirling.software.SPDF.model.api.security.RedactExecuteRequest.TextRange;
|
||||
import stirling.software.SPDF.pdf.parser.PageColumnLayout;
|
||||
import stirling.software.SPDF.pdf.parser.PageImageLocator;
|
||||
import stirling.software.SPDF.pdf.redaction.RedactionPipeline;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
import stirling.software.common.util.TempFile;
|
||||
@@ -94,8 +90,8 @@ class RedactExecuteService {
|
||||
try {
|
||||
document = pdfDocumentFactory.load(request.getFileInput());
|
||||
|
||||
// Single-pass text scan: collect all text-based targets so we run the PDF stripper only
|
||||
// once across the entire execute() call rather than once per target.
|
||||
// Single-pass text scan: collect all text-based targets so we run the PDF
|
||||
// stripper only once across the entire execute() call rather than once per target.
|
||||
Map<Integer, List<PDFText>> foundTexts =
|
||||
hasTextOps ? collectTextMatches(document, request) : new HashMap<>();
|
||||
|
||||
@@ -105,13 +101,13 @@ class RedactExecuteService {
|
||||
totalMatches,
|
||||
foundTexts.size());
|
||||
|
||||
// Text removal (content-stream rewriting) - skipped in overlay-only mode.
|
||||
// Text removal (content-stream rewriting) — skipped in overlay-only mode.
|
||||
boolean needsOverlayOnly = overlayOnly;
|
||||
if (hasTextOps && !foundTexts.isEmpty() && !overlayOnly) {
|
||||
needsOverlayOnly = applyTextRemoval(document, request);
|
||||
} else if (overlayOnly) {
|
||||
log.info(
|
||||
"[redact/execute] overlay-only mode requested - skipping content-stream rewriting");
|
||||
"[redact/execute] overlay-only mode requested — skipping content-stream rewriting");
|
||||
}
|
||||
|
||||
// Reload fresh document on fallback so we overlay onto clean content.
|
||||
@@ -132,46 +128,25 @@ class RedactExecuteService {
|
||||
applyPageWipe(document, wipePages, style);
|
||||
}
|
||||
|
||||
// Range + image-box redactions are geometric overlays.
|
||||
Set<Integer> geometricRasterPages = new HashSet<>();
|
||||
for (TextRange range : ranges) {
|
||||
geometricRasterPages.addAll(
|
||||
applyRangeRedaction(document, range, style, layoutCache));
|
||||
applyRangeRedaction(document, range, style, layoutCache);
|
||||
}
|
||||
|
||||
for (ImageBox box : imageBoxes) {
|
||||
geometricRasterPages.addAll(applyImageBoxRedaction(document, box, style));
|
||||
applyImageBoxRedaction(document, box, style);
|
||||
}
|
||||
|
||||
if (request.getRedactImagePages() != null) {
|
||||
applyAllImagesRedaction(document, request.getRedactImagePages(), style);
|
||||
}
|
||||
|
||||
// Overlay-only skips removal/verify; font-fallback overlays still pass targets.
|
||||
Set<String> literalTargets = new LinkedHashSet<>();
|
||||
for (String value : textValues) {
|
||||
String trimmed = value == null ? "" : value.trim();
|
||||
if (!trimmed.isEmpty()) {
|
||||
literalTargets.add(trimmed);
|
||||
}
|
||||
}
|
||||
List<Pattern> verificationPatterns =
|
||||
RedactionPipeline.buildPatterns(
|
||||
regexPatterns.toArray(new String[0]), true, false);
|
||||
Set<String> finalizeTargets = overlayOnly ? Collections.emptySet() : literalTargets;
|
||||
List<Pattern> finalizePatterns =
|
||||
overlayOnly ? Collections.emptyList() : verificationPatterns;
|
||||
|
||||
return manualRedactionService.finalizeRedaction(
|
||||
document,
|
||||
foundTexts,
|
||||
style.getColor(),
|
||||
style.getPadding(),
|
||||
convertToImage,
|
||||
!needsOverlayOnly,
|
||||
finalizeTargets,
|
||||
finalizePatterns,
|
||||
geometricRasterPages);
|
||||
!needsOverlayOnly);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Execute redaction failed: {}", e.getMessage(), e);
|
||||
@@ -187,7 +162,9 @@ class RedactExecuteService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Single-pass text scan (one stripper pass per execute() call)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Runs a single PDF text-stripper pass over all text-based targets and returns the merged hit
|
||||
@@ -220,7 +197,9 @@ class RedactExecuteService {
|
||||
return found;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Text removal (content-stream rewriting)
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Attempts content-stream text removal for all text/regex targets. Returns {@code true} if the
|
||||
@@ -254,7 +233,7 @@ class RedactExecuteService {
|
||||
|
||||
if (fallback) {
|
||||
log.warn(
|
||||
"[redact/execute] font compatibility issue - falling back to overlay-only");
|
||||
"[redact/execute] font compatibility issue — falling back to overlay-only");
|
||||
} else {
|
||||
log.info("[redact/execute] content-stream text removal applied successfully");
|
||||
}
|
||||
@@ -267,7 +246,9 @@ class RedactExecuteService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Per-operation dispatch methods
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private void applyPageWipe(PDDocument document, List<Integer> pageNumbers, RedactStyle style)
|
||||
throws IOException {
|
||||
@@ -323,10 +304,7 @@ class RedactExecuteService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 0-based pages covered by the range overlay; those pages must be rasterised.
|
||||
*/
|
||||
private Set<Integer> applyRangeRedaction(
|
||||
private void applyRangeRedaction(
|
||||
PDDocument document,
|
||||
TextRange range,
|
||||
RedactStyle style,
|
||||
@@ -344,11 +322,6 @@ class RedactExecuteService {
|
||||
style.getPadding(),
|
||||
ManualRedactionService.decodeOrDefault(style.getColor()),
|
||||
false);
|
||||
Set<Integer> pages = new HashSet<>();
|
||||
for (PDFText block : blocks) {
|
||||
pages.add(block.getPageIndex());
|
||||
}
|
||||
return pages;
|
||||
} else {
|
||||
log.warn(
|
||||
"[redact/execute] range not found: start='{}' end='{}'",
|
||||
@@ -358,14 +331,10 @@ class RedactExecuteService {
|
||||
} catch (Exception e) {
|
||||
log.warn("[redact/execute] range redaction failed: {}", e.getMessage());
|
||||
}
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 0-based page covered by the image-box overlay; that page must be rasterised.
|
||||
*/
|
||||
private Set<Integer> applyImageBoxRedaction(
|
||||
PDDocument document, ImageBox box, RedactStyle style) throws IOException {
|
||||
private void applyImageBoxRedaction(PDDocument document, ImageBox box, RedactStyle style)
|
||||
throws IOException {
|
||||
List<float[]> boxes =
|
||||
List.of(
|
||||
new float[] {
|
||||
@@ -374,7 +343,6 @@ class RedactExecuteService {
|
||||
log.info("[redact/execute] image box overlay on page {}", box.pageIndex());
|
||||
Color boxColor = ManualRedactionService.decodeOrDefault(style.getColor());
|
||||
manualRedactionService.redactImageBoxes(document, boxes, boxColor);
|
||||
return Set.of(box.pageIndex());
|
||||
}
|
||||
|
||||
private void applyAllImagesRedaction(
|
||||
@@ -418,7 +386,9 @@ class RedactExecuteService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Range collection helpers
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Locates {@code startStr} in the document and returns {@link PDFText} blocks for every text
|
||||
@@ -488,7 +458,7 @@ class RedactExecuteService {
|
||||
}
|
||||
if (end == null) {
|
||||
log.warn(
|
||||
"[redact/execute] no end anchor after start at (page={}, col={}, y={}) - skipping",
|
||||
"[redact/execute] no end anchor after start at (page={}, col={}, y={}) — skipping",
|
||||
start.page + 1,
|
||||
start.col,
|
||||
start.y);
|
||||
@@ -509,7 +479,7 @@ class RedactExecuteService {
|
||||
}
|
||||
|
||||
log.info(
|
||||
"[redact/execute] range '{}'->'{}': {} total blocks",
|
||||
"[redact/execute] range '{}'→'{}': {} total blocks",
|
||||
startStr,
|
||||
openEnded ? "<end of document>" : endStr,
|
||||
blocks.size());
|
||||
@@ -541,6 +511,7 @@ class RedactExecuteService {
|
||||
float endY = openEnded ? Float.POSITIVE_INFINITY : end.text.getY2();
|
||||
|
||||
// Line-box cache: populated lazily per page, reused across range iterations.
|
||||
// Cannot use computeIfAbsent because AllTextLineExtractor's constructor throws IOException.
|
||||
Map<Integer, List<float[]>> lineBoxCache = new HashMap<>();
|
||||
|
||||
for (int pageIdx = startPage; pageIdx <= endPage; pageIdx++) {
|
||||
@@ -706,7 +677,7 @@ class RedactExecuteService {
|
||||
if (i > 0) sb.append(", ");
|
||||
sb.append(String.format("(p=%d,c=%d,y=%.1f)", a.page + 1, a.col, a.y));
|
||||
}
|
||||
if (anchors.size() > max) sb.append(", ...");
|
||||
if (anchors.size() > max) sb.append(", …");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@@ -732,8 +703,9 @@ class RedactExecuteService {
|
||||
candidates.add(new Candidate(tolerant, true));
|
||||
}
|
||||
|
||||
// Long multi-line anchors mismatch on extraction artifacts, so try just the first non-empty
|
||||
// line.
|
||||
// If the anchor spans multiple lines (model provided entire paragraph instead of a short
|
||||
// phrase), try just the first non-empty line — it's usually sufficient to locate the
|
||||
// position and avoids mismatches from mid-paragraph text extraction artifacts.
|
||||
if (trimmed.contains("\n")) {
|
||||
String firstLine =
|
||||
Arrays.stream(trimmed.split("\n"))
|
||||
@@ -761,7 +733,7 @@ class RedactExecuteService {
|
||||
if (!m.isEmpty()) {
|
||||
if (!c.pattern.equals(trimmed)) {
|
||||
log.info(
|
||||
"[redact/execute] range boundary matched via fallback: '{}' -> '{}'",
|
||||
"[redact/execute] range boundary matched via fallback: '{}' → '{}'",
|
||||
trimmed,
|
||||
c.pattern);
|
||||
}
|
||||
@@ -773,7 +745,9 @@ class RedactExecuteService {
|
||||
|
||||
private record Candidate(String pattern, boolean useRegex) {}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Static helpers
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Joins {@code raw}'s alphanumeric runs with {@code \W*} so anchors match across punctuation
|
||||
|
||||
+20
-5
@@ -46,11 +46,12 @@ class TextRedactionService {
|
||||
private static final int MAX_XOBJECT_DEPTH = 10;
|
||||
private static final float PRECISION_THRESHOLD = 1e-3f;
|
||||
private static final int FONT_SCALE_FACTOR = 1000;
|
||||
private static final Set<String> TEXT_SHOWING_OPERATORS =
|
||||
stirling.software.SPDF.pdf.redaction.RedactionPipeline.TEXT_SHOWING_OPERATORS;
|
||||
private static final Set<String> TEXT_SHOWING_OPERATORS = Set.of("Tj", "TJ", "'", "\"");
|
||||
private static final COSString EMPTY_COS_STRING = new COSString("");
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Public API
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
Map<Integer, List<PDFText>> findTextToRedact(
|
||||
PDDocument document, String[] listOfText, boolean useRegex, boolean wholeWordSearch) {
|
||||
@@ -134,7 +135,9 @@ class TextRedactionService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Content stream manipulation
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
List<Object> createTokensWithoutTargetText(
|
||||
PDDocument document,
|
||||
@@ -268,7 +271,9 @@ class TextRedactionService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Placeholder creation
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
String createPlaceholderWithFont(String originalWord, PDFont font) {
|
||||
if (originalWord == null || originalWord.isEmpty()) {
|
||||
@@ -405,7 +410,9 @@ class TextRedactionService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Width calculation
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private float safeGetStringWidth(PDFont font, String text) {
|
||||
if (font == null || text == null || text.isEmpty()) {
|
||||
@@ -594,7 +601,9 @@ class TextRedactionService {
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Token and segment operations
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private void processPageXObjects(
|
||||
PDDocument document,
|
||||
@@ -697,12 +706,16 @@ class TextRedactionService {
|
||||
private void writeRedactedContentToXObject(
|
||||
PDDocument document, PDFormXObject formXObject, List<Object> redactedTokens)
|
||||
throws IOException {
|
||||
// A form XObject's content IS its own stream body; overwrite it in place.
|
||||
PDStream formStream = new PDStream(formXObject.getCOSObject());
|
||||
try (var out = formStream.createOutputStream(COSName.FLATE_DECODE)) {
|
||||
|
||||
PDStream newStream = new PDStream(document);
|
||||
|
||||
try (var out = newStream.createOutputStream()) {
|
||||
ContentStreamWriter writer = new ContentStreamWriter(out);
|
||||
writer.writeTokens(redactedTokens);
|
||||
}
|
||||
|
||||
formXObject.getCOSObject().removeItem(COSName.CONTENTS);
|
||||
formXObject.getCOSObject().setItem(COSName.CONTENTS, newStream.getCOSObject());
|
||||
}
|
||||
|
||||
private List<TextSegment> extractTextSegments(PDPage page, List<Object> tokens) {
|
||||
@@ -1155,7 +1168,9 @@ class TextRedactionService {
|
||||
};
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Inner data classes
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Data
|
||||
private static class GraphicsState {
|
||||
|
||||
@@ -1,755 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.cos.COSArray;
|
||||
import org.apache.pdfbox.cos.COSBase;
|
||||
import org.apache.pdfbox.cos.COSDictionary;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.cos.COSObject;
|
||||
import org.apache.pdfbox.cos.COSStream;
|
||||
import org.apache.pdfbox.cos.COSString;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.common.PDMetadata;
|
||||
import org.apache.pdfbox.pdmodel.common.PDNameTreeNode;
|
||||
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
|
||||
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
|
||||
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
|
||||
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/** Removes/rewrites every catalog carrier that could leak redacted text. */
|
||||
@Slf4j
|
||||
public final class CatalogScrubber {
|
||||
|
||||
// A literal shorter than this won't delete a whole carrier (JS/XFA/action/embedded file).
|
||||
private static final int MIN_CARRIER_DROP_LITERAL = 3;
|
||||
|
||||
private CatalogScrubber() {}
|
||||
|
||||
/** Scrub all catalog-level carriers of the given literal/regex targets. */
|
||||
public static void scrub(
|
||||
PDDocument document, Set<String> literalTargets, List<Pattern> patterns) {
|
||||
if (document == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
||||
if (catalog == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
scrubOutline(catalog.getDocumentOutline(), literalTargets, patterns);
|
||||
scrubAcroForm(catalog.getAcroForm(), literalTargets, patterns);
|
||||
scrubAnnotations(document, literalTargets, patterns);
|
||||
scrubStructTree(catalog.getStructureTreeRoot(), literalTargets, patterns);
|
||||
scrubNames(catalog.getNames(), literalTargets, patterns);
|
||||
scrubCatalogActions(catalog, literalTargets, patterns);
|
||||
scrubDocumentInfo(document, literalTargets, patterns);
|
||||
}
|
||||
|
||||
// Catalog actions: OpenAction, AA, and any JavaScript / URI payloads
|
||||
|
||||
private static void scrubCatalogActions(
|
||||
PDDocumentCatalog catalog, Set<String> targets, List<Pattern> patterns) {
|
||||
COSDictionary root = catalog.getCOSObject();
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
// OpenAction may be either an action dict (with /URI or /JS) or an explicit
|
||||
scrubActionIfMatching(root, COSName.getPDFName("OpenAction"), targets, patterns);
|
||||
scrubActionIfMatching(root, COSName.getPDFName("AA"), targets, patterns);
|
||||
}
|
||||
|
||||
/** Drop the action at key if any target appears in its URI/JS payload. */
|
||||
private static void scrubActionIfMatching(
|
||||
COSDictionary parent, COSName key, Set<String> targets, List<Pattern> patterns) {
|
||||
if (parent == null || key == null) {
|
||||
return;
|
||||
}
|
||||
COSBase value = parent.getDictionaryObject(key);
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
if (containsTarget(value, carrierDropLiterals(targets), patterns, new HashSet<>())) {
|
||||
log.debug("Removing catalog {} due to target match", key.getName());
|
||||
parent.removeItem(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Literals specific enough to justify DELETING an entire carrier (JS / XFA / action / embedded
|
||||
* file). Sub-threshold literals (a single digit, a 2-char run) would nuke unrelated carriers,
|
||||
* so they are excluded from whole-carrier drops - they are still removed in-string by
|
||||
* stripMatches where the carrier is a plain string.
|
||||
*/
|
||||
private static Set<String> carrierDropLiterals(Set<String> targets) {
|
||||
if (targets == null) {
|
||||
return java.util.Collections.emptySet();
|
||||
}
|
||||
Set<String> specific = new LinkedHashSet<>();
|
||||
for (String t : targets) {
|
||||
if (t != null && t.trim().length() >= MIN_CARRIER_DROP_LITERAL) {
|
||||
specific.add(t);
|
||||
}
|
||||
}
|
||||
return specific;
|
||||
}
|
||||
|
||||
private static boolean containsTarget(
|
||||
COSBase base, Set<String> targets, List<Pattern> patterns, Set<COSBase> seen) {
|
||||
if (base == null) {
|
||||
return false;
|
||||
}
|
||||
COSBase resolved = base instanceof COSObject obj ? obj.getObject() : base;
|
||||
if (resolved == null || !seen.add(resolved)) {
|
||||
return false;
|
||||
}
|
||||
if (resolved instanceof COSString cs) {
|
||||
return matches(cs.getString(), targets, patterns);
|
||||
}
|
||||
if (resolved instanceof COSStream stream) {
|
||||
// Streams in XFA / OpenAction contexts are text (XML, JavaScript).
|
||||
try (java.io.InputStream is = stream.createInputStream()) {
|
||||
byte[] buf = new byte[2 * 1024 * 1024];
|
||||
int total = 0;
|
||||
int n;
|
||||
while ((n = is.read(buf, total, buf.length - total)) > 0) {
|
||||
total += n;
|
||||
if (total >= buf.length) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
String text = new String(buf, 0, total, java.nio.charset.StandardCharsets.UTF_8);
|
||||
if (matches(text, targets, patterns)) {
|
||||
return true;
|
||||
}
|
||||
// Fail closed: content past the 2 MiB cap is unproven, so treat as a match.
|
||||
return total >= buf.length && is.read() >= 0;
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scan stream for targets: {}", e.getMessage());
|
||||
// Fail closed: if we cannot read it we cannot prove it is clean, so treat
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (resolved instanceof COSDictionary dict) {
|
||||
for (COSName k : new HashSet<>(dict.keySet())) {
|
||||
if (containsTarget(dict.getItem(k), targets, patterns, seen)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (resolved instanceof COSArray array) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
if (containsTarget(array.getObject(i), targets, patterns, seen)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the redaction target from /Info string entries and drop the XMP packet only if it
|
||||
* carries a target. Non-matching document properties (Title, Author, dates) are left intact -
|
||||
* redaction removes the target, it does not blanket-wipe metadata.
|
||||
*/
|
||||
private static void scrubDocumentInfo(
|
||||
PDDocument document, Set<String> targets, List<Pattern> patterns) {
|
||||
PDDocumentInformation info = document.getDocumentInformation();
|
||||
if (info != null && info.getCOSObject() != null) {
|
||||
COSDictionary infoDict = info.getCOSObject();
|
||||
for (COSName key : new HashSet<>(infoDict.keySet())) {
|
||||
if (infoDict.getDictionaryObject(key) instanceof COSString cs) {
|
||||
String stripped = stripMatches(cs.getString(), targets, patterns);
|
||||
if (!stripped.equals(cs.getString())) {
|
||||
if (stripped.isEmpty()) {
|
||||
infoDict.removeItem(key);
|
||||
} else {
|
||||
infoDict.setString(key, stripped);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
||||
if (catalog != null && catalog.getMetadata() != null) {
|
||||
scrubXmp(document, catalog, targets, patterns);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* XMP is RDF/XML that usually mirrors /Info. Strip only the target occurrences so non-matching
|
||||
* properties (dates, rights, custom schema) survive; fall back to dropping the whole packet if
|
||||
* the edit can't be proven to have removed the target (e.g. entity-encoded) or anything throws.
|
||||
*/
|
||||
private static void scrubXmp(
|
||||
PDDocument document,
|
||||
PDDocumentCatalog catalog,
|
||||
Set<String> targets,
|
||||
List<Pattern> patterns) {
|
||||
String xmp;
|
||||
try {
|
||||
xmp = new String(catalog.getMetadata().toByteArray(), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
log.debug("Could not read XMP metadata: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
if (!matches(xmp, targets, patterns)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String stripped = stripMatches(xmp, targets, patterns);
|
||||
// Only keep the edited packet if the target is provably gone from it.
|
||||
if (!matches(stripped, targets, patterns)) {
|
||||
catalog.setMetadata(
|
||||
new PDMetadata(
|
||||
document,
|
||||
new ByteArrayInputStream(
|
||||
stripped.getBytes(StandardCharsets.UTF_8))));
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Surgical XMP scrub failed; dropping packet: {}", e.getMessage());
|
||||
}
|
||||
catalog.setMetadata(null);
|
||||
}
|
||||
|
||||
// Outline
|
||||
|
||||
private static void scrubOutline(
|
||||
PDDocumentOutline outline, Set<String> targets, List<Pattern> patterns) {
|
||||
if (outline == null) {
|
||||
return;
|
||||
}
|
||||
scrubOutlineItems(outline.children(), targets, patterns);
|
||||
}
|
||||
|
||||
private static void scrubOutlineItems(
|
||||
Iterable<PDOutlineItem> items, Set<String> targets, List<Pattern> patterns) {
|
||||
if (items == null) {
|
||||
return;
|
||||
}
|
||||
for (PDOutlineItem item : items) {
|
||||
try {
|
||||
String title = item.getTitle();
|
||||
if (title != null) {
|
||||
String stripped = stripMatches(title, targets, patterns);
|
||||
if (!stripped.equals(title)) {
|
||||
item.setTitle(stripped);
|
||||
}
|
||||
}
|
||||
// Bookmark actions: /A is an action dict which may carry a /URI or /JS
|
||||
COSDictionary itemDict = item.getCOSObject();
|
||||
if (itemDict != null) {
|
||||
scrubActionIfMatching(itemDict, COSName.A, targets, patterns);
|
||||
scrubActionIfMatching(itemDict, COSName.getPDFName("AA"), targets, patterns);
|
||||
}
|
||||
scrubOutlineItems(item.children(), targets, patterns);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scrub outline item: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AcroForm
|
||||
|
||||
private static void scrubAcroForm(
|
||||
PDAcroForm form, Set<String> targets, List<Pattern> patterns) {
|
||||
if (form == null) {
|
||||
return;
|
||||
}
|
||||
// XFA forms: scrubbed separately because the XFA XML packet carries
|
||||
scrubXfa(form, targets, patterns);
|
||||
|
||||
try {
|
||||
for (PDField field : form.getFieldTree()) {
|
||||
scrubField(field, targets, patterns);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to walk AcroForm field tree: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// Force viewers to regenerate appearance streams from the (scrubbed) /V
|
||||
try {
|
||||
form.setNeedAppearances(true);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to set /NeedAppearances on AcroForm: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void scrubXfa(PDAcroForm form, Set<String> targets, List<Pattern> patterns) {
|
||||
try {
|
||||
COSBase xfaBase = form.getCOSObject().getDictionaryObject(COSName.XFA);
|
||||
if (xfaBase == null) {
|
||||
return;
|
||||
}
|
||||
boolean hit =
|
||||
containsTarget(
|
||||
xfaBase, carrierDropLiterals(targets), patterns, new HashSet<>());
|
||||
if (hit) {
|
||||
// Simplest safe move: strip the XFA entry entirely.
|
||||
log.warn(
|
||||
"Removing XFA form packet from AcroForm - XFA XML contained a redaction "
|
||||
+ "target and has been dropped so viewers render AcroForm widgets "
|
||||
+ "instead.");
|
||||
form.getCOSObject().removeItem(COSName.XFA);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scrub XFA: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void scrubField(PDField field, Set<String> targets, List<Pattern> patterns) {
|
||||
if (field == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
COSDictionary dict = field.getCOSObject();
|
||||
// Only touch fields whose own values actually contain a target: clearing /AP
|
||||
// document-wide blanks unrelated fields in viewers that ignore /NeedAppearances.
|
||||
boolean matched =
|
||||
dictValueMatches(dict, COSName.V, targets, patterns)
|
||||
|| dictValueMatches(dict, COSName.DV, targets, patterns)
|
||||
|| dictValueMatches(dict, COSName.getPDFName("RV"), targets, patterns)
|
||||
|| dictValueMatches(dict, COSName.getPDFName("TU"), targets, patterns)
|
||||
|| buttonCaptionMatches(dict, targets, patterns)
|
||||
|| fieldValueMatches(field, targets, patterns);
|
||||
if (!matched) {
|
||||
return;
|
||||
}
|
||||
scrubDictStrings(dict, COSName.V, targets, patterns);
|
||||
scrubDictStrings(dict, COSName.DV, targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("RV"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("TU"), targets, patterns);
|
||||
// Keep field appearance streams in sync with value where possible.
|
||||
try {
|
||||
if (field.getValueAsString() != null) {
|
||||
String stripped = stripMatches(field.getValueAsString(), targets, patterns);
|
||||
if (!stripped.equals(field.getValueAsString())) {
|
||||
field.setValue(stripped);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to rewrite field value via setValue: {}", e.getMessage());
|
||||
}
|
||||
if (!isButtonField(dict)) {
|
||||
clearWidgetAppearances(dict);
|
||||
} else if (scrubButtonCaption(dict, targets, patterns)) {
|
||||
// A button caption (/MK /CA,/RC,/AC) that carried the target renders via /AP that
|
||||
// /NeedAppearances can't rebuild, so drop the stale /AP too.
|
||||
clearWidgetAppearances(dict);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scrub field: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static final String[] MK_CAPTION_KEYS = {"CA", "RC", "AC"};
|
||||
|
||||
/** True if a button widget's /MK caption (down/rollover/alternate) contains a target. */
|
||||
private static boolean buttonCaptionMatches(
|
||||
COSDictionary dict, Set<String> targets, List<Pattern> patterns) {
|
||||
for (COSDictionary mk : mkDicts(dict)) {
|
||||
for (String k : MK_CAPTION_KEYS) {
|
||||
if (dictValueMatches(mk, COSName.getPDFName(k), targets, patterns)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Strip target substrings from a button widget's /MK captions; true if any matched. */
|
||||
private static boolean scrubButtonCaption(
|
||||
COSDictionary dict, Set<String> targets, List<Pattern> patterns) {
|
||||
boolean hit = false;
|
||||
for (COSDictionary mk : mkDicts(dict)) {
|
||||
for (String k : MK_CAPTION_KEYS) {
|
||||
COSName key = COSName.getPDFName(k);
|
||||
if (dictValueMatches(mk, key, targets, patterns)) {
|
||||
hit = true;
|
||||
scrubDictStrings(mk, key, targets, patterns);
|
||||
}
|
||||
}
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
/** The /MK appearance-characteristics dicts on a field and any widget kids. */
|
||||
private static List<COSDictionary> mkDicts(COSDictionary dict) {
|
||||
List<COSDictionary> out = new java.util.ArrayList<>();
|
||||
if (dict.getDictionaryObject(COSName.getPDFName("MK")) instanceof COSDictionary mk) {
|
||||
out.add(mk);
|
||||
}
|
||||
if (dict.getDictionaryObject(COSName.KIDS) instanceof COSArray kids) {
|
||||
for (int i = 0; i < kids.size(); i++) {
|
||||
if (kids.getObject(i) instanceof COSDictionary kid
|
||||
&& kid.getDictionaryObject(COSName.getPDFName("MK"))
|
||||
instanceof COSDictionary mk) {
|
||||
out.add(mk);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean isButtonField(COSDictionary dict) {
|
||||
COSBase ftBase = dict.getDictionaryObject(COSName.FT);
|
||||
COSName ft = ftBase instanceof COSName n ? n : null;
|
||||
if (ft == null) {
|
||||
COSBase parent = dict.getDictionaryObject(COSName.PARENT);
|
||||
if (parent instanceof COSDictionary p
|
||||
&& p.getDictionaryObject(COSName.FT) instanceof COSName pn) {
|
||||
ft = pn;
|
||||
}
|
||||
}
|
||||
return COSName.getPDFName("Btn").equals(ft);
|
||||
}
|
||||
|
||||
private static boolean dictValueMatches(
|
||||
COSDictionary dict, COSName key, Set<String> targets, List<Pattern> patterns) {
|
||||
COSBase value = dict.getDictionaryObject(key);
|
||||
if (value instanceof COSString cs) {
|
||||
return matches(cs.getString(), targets, patterns);
|
||||
}
|
||||
if (value instanceof COSArray array) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
if (array.getObject(i) instanceof COSString element
|
||||
&& matches(element.getString(), targets, patterns)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean fieldValueMatches(
|
||||
PDField field, Set<String> targets, List<Pattern> patterns) {
|
||||
try {
|
||||
String value = field.getValueAsString();
|
||||
return value != null && matches(value, targets, patterns);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void clearWidgetAppearances(COSDictionary fieldDict) {
|
||||
if (fieldDict == null) {
|
||||
return;
|
||||
}
|
||||
// The field itself may be a widget (single-widget field) and/or have Kids.
|
||||
fieldDict.removeItem(COSName.AP);
|
||||
COSBase kids = fieldDict.getDictionaryObject(COSName.KIDS);
|
||||
if (kids instanceof COSArray arr) {
|
||||
for (int i = 0; i < arr.size(); i++) {
|
||||
COSBase kidBase = arr.getObject(i);
|
||||
if (kidBase instanceof COSDictionary kidDict) {
|
||||
kidDict.removeItem(COSName.AP);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Annotations
|
||||
|
||||
private static void scrubAnnotations(
|
||||
PDDocument document, Set<String> targets, List<Pattern> patterns) {
|
||||
try {
|
||||
for (PDPage page : document.getPages()) {
|
||||
// Page-level additional actions (/AA - open/close JS) can carry the target too.
|
||||
scrubActionIfMatching(
|
||||
page.getCOSObject(), COSName.getPDFName("AA"), targets, patterns);
|
||||
List<PDAnnotation> annotations;
|
||||
try {
|
||||
annotations = page.getAnnotations();
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to load annotations for page: {}", e.getMessage());
|
||||
continue;
|
||||
}
|
||||
if (annotations == null) {
|
||||
continue;
|
||||
}
|
||||
for (PDAnnotation annotation : annotations) {
|
||||
scrubAnnotation(annotation, targets, patterns);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Annotation scrub walk failed: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void scrubAnnotation(
|
||||
PDAnnotation annotation, Set<String> targets, List<Pattern> patterns) {
|
||||
if (annotation == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String contents = annotation.getContents();
|
||||
if (contents != null) {
|
||||
String stripped = stripMatches(contents, targets, patterns);
|
||||
if (!stripped.equals(contents)) {
|
||||
annotation.setContents(stripped);
|
||||
}
|
||||
}
|
||||
COSDictionary dict = annotation.getCOSObject();
|
||||
scrubDictStrings(dict, COSName.getPDFName("RC"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("Subj"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("T"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("NM"), targets, patterns);
|
||||
// Link/widget annotation actions can encode the target in a /URI or JS body.
|
||||
scrubActionIfMatching(dict, COSName.A, targets, patterns);
|
||||
scrubActionIfMatching(dict, COSName.getPDFName("AA"), targets, patterns);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scrub annotation: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Structure tree
|
||||
|
||||
private static void scrubStructTree(
|
||||
PDStructureTreeRoot root, Set<String> targets, List<Pattern> patterns) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
scrubStructDict(root.getCOSObject(), targets, patterns, new HashSet<>());
|
||||
} catch (Exception e) {
|
||||
log.debug("Structure tree scrub failed: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void scrubStructDict(
|
||||
COSBase base, Set<String> targets, List<Pattern> patterns, Set<COSBase> seen) {
|
||||
if (base == null) {
|
||||
return;
|
||||
}
|
||||
COSBase resolved = base instanceof COSObject obj ? obj.getObject() : base;
|
||||
if (resolved == null || !seen.add(resolved)) {
|
||||
return;
|
||||
}
|
||||
if (resolved instanceof COSDictionary dict) {
|
||||
// Do not walk into content streams - those are handled by content-stream
|
||||
if (resolved instanceof COSStream) {
|
||||
return;
|
||||
}
|
||||
scrubDictStrings(dict, COSName.getPDFName("ActualText"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("Alt"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("E"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("T"), targets, patterns);
|
||||
scrubDictStrings(dict, COSName.getPDFName("Lang"), targets, patterns);
|
||||
for (COSName key : new HashSet<>(dict.keySet())) {
|
||||
COSBase value = dict.getItem(key);
|
||||
if (value instanceof COSDictionary
|
||||
|| value instanceof COSArray
|
||||
|| value instanceof COSObject) {
|
||||
scrubStructDict(value, targets, patterns, seen);
|
||||
}
|
||||
}
|
||||
} else if (resolved instanceof COSArray array) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
scrubStructDict(array.getObject(i), targets, patterns, seen);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Names tree (JavaScript + embedded files)
|
||||
|
||||
private static void scrubNames(
|
||||
PDDocumentNameDictionary names, Set<String> targets, List<Pattern> patterns) {
|
||||
if (names == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
dropMatchingNames(names.getJavaScript(), targets, patterns);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scrub JavaScript names: {}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
dropMatchingNames(names.getEmbeddedFiles(), targets, patterns);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to scrub embedded-file names: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void dropMatchingNames(
|
||||
PDNameTreeNode<?> node, Set<String> targets, List<Pattern> patterns) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
COSDictionary dict = node.getCOSObject();
|
||||
if (dict == null) {
|
||||
return;
|
||||
}
|
||||
scrubNameTreeDict(dict, targets, patterns);
|
||||
}
|
||||
|
||||
private static void scrubNameTreeDict(
|
||||
COSDictionary dict, Set<String> targets, List<Pattern> patterns) {
|
||||
if (dict == null) {
|
||||
return;
|
||||
}
|
||||
// Guarded casts: a malformed /Names or /Kids must skip that carrier, not throw a swallowed
|
||||
// ClassCastException.
|
||||
COSArray namesArray =
|
||||
dict.getDictionaryObject(COSName.NAMES) instanceof COSArray a ? a : null;
|
||||
if (namesArray != null) {
|
||||
Set<String> dropLiterals = carrierDropLiterals(targets);
|
||||
for (int i = namesArray.size() - 2; i >= 0; i -= 2) {
|
||||
COSBase keyBase = namesArray.getObject(i);
|
||||
String key = keyBase instanceof COSString s ? s.getString() : null;
|
||||
// Drop the pair when the KEY or the VALUE (JS /JS stream, embedded-file bytes)
|
||||
// contains a target - not just the key.
|
||||
boolean keyHit = key != null && matches(key, dropLiterals, patterns);
|
||||
boolean valueHit =
|
||||
i + 1 < namesArray.size()
|
||||
&& containsTarget(
|
||||
namesArray.getObject(i + 1),
|
||||
dropLiterals,
|
||||
patterns,
|
||||
new HashSet<>());
|
||||
if (keyHit || valueHit) {
|
||||
namesArray.remove(i + 1);
|
||||
namesArray.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
COSArray kids = dict.getDictionaryObject(COSName.KIDS) instanceof COSArray a ? a : null;
|
||||
if (kids != null) {
|
||||
for (int i = 0; i < kids.size(); i++) {
|
||||
COSBase kid = kids.getObject(i);
|
||||
if (kid instanceof COSDictionary kidDict) {
|
||||
scrubNameTreeDict(kidDict, targets, patterns);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
private static void scrubDictStrings(
|
||||
COSDictionary dict, COSName key, Set<String> targets, List<Pattern> patterns) {
|
||||
if (dict == null || key == null) {
|
||||
return;
|
||||
}
|
||||
COSBase value = dict.getDictionaryObject(key);
|
||||
if (value instanceof COSString cosString) {
|
||||
String stripped = stripMatches(cosString.getString(), targets, patterns);
|
||||
if (!stripped.equals(cosString.getString())) {
|
||||
dict.setString(key, stripped);
|
||||
}
|
||||
} else if (value instanceof COSArray array) {
|
||||
for (int i = 0; i < array.size(); i++) {
|
||||
COSBase element = array.getObject(i);
|
||||
if (element instanceof COSString elementString) {
|
||||
String stripped = stripMatches(elementString.getString(), targets, patterns);
|
||||
if (!stripped.equals(elementString.getString())) {
|
||||
array.set(i, new COSString(stripped));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String stripMatches(String source, Set<String> literalTargets, List<Pattern> patterns) {
|
||||
if (source == null || source.isEmpty()) {
|
||||
return source;
|
||||
}
|
||||
String result = source;
|
||||
if (literalTargets != null) {
|
||||
for (String target : literalTargets) {
|
||||
if (target == null || target.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
// Case-insensitive literal removal. Verification is case-insensitive
|
||||
result = caseInsensitiveReplaceAll(result, target);
|
||||
}
|
||||
}
|
||||
if (patterns != null) {
|
||||
for (Pattern pattern : patterns) {
|
||||
try {
|
||||
// Force case-insensitive matching for catalog carriers regardless
|
||||
Pattern ci = withCaseInsensitive(pattern);
|
||||
result = ci.matcher(DeadlineCharSequence.of(result)).replaceAll("");
|
||||
} catch (RuntimeException | StackOverflowError e) {
|
||||
// Fail closed: a throwing regex means we cannot prove the carrier clean, so
|
||||
// drop the whole string rather than leaving it intact.
|
||||
log.warn("Pattern replace failed for {}; dropping carrier text", pattern);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static boolean matches(String source, Set<String> literalTargets, List<Pattern> patterns) {
|
||||
if (source == null || source.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String lower = source.toLowerCase(Locale.ROOT);
|
||||
if (literalTargets != null) {
|
||||
for (String target : literalTargets) {
|
||||
if (target != null
|
||||
&& !target.isEmpty()
|
||||
&& lower.contains(target.toLowerCase(Locale.ROOT))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (patterns != null) {
|
||||
for (Pattern pattern : patterns) {
|
||||
try {
|
||||
if (withCaseInsensitive(pattern)
|
||||
.matcher(DeadlineCharSequence.of(source))
|
||||
.find()) {
|
||||
return true;
|
||||
}
|
||||
} catch (RuntimeException | StackOverflowError e) {
|
||||
// Fail closed: a throwing regex counts as a match so the carrier is scrubbed.
|
||||
log.warn("Pattern match failed for {}; treating carrier as a match", pattern);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String caseInsensitiveReplaceAll(String source, String target) {
|
||||
if (target.isEmpty()) {
|
||||
return source;
|
||||
}
|
||||
Pattern literal =
|
||||
Pattern.compile(
|
||||
Pattern.quote(target), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
|
||||
return literal.matcher(source).replaceAll("");
|
||||
}
|
||||
|
||||
private static Pattern withCaseInsensitive(Pattern pattern) {
|
||||
if ((pattern.flags() & Pattern.CASE_INSENSITIVE) != 0) {
|
||||
return pattern;
|
||||
}
|
||||
try {
|
||||
return Pattern.compile(
|
||||
pattern.pattern(),
|
||||
pattern.flags() | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
|
||||
} catch (Exception e) {
|
||||
return pattern;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
/**
|
||||
* Wraps a match subject so a runaway (catastrophic-backtracking) regex aborts instead of hanging
|
||||
* the request thread: every {@link #charAt(int)} the matcher performs checks a wall-clock deadline
|
||||
* and throws once it is exceeded. The thrown {@link RegexTimeoutException} is a {@link
|
||||
* RuntimeException}, so the redaction match sites' existing fail-closed catches handle it.
|
||||
*/
|
||||
final class DeadlineCharSequence implements CharSequence {
|
||||
|
||||
/** Per-match wall-clock budget. A legitimate whole-document match finishes far inside this. */
|
||||
static final long DEFAULT_BUDGET_MILLIS = 2_000L;
|
||||
|
||||
static final class RegexTimeoutException extends RuntimeException {
|
||||
RegexTimeoutException(long budgetMillis) {
|
||||
super("Regex evaluation exceeded " + budgetMillis + " ms (possible ReDoS)");
|
||||
}
|
||||
}
|
||||
|
||||
private final CharSequence inner;
|
||||
private final long deadlineNanos;
|
||||
private final long budgetMillis;
|
||||
|
||||
private DeadlineCharSequence(CharSequence inner, long budgetMillis) {
|
||||
this.inner = inner;
|
||||
this.budgetMillis = budgetMillis;
|
||||
this.deadlineNanos = System.nanoTime() + budgetMillis * 1_000_000L;
|
||||
}
|
||||
|
||||
/** Wrap {@code text} with the default budget; null becomes an empty sequence. */
|
||||
static DeadlineCharSequence of(String text) {
|
||||
return new DeadlineCharSequence(text == null ? "" : text, DEFAULT_BUDGET_MILLIS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public char charAt(int index) {
|
||||
if (System.nanoTime() > deadlineNanos) {
|
||||
throw new RegexTimeoutException(budgetMillis);
|
||||
}
|
||||
return inner.charAt(index);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int length() {
|
||||
return inner.length();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence subSequence(int start, int end) {
|
||||
return inner.subSequence(start, end);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return inner.toString();
|
||||
}
|
||||
}
|
||||
-748
@@ -1,748 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.contentstream.operator.Operator;
|
||||
import org.apache.pdfbox.cos.COSArray;
|
||||
import org.apache.pdfbox.cos.COSBase;
|
||||
import org.apache.pdfbox.cos.COSFloat;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.cos.COSString;
|
||||
import org.apache.pdfbox.pdfparser.PDFStreamParser;
|
||||
import org.apache.pdfbox.pdfwriter.ContentStreamWriter;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
import org.apache.pdfbox.pdmodel.common.PDStream;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
|
||||
import org.apache.pdfbox.text.PDFTextStripperByArea;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.SPDF.pdf.parser.PageImageLocator;
|
||||
|
||||
/**
|
||||
* Content-stream editing: physically removes glyphs from page and form-XObject streams, both by
|
||||
* literal/regex match (auto-word) and by rect intersection (manual area), plus the area-capture and
|
||||
* overlay/annotation helpers those paths rely on.
|
||||
*/
|
||||
@Slf4j
|
||||
final class RedactionContentEditor {
|
||||
|
||||
private static final int MAX_XOBJECT_DEPTH = 10;
|
||||
|
||||
private RedactionContentEditor() {}
|
||||
|
||||
/** True only for upright pages whose CropBox origin is (0,0), where the rect flip is exact. */
|
||||
static boolean isSurgicallySafe(PDPage page) {
|
||||
if (page.getRotation() != 0) {
|
||||
return false;
|
||||
}
|
||||
PDRectangle crop = page.getCropBox();
|
||||
return crop.getLowerLeftX() == 0f && crop.getLowerLeftY() == 0f;
|
||||
}
|
||||
|
||||
/** Drop annotations whose rectangle overlaps any redaction rect. */
|
||||
static void removeOverlappingAnnotations(PDPage page, List<PDRectangle> rects) {
|
||||
try {
|
||||
List<PDAnnotation> kept = new ArrayList<>();
|
||||
for (var ann : page.getAnnotations()) {
|
||||
PDRectangle ar = ann.getRectangle();
|
||||
boolean overlaps = false;
|
||||
if (ar != null) {
|
||||
Rectangle2D.Float a =
|
||||
new Rectangle2D.Float(
|
||||
ar.getLowerLeftX(),
|
||||
ar.getLowerLeftY(),
|
||||
ar.getWidth(),
|
||||
ar.getHeight());
|
||||
for (PDRectangle rect : rects) {
|
||||
if (a.intersects(
|
||||
rect.getLowerLeftX(),
|
||||
rect.getLowerLeftY(),
|
||||
rect.getWidth(),
|
||||
rect.getHeight())) {
|
||||
overlaps = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!overlaps) {
|
||||
kept.add(ann);
|
||||
}
|
||||
}
|
||||
page.setAnnotations(kept);
|
||||
} catch (Exception e) {
|
||||
log.debug("Could not strip overlapping annotations: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
static List<Pattern> effectivePatterns(Set<String> literalTargets, List<Pattern> patterns) {
|
||||
List<Pattern> result = new ArrayList<>();
|
||||
if (literalTargets != null) {
|
||||
for (String target : literalTargets) {
|
||||
if (target == null || target.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
// Case-insensitive to match TextFinderUtils; removal must not miss finder hits.
|
||||
result.add(
|
||||
Pattern.compile(
|
||||
Pattern.quote(target),
|
||||
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE));
|
||||
}
|
||||
}
|
||||
if (patterns != null) {
|
||||
result.addAll(patterns);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Per-page content-stream rewrite (literal/regex based)
|
||||
|
||||
static void rewritePageContent(PDDocument document, PDPage page, List<Pattern> patterns)
|
||||
throws IOException {
|
||||
PDResources resources = page.getResources();
|
||||
if (resources == null) {
|
||||
return;
|
||||
}
|
||||
List<Object> tokens = parseTokens(new PDFStreamParser(page));
|
||||
boolean modified = rewriteTokens(tokens, resources, patterns);
|
||||
if (modified) {
|
||||
writePageTokens(document, page, tokens);
|
||||
}
|
||||
// Recurse into form XObjects referenced by this page (shared visited set + depth cap).
|
||||
rewriteFormXObjects(resources, resources, patterns, new HashSet<>(), 0);
|
||||
}
|
||||
|
||||
private static void rewriteFormXObjects(
|
||||
PDResources resources,
|
||||
PDResources parentResources,
|
||||
List<Pattern> patterns,
|
||||
Set<COSBase> visited,
|
||||
int depth)
|
||||
throws IOException {
|
||||
if (depth > MAX_XOBJECT_DEPTH) {
|
||||
log.warn("XObject nesting exceeded {}; stopping recursion", MAX_XOBJECT_DEPTH);
|
||||
return;
|
||||
}
|
||||
for (COSName name : resources.getXObjectNames()) {
|
||||
try {
|
||||
var xobj = resources.getXObject(name);
|
||||
if (!(xobj instanceof PDFormXObject form)) {
|
||||
continue;
|
||||
}
|
||||
if (!visited.add(form.getCOSObject())) {
|
||||
continue;
|
||||
}
|
||||
List<Object> tokens = parseTokens(new PDFStreamParser(form));
|
||||
// Forms may inherit fonts from the parent when they carry no own /Resources.
|
||||
PDResources formResources =
|
||||
form.getResources() != null ? form.getResources() : parentResources;
|
||||
boolean modified = rewriteTokens(tokens, formResources, patterns);
|
||||
if (modified) {
|
||||
// A form XObject's content IS its own stream body; overwrite it in place.
|
||||
PDStream formStream = new PDStream(form.getCOSObject());
|
||||
try (var out = formStream.createOutputStream(COSName.FLATE_DECODE)) {
|
||||
new ContentStreamWriter(out).writeTokens(tokens);
|
||||
}
|
||||
}
|
||||
rewriteFormXObjects(formResources, formResources, patterns, visited, depth + 1);
|
||||
} catch (IOException e) {
|
||||
log.debug("Failed to rewrite XObject {}: {}", name.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Object> parseTokens(PDFStreamParser parser) throws IOException {
|
||||
List<Object> tokens = new ArrayList<>();
|
||||
Object t;
|
||||
while ((t = parser.parseNextToken()) != null) {
|
||||
tokens.add(t);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** Walk tokens keeping a tiny text state (current font). */
|
||||
private static boolean rewriteTokens(
|
||||
List<Object> tokens, PDResources resources, List<Pattern> patterns) {
|
||||
boolean modified = false;
|
||||
PDFont currentFont = null;
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
Object tok = tokens.get(i);
|
||||
if (!(tok instanceof Operator op)) {
|
||||
continue;
|
||||
}
|
||||
String name = op.getName();
|
||||
if ("Tf".equals(name) && i >= 2) {
|
||||
Object fontNameTok = tokens.get(i - 2);
|
||||
if (fontNameTok instanceof COSName fontName) {
|
||||
try {
|
||||
currentFont = resources.getFont(fontName);
|
||||
} catch (IOException ex) {
|
||||
log.debug(
|
||||
"Could not resolve font {}: {}",
|
||||
fontName.getName(),
|
||||
ex.getMessage());
|
||||
currentFont = null;
|
||||
}
|
||||
}
|
||||
} else if (RedactionPipeline.TEXT_SHOWING_OPERATORS.contains(name) && i >= 1) {
|
||||
int operandIdx = i - 1;
|
||||
Object operand = tokens.get(operandIdx);
|
||||
if (operand instanceof COSString cosString) {
|
||||
COSString replacement = rewriteCosString(cosString, currentFont, patterns);
|
||||
if (replacement != null) {
|
||||
tokens.set(operandIdx, replacement);
|
||||
modified = true;
|
||||
}
|
||||
} else if (operand instanceof COSArray arr) {
|
||||
COSArray newArr = rewriteCosArray(arr, currentFont, patterns);
|
||||
if (newArr != null) {
|
||||
tokens.set(operandIdx, newArr);
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
private static COSString rewriteCosString(
|
||||
COSString cosString, PDFont font, List<Pattern> patterns) {
|
||||
if (font == null) {
|
||||
// Without a font we cannot decode safely.
|
||||
return rewriteRawLatin(cosString, patterns);
|
||||
}
|
||||
DecodeResult decoded = decodeCosString(cosString, font);
|
||||
if (decoded == null) {
|
||||
return rewriteRawLatin(cosString, patterns);
|
||||
}
|
||||
boolean[] drop = findDroppedCharsMask(decoded.text, patterns);
|
||||
if (drop == null) {
|
||||
return null;
|
||||
}
|
||||
return buildFilteredCosString(decoded, drop, font);
|
||||
}
|
||||
|
||||
private static COSArray rewriteCosArray(COSArray arr, PDFont font, List<Pattern> patterns) {
|
||||
// Build a concatenated decode across all COSString elements so that matches
|
||||
List<DecodeResult> parts = new ArrayList<>();
|
||||
StringBuilder concat = new StringBuilder();
|
||||
for (int i = 0; i < arr.size(); i++) {
|
||||
COSBase elem = arr.get(i);
|
||||
if (elem instanceof COSString cs) {
|
||||
DecodeResult decoded = font != null ? decodeCosString(cs, font) : null;
|
||||
if (decoded == null) {
|
||||
decoded = decodeAsLatin(cs);
|
||||
}
|
||||
parts.add(decoded);
|
||||
concat.append(decoded.text);
|
||||
} else {
|
||||
parts.add(null);
|
||||
}
|
||||
}
|
||||
boolean[] fullDrop = findDroppedCharsMask(concat.toString(), patterns);
|
||||
if (fullDrop == null) {
|
||||
return null;
|
||||
}
|
||||
COSArray out = new COSArray();
|
||||
int cursor = 0;
|
||||
for (int i = 0; i < arr.size(); i++) {
|
||||
COSBase elem = arr.get(i);
|
||||
if (elem instanceof COSString cs) {
|
||||
DecodeResult decoded = parts.get(i);
|
||||
int partLen = decoded.text.length();
|
||||
boolean[] partDrop = new boolean[partLen];
|
||||
System.arraycopy(fullDrop, cursor, partDrop, 0, partLen);
|
||||
cursor += partLen;
|
||||
COSString rebuilt =
|
||||
buildFilteredCosStringRaw(decoded, partDrop, font, cs.getBytes());
|
||||
// A zero-length COSString is valid; PDFBox emits it as () producing no
|
||||
out.add(rebuilt);
|
||||
} else {
|
||||
out.add(elem);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** For cases where we have no font - treat the bytes as latin-1 characters. */
|
||||
private static COSString rewriteRawLatin(COSString cosString, List<Pattern> patterns) {
|
||||
DecodeResult decoded = decodeAsLatin(cosString);
|
||||
boolean[] drop = findDroppedCharsMask(decoded.text, patterns);
|
||||
if (drop == null) {
|
||||
return null;
|
||||
}
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
for (int i = 0; i < decoded.text.length(); i++) {
|
||||
if (drop[i]) continue;
|
||||
out.write(decoded.text.charAt(i) & 0xFF);
|
||||
}
|
||||
return new COSString(out.toByteArray());
|
||||
}
|
||||
|
||||
private static DecodeResult decodeAsLatin(COSString cosString) {
|
||||
byte[] bytes = cosString.getBytes();
|
||||
StringBuilder sb = new StringBuilder(bytes.length);
|
||||
int[] codeStart = new int[bytes.length];
|
||||
int[] codeLen = new int[bytes.length];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
sb.append((char) (bytes[i] & 0xFF));
|
||||
codeStart[i] = i;
|
||||
codeLen[i] = 1;
|
||||
}
|
||||
return new DecodeResult(sb.toString(), bytes, codeStart, codeLen);
|
||||
}
|
||||
|
||||
/** Decode a COSString to Unicode via the font; null if decoding fails. */
|
||||
private static DecodeResult decodeCosString(COSString cosString, PDFont font) {
|
||||
byte[] bytes = cosString.getBytes();
|
||||
StringBuilder text = new StringBuilder();
|
||||
List<Integer> starts = new ArrayList<>();
|
||||
List<Integer> lens = new ArrayList<>();
|
||||
try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
|
||||
int pos = 0;
|
||||
while (in.available() > 0) {
|
||||
int before = in.available();
|
||||
int code;
|
||||
try {
|
||||
code = font.readCode(in);
|
||||
} catch (IOException | RuntimeException ex) {
|
||||
log.debug(
|
||||
"Font {} failed to decode byte sequence: {}",
|
||||
font.getName(),
|
||||
ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
int consumed = before - in.available();
|
||||
String unicode;
|
||||
try {
|
||||
unicode = font.toUnicode(code);
|
||||
} catch (Exception ex) {
|
||||
unicode = null;
|
||||
}
|
||||
if (unicode == null) {
|
||||
// If the font has no ToUnicode mapping we cannot match reliably - return
|
||||
return null;
|
||||
}
|
||||
text.append(unicode);
|
||||
// Associate every Unicode character produced with the same code byte range
|
||||
for (int c = 0; c < unicode.length(); c++) {
|
||||
starts.add(pos);
|
||||
lens.add(consumed);
|
||||
}
|
||||
if (consumed == 0) {
|
||||
// Defensive: avoid infinite loop on malformed fonts.
|
||||
break;
|
||||
}
|
||||
pos += consumed;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
int[] startArr = starts.stream().mapToInt(Integer::intValue).toArray();
|
||||
int[] lenArr = lens.stream().mapToInt(Integer::intValue).toArray();
|
||||
return new DecodeResult(text.toString(), bytes, startArr, lenArr);
|
||||
}
|
||||
|
||||
/** Null if no pattern matches; else a per-char drop mask over the text. */
|
||||
private static boolean[] findDroppedCharsMask(String text, List<Pattern> patterns) {
|
||||
boolean any = false;
|
||||
boolean[] mask = new boolean[text.length()];
|
||||
for (Pattern pattern : patterns) {
|
||||
Matcher m;
|
||||
try {
|
||||
m = pattern.matcher(DeadlineCharSequence.of(text));
|
||||
} catch (Exception ex) {
|
||||
continue;
|
||||
}
|
||||
while (m.find()) {
|
||||
int s = m.start();
|
||||
int e = m.end();
|
||||
if (e <= s) continue;
|
||||
for (int i = s; i < e; i++) {
|
||||
mask[i] = true;
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
return any ? mask : null;
|
||||
}
|
||||
|
||||
private static COSString buildFilteredCosString(
|
||||
DecodeResult decoded, boolean[] drop, PDFont font) {
|
||||
return buildFilteredCosStringRaw(decoded, drop, font, decoded.bytes);
|
||||
}
|
||||
|
||||
private static COSString buildFilteredCosStringRaw(
|
||||
DecodeResult decoded, boolean[] drop, PDFont font, byte[] originalBytes) {
|
||||
// Collect code byte-ranges to drop.
|
||||
Set<Integer> dropStarts = new HashSet<>();
|
||||
for (int i = 0; i < drop.length; i++) {
|
||||
if (drop[i]) {
|
||||
dropStarts.add(decoded.codeStarts[i]);
|
||||
}
|
||||
}
|
||||
// Map byte-start -> code length once (O(n)); findCodeLenAt was an O(n^2) linear scan.
|
||||
Map<Integer, Integer> lenByStart = new HashMap<>();
|
||||
for (int j = 0; j < decoded.codeStarts.length; j++) {
|
||||
lenByStart.putIfAbsent(decoded.codeStarts[j], decoded.codeLens[j]);
|
||||
}
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int i = 0;
|
||||
while (i < originalBytes.length) {
|
||||
int start = i;
|
||||
int len = lenByStart.getOrDefault(start, -1);
|
||||
if (len <= 0) {
|
||||
// Unknown - keep the byte verbatim.
|
||||
out.write(originalBytes[i] & 0xFF);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (dropStarts.contains(start)) {
|
||||
// Replace dropped code with encoded space if possible.
|
||||
byte[] spaceBytes = tryEncodeSpace(font);
|
||||
if (spaceBytes != null) {
|
||||
out.write(spaceBytes, 0, spaceBytes.length);
|
||||
}
|
||||
} else {
|
||||
out.write(originalBytes, start, len);
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
return new COSString(out.toByteArray());
|
||||
}
|
||||
|
||||
private static byte[] tryEncodeSpace(PDFont font) {
|
||||
if (font == null) {
|
||||
return new byte[] {0x20};
|
||||
}
|
||||
try {
|
||||
return font.encode(" ");
|
||||
} catch (Exception e) {
|
||||
// Some fonts cannot encode a space at all (e.g. Type3 throws
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class DecodeResult {
|
||||
final String text;
|
||||
final byte[] bytes;
|
||||
final int[] codeStarts;
|
||||
final int[] codeLens;
|
||||
|
||||
DecodeResult(String text, byte[] bytes, int[] codeStarts, int[] codeLens) {
|
||||
this.text = text;
|
||||
this.bytes = bytes;
|
||||
this.codeStarts = codeStarts;
|
||||
this.codeLens = codeLens;
|
||||
}
|
||||
}
|
||||
|
||||
// Area capture
|
||||
|
||||
static List<String> captureTextInRects(PDPage page, List<PDRectangle> rects)
|
||||
throws IOException {
|
||||
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
|
||||
stripper.setSortByPosition(true);
|
||||
for (int i = 0; i < rects.size(); i++) {
|
||||
PDRectangle rect = rects.get(i);
|
||||
// PDFTextStripperByArea uses a Java2D rectangle in the same coordinate
|
||||
float pdfY = page.getBBox().getHeight() - rect.getUpperRightY();
|
||||
Rectangle2D.Float region =
|
||||
new Rectangle2D.Float(
|
||||
rect.getLowerLeftX(), pdfY, rect.getWidth(), rect.getHeight());
|
||||
stripper.addRegion("r" + i, region);
|
||||
}
|
||||
try {
|
||||
stripper.extractRegions(page);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to extract text in rects: {}", e.getMessage());
|
||||
return Collections.emptyList();
|
||||
}
|
||||
Set<String> captured = new LinkedHashSet<>();
|
||||
for (int i = 0; i < rects.size(); i++) {
|
||||
String text = stripper.getTextForRegion("r" + i);
|
||||
if (text == null) {
|
||||
continue;
|
||||
}
|
||||
for (String token : text.split("\\s+")) {
|
||||
String trimmed = token.trim();
|
||||
if (!trimmed.isEmpty()) {
|
||||
captured.add(trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(captured);
|
||||
}
|
||||
|
||||
// Content-stream rewriting (rect-driven glyph removal)
|
||||
|
||||
/**
|
||||
* Blanks show-text operands whose glyphs fall in a rect. Returns false (surgical removal is
|
||||
* unreliable, caller must rasterise) when text-bearing form XObjects skew the operator ordinals
|
||||
* or an image sits under a rect - leaving the page stream untouched so the raster is correct.
|
||||
*/
|
||||
static boolean removeTokensIntersectingRects(
|
||||
PDDocument document, PDPage page, List<PDRectangle> rects) throws IOException {
|
||||
|
||||
List<Rectangle2D.Float> areaRects = new ArrayList<>();
|
||||
for (PDRectangle rect : rects) {
|
||||
float pdfY = page.getBBox().getHeight() - rect.getUpperRightY();
|
||||
areaRects.add(
|
||||
new Rectangle2D.Float(
|
||||
rect.getLowerLeftX(), pdfY, rect.getWidth(), rect.getHeight()));
|
||||
}
|
||||
|
||||
int pageIndex = document.getPages().indexOf(page);
|
||||
TokenIndexCollector collector = new TokenIndexCollector(areaRects);
|
||||
collector.setStartPage(pageIndex + 1);
|
||||
collector.setEndPage(pageIndex + 1);
|
||||
collector.getText(document);
|
||||
int collectorTextOps = collector.totalTextOps();
|
||||
|
||||
List<Object> tokens = parseTokens(new PDFStreamParser(page));
|
||||
int pageTextOps = 0;
|
||||
for (Object t : tokens) {
|
||||
if (t instanceof Operator op
|
||||
&& RedactionPipeline.TEXT_SHOWING_OPERATORS.contains(op.getName())) {
|
||||
pageTextOps++;
|
||||
}
|
||||
}
|
||||
// Collector ordinals span form XObjects; images under a rect can't be surgically removed.
|
||||
if (collectorTextOps != pageTextOps || imageIntersectsAnyRect(page, pageIndex, rects)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Drop ONLY the in-rect glyphs of each operand (not the whole run), tracking the active
|
||||
// font so codes decode. Bail to rasterise if the font can't decode or glyph!=code counts.
|
||||
PDResources resources = page.getResources();
|
||||
PDFont currentFont = null;
|
||||
int opCounter = -1;
|
||||
boolean modified = false;
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
Object tok = tokens.get(i);
|
||||
if (!(tok instanceof Operator op)) {
|
||||
continue;
|
||||
}
|
||||
String name = op.getName();
|
||||
if ("Tf".equals(name) && i >= 2 && tokens.get(i - 2) instanceof COSName fn) {
|
||||
try {
|
||||
currentFont = resources != null ? resources.getFont(fn) : null;
|
||||
} catch (IOException e) {
|
||||
currentFont = null;
|
||||
}
|
||||
} else if (RedactionPipeline.TEXT_SHOWING_OPERATORS.contains(name)) {
|
||||
opCounter++;
|
||||
Set<Integer> dropGlyphs = collector.dropGlyphsByOp.get(opCounter);
|
||||
if (dropGlyphs == null || dropGlyphs.isEmpty() || i < 1) {
|
||||
continue;
|
||||
}
|
||||
// ' and " also move to the next line; converting them to TJ would lose that -
|
||||
// raster.
|
||||
if ("'".equals(name) || "\"".equals(name)) {
|
||||
return false;
|
||||
}
|
||||
int expected = collector.glyphCountByOp.getOrDefault(opCounter, -1);
|
||||
COSArray rebuilt =
|
||||
rebuildAdvancePreserving(
|
||||
tokens.get(i - 1), currentFont, dropGlyphs, expected);
|
||||
if (rebuilt == null) {
|
||||
return false; // undecodable / glyph-count mismatch - rasterise instead
|
||||
}
|
||||
// Emit as TJ so the removed glyphs' advance is preserved (no reflow).
|
||||
tokens.set(i - 1, rebuilt);
|
||||
tokens.set(i, Operator.getOperator("TJ"));
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (modified) {
|
||||
writePageTokens(document, page, tokens);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Distinct code byte-starts in order (one per glyph/code) from a per-char DecodeResult. */
|
||||
private static int[] distinctCodeStarts(DecodeResult d) {
|
||||
List<Integer> starts = new ArrayList<>();
|
||||
int last = -1;
|
||||
for (int s : d.codeStarts) {
|
||||
if (s != last) {
|
||||
starts.add(s);
|
||||
last = s;
|
||||
}
|
||||
}
|
||||
return starts.stream().mapToInt(Integer::intValue).toArray();
|
||||
}
|
||||
|
||||
private static int codeAt(PDFont font, byte[] bytes, int start, int len) throws IOException {
|
||||
try (ByteArrayInputStream in = new ByteArrayInputStream(bytes, start, len)) {
|
||||
return font.readCode(in);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild a Tj/TJ operand as a TJ array that keeps every glyph EXCEPT the given 0-based
|
||||
* indexes, replacing each dropped run with a numeric adjustment equal to its advance so the
|
||||
* surviving text does not reflow into (or out of) the box. Returns null (caller rasterises) if
|
||||
* anything can't be decoded or the glyph count doesn't line up with the position pass.
|
||||
*/
|
||||
private static COSArray rebuildAdvancePreserving(
|
||||
Object operand, PDFont font, Set<Integer> dropGlyphs, int expectedGlyphs) {
|
||||
if (font == null) {
|
||||
return null;
|
||||
}
|
||||
List<COSBase> elements = new ArrayList<>();
|
||||
if (operand instanceof COSString cs) {
|
||||
elements.add(cs);
|
||||
} else if (operand instanceof COSArray arr) {
|
||||
for (COSBase b : arr) {
|
||||
elements.add(b);
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
COSArray out = new COSArray();
|
||||
ByteArrayOutputStream seg = new ByteArrayOutputStream();
|
||||
float pendingAdvance = 0f; // accumulated width of dropped codes, in 1/1000 text units
|
||||
int globalCode = 0;
|
||||
for (COSBase el : elements) {
|
||||
if (!(el instanceof COSString s)) {
|
||||
// Existing numeric adjustment: flush whichever run is pending, then preserve it.
|
||||
if (seg.size() > 0) {
|
||||
out.add(new COSString(seg.toByteArray()));
|
||||
seg.reset();
|
||||
} else if (pendingAdvance != 0f) {
|
||||
out.add(new COSFloat(-pendingAdvance));
|
||||
pendingAdvance = 0f;
|
||||
}
|
||||
out.add(el);
|
||||
continue;
|
||||
}
|
||||
DecodeResult d = decodeCosString(s, font);
|
||||
if (d == null) {
|
||||
return null;
|
||||
}
|
||||
byte[] b = s.getBytes();
|
||||
int[] starts = distinctCodeStarts(d);
|
||||
Map<Integer, Integer> lenByStart = new HashMap<>();
|
||||
for (int j = 0; j < d.codeStarts.length; j++) {
|
||||
lenByStart.putIfAbsent(d.codeStarts[j], d.codeLens[j]);
|
||||
}
|
||||
for (int k = 0; k < starts.length; k++) {
|
||||
int bs = starts[k];
|
||||
int len = lenByStart.getOrDefault(bs, -1);
|
||||
if (len <= 0) {
|
||||
return null;
|
||||
}
|
||||
if (dropGlyphs.contains(globalCode)) {
|
||||
if (seg.size() > 0) { // close the kept run before accumulating advance
|
||||
out.add(new COSString(seg.toByteArray()));
|
||||
seg.reset();
|
||||
}
|
||||
try {
|
||||
pendingAdvance += font.getWidth(codeAt(font, b, bs, len));
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
if (pendingAdvance != 0f) { // emit the removed run's advance, then keep glyphs
|
||||
out.add(new COSFloat(-pendingAdvance));
|
||||
pendingAdvance = 0f;
|
||||
}
|
||||
seg.write(b, bs, len);
|
||||
}
|
||||
globalCode++;
|
||||
}
|
||||
}
|
||||
if (pendingAdvance != 0f) {
|
||||
out.add(new COSFloat(-pendingAdvance));
|
||||
}
|
||||
if (seg.size() > 0) {
|
||||
out.add(new COSString(seg.toByteArray()));
|
||||
}
|
||||
if (expectedGlyphs >= 0 && globalCode != expectedGlyphs) {
|
||||
return null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any image on the page overlaps a redaction rect (would survive under the overlay).
|
||||
*/
|
||||
private static boolean imageIntersectsAnyRect(
|
||||
PDPage page, int pageIndex, List<PDRectangle> rects) {
|
||||
try {
|
||||
PageImageLocator locator = new PageImageLocator(page, pageIndex);
|
||||
locator.processPage(page);
|
||||
for (PageImageLocator.ImageBox ib : locator.getImageBoxes()) {
|
||||
Rectangle2D.Float img =
|
||||
new Rectangle2D.Float(
|
||||
ib.x1(), ib.y1(), ib.x2() - ib.x1(), ib.y2() - ib.y1());
|
||||
for (PDRectangle rect : rects) {
|
||||
if (img.intersects(
|
||||
rect.getLowerLeftX(),
|
||||
rect.getLowerLeftY(),
|
||||
rect.getWidth(),
|
||||
rect.getHeight())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
// Cannot prove no image sits under a box - treat as unsafe (force raster).
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void writePageTokens(PDDocument document, PDPage page, List<Object> tokens)
|
||||
throws IOException {
|
||||
PDStream stream = new PDStream(document);
|
||||
try (var out = stream.createOutputStream(COSName.FLATE_DECODE)) {
|
||||
ContentStreamWriter writer = new ContentStreamWriter(out);
|
||||
writer.writeTokens(tokens);
|
||||
}
|
||||
page.setContents(stream);
|
||||
}
|
||||
|
||||
static void drawOverlay(
|
||||
PDDocument document, PDPage page, List<PDRectangle> rects, Color overlayColor)
|
||||
throws IOException {
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||
cs.saveGraphicsState();
|
||||
cs.setNonStrokingColor(overlayColor);
|
||||
for (PDRectangle rect : rects) {
|
||||
cs.addRect(
|
||||
rect.getLowerLeftX(),
|
||||
rect.getLowerLeftY(),
|
||||
rect.getWidth(),
|
||||
rect.getHeight());
|
||||
}
|
||||
cs.fill();
|
||||
cs.restoreGraphicsState();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,301 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.SPDF.utils.text.TextFinderUtils;
|
||||
import stirling.software.common.util.RegexPatternUtils;
|
||||
|
||||
/**
|
||||
* Public facade for the manual-area, whole-page and auto-word redaction paths. Orchestrates the
|
||||
* collaborators that do the work: {@link RedactionContentEditor} (content-stream glyph removal),
|
||||
* {@link RedactionVerifier} (fail-closed independent verification) and {@link RedactionRasteriser}
|
||||
* (last-resort rasterisation), with {@link CatalogScrubber} for out-of-page carriers.
|
||||
*/
|
||||
@Slf4j
|
||||
public final class RedactionPipeline {
|
||||
|
||||
public static final Set<String> TEXT_SHOWING_OPERATORS = Set.of("Tj", "TJ", "'", "\"");
|
||||
|
||||
private RedactionPipeline() {}
|
||||
|
||||
/** Test hook to simulate the native binding being unavailable (drives the fail-closed path). */
|
||||
static void setJpdfiumAvailableForTest(boolean available) {
|
||||
RedactionVerifier.setJpdfiumAvailableForTest(available);
|
||||
}
|
||||
|
||||
/** Redact page-local rects (PDF user-space), dropping intersecting glyphs + overlay. */
|
||||
public static RedactionResult redactAreas(
|
||||
PDDocument document,
|
||||
Map<Integer, List<PDRectangle>> rectsByPageIndex,
|
||||
Color overlayColor)
|
||||
throws IOException {
|
||||
|
||||
Set<String> capturedStrings = new LinkedHashSet<>();
|
||||
Set<Integer> forceRasterPages = new LinkedHashSet<>();
|
||||
|
||||
for (Map.Entry<Integer, List<PDRectangle>> entry : rectsByPageIndex.entrySet()) {
|
||||
int pageIndex = entry.getKey();
|
||||
List<PDRectangle> rects = entry.getValue();
|
||||
if (pageIndex < 0 || pageIndex >= document.getNumberOfPages() || rects.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
PDPage page = document.getPage(pageIndex);
|
||||
capturedStrings.addAll(RedactionContentEditor.captureTextInRects(page, rects));
|
||||
|
||||
// Rotation / non-zero CropBox origin break the coordinate flip, and text-bearing forms
|
||||
// or in-rect images defeat page-stream ordinal removal.
|
||||
boolean surgical =
|
||||
RedactionContentEditor.isSurgicallySafe(page)
|
||||
&& RedactionContentEditor.removeTokensIntersectingRects(
|
||||
document, page, rects);
|
||||
if (!surgical) {
|
||||
forceRasterPages.add(pageIndex);
|
||||
}
|
||||
RedactionContentEditor.removeOverlappingAnnotations(page, rects);
|
||||
RedactionContentEditor.drawOverlay(document, page, rects, overlayColor);
|
||||
}
|
||||
|
||||
return new RedactionResult(capturedStrings, forceRasterPages);
|
||||
}
|
||||
|
||||
/** Wipe whole pages: drop all content/resources, fill with a rectangle. */
|
||||
public static void redactWholePages(
|
||||
PDDocument document, List<Integer> pageIndexes, Color overlayColor) throws IOException {
|
||||
for (Integer pageIndex : pageIndexes) {
|
||||
if (pageIndex == null || pageIndex < 0 || pageIndex >= document.getNumberOfPages()) {
|
||||
continue;
|
||||
}
|
||||
PDPage page = document.getPage(pageIndex);
|
||||
PDRectangle media = page.getMediaBox();
|
||||
|
||||
// Drop existing content streams and page resources outright.
|
||||
page.getCOSObject().removeItem(COSName.CONTENTS);
|
||||
page.setResources(new PDResources());
|
||||
page.getCOSObject().removeItem(COSName.ANNOTS);
|
||||
// /Thumb is a rendered image of the original page - drop it too.
|
||||
page.getCOSObject().removeItem(COSName.getPDFName("Thumb"));
|
||||
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.OVERWRITE, true, true)) {
|
||||
cs.setNonStrokingColor(overlayColor);
|
||||
cs.addRect(
|
||||
media.getLowerLeftX(),
|
||||
media.getLowerLeftY(),
|
||||
media.getWidth(),
|
||||
media.getHeight());
|
||||
cs.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Physically remove every literal/regex match from all page content streams. */
|
||||
public static void redactLiteralTerms(
|
||||
PDDocument document, Set<String> literalTargets, List<Pattern> patterns)
|
||||
throws IOException {
|
||||
List<Pattern> effectivePatterns =
|
||||
RedactionContentEditor.effectivePatterns(literalTargets, patterns);
|
||||
if (effectivePatterns.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
int pageIndex = 0;
|
||||
for (PDPage page : document.getPages()) {
|
||||
try {
|
||||
RedactionContentEditor.rewritePageContent(document, page, effectivePatterns);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
// Never let one page's font quirk (e.g. Type3 encode, damaged program)
|
||||
log.warn(
|
||||
"Content-stream rewrite failed on page {} ({}); leaving it for the "
|
||||
+ "verification/rasterisation pass.",
|
||||
pageIndex + 1,
|
||||
e.toString());
|
||||
}
|
||||
pageIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
/** Finalize with document-wide verification: scrub, wipe metadata, save, verify. */
|
||||
public static byte[] finalize(
|
||||
PDDocument document, Set<String> literalTargets, List<Pattern> patterns)
|
||||
throws IOException {
|
||||
return finalize(document, literalTargets, patterns, null);
|
||||
}
|
||||
|
||||
/** Finalize with verification scoped to a specific set of page indexes. */
|
||||
public static byte[] finalize(
|
||||
PDDocument document,
|
||||
Set<String> literalTargets,
|
||||
List<Pattern> patterns,
|
||||
Set<Integer> affectedPages)
|
||||
throws IOException {
|
||||
|
||||
CatalogScrubber.scrub(document, literalTargets, patterns);
|
||||
RedactionVerifier.warnAboutEmbeddedFontGlyphs(document);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
document.save(baos);
|
||||
byte[] bytes = baos.toByteArray();
|
||||
|
||||
try {
|
||||
RedactionVerifier.verify(bytes, literalTargets, patterns, affectedPages);
|
||||
return bytes;
|
||||
} catch (RedactionVerificationFailedException primaryFailure) {
|
||||
// Rewriter could not guarantee removal; rasterise as a last resort.
|
||||
log.warn(
|
||||
"Primary redaction verification failed ({}); falling back to page-scoped "
|
||||
+ "rasterisation to guarantee removal.",
|
||||
primaryFailure.getMessage());
|
||||
// With no page scope (auto-word), rasterise only the pages that still leak.
|
||||
Set<Integer> pagesToRaster =
|
||||
(affectedPages == null || affectedPages.isEmpty())
|
||||
? RedactionVerifier.findLeakingPages(bytes, literalTargets, patterns)
|
||||
: new HashSet<>(affectedPages);
|
||||
try (PDDocument rasterised = RedactionRasteriser.rasterisePages(bytes, pagesToRaster)) {
|
||||
CatalogScrubber.scrub(rasterised, literalTargets, patterns);
|
||||
ByteArrayOutputStream rasterOut = new ByteArrayOutputStream();
|
||||
rasterised.save(rasterOut);
|
||||
byte[] rasterBytes = rasterOut.toByteArray();
|
||||
RedactionVerifier.verify(rasterBytes, literalTargets, patterns, affectedPages);
|
||||
return rasterBytes;
|
||||
} catch (IOException e) {
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Rasterisation fallback failed after primary redaction leak", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Finalize a manual area redaction; rasterises forced + verified-leaking pages. */
|
||||
public static byte[] finalizeAreas(
|
||||
PDDocument document,
|
||||
Map<Integer, List<PDRectangle>> rectsByPage,
|
||||
Set<Integer> forceRasterPages,
|
||||
Set<String> capturedTargets)
|
||||
throws IOException {
|
||||
|
||||
// Text captured under the rects may also live in a bookmark / form value / annotation / JS
|
||||
// carrier.
|
||||
Set<String> carrierTargets =
|
||||
capturedTargets == null ? Collections.emptySet() : capturedTargets;
|
||||
CatalogScrubber.scrub(document, carrierTargets, Collections.emptyList());
|
||||
RedactionVerifier.warnAboutEmbeddedFontGlyphs(document);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
document.save(baos);
|
||||
byte[] bytes = baos.toByteArray();
|
||||
|
||||
Set<Integer> toRaster =
|
||||
new HashSet<>(forceRasterPages == null ? Set.of() : forceRasterPages);
|
||||
toRaster.addAll(RedactionVerifier.findLeakingRectPages(bytes, rectsByPage));
|
||||
if (toRaster.isEmpty()) {
|
||||
return bytes;
|
||||
}
|
||||
log.warn("Manual redaction rasterising page(s) {} to guarantee removal", toRaster);
|
||||
try (PDDocument rasterised = RedactionRasteriser.rasterisePages(bytes, toRaster)) {
|
||||
ByteArrayOutputStream rasterOut = new ByteArrayOutputStream();
|
||||
rasterised.save(rasterOut);
|
||||
return rasterOut.toByteArray();
|
||||
} catch (IOException e) {
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Rasterisation fallback failed after manual redaction leak", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rasterise the given pages of already-finalized bytes to guarantee removal of geometric (range
|
||||
* / image-box) redactions whose covered content - text under an overlay, or an image - is not
|
||||
* removed by content-stream text redaction. Scrubs carriers and re-saves.
|
||||
*/
|
||||
public static byte[] rasteriseSpecificPages(
|
||||
byte[] bytes, Set<Integer> pages, Set<String> literalTargets, List<Pattern> patterns)
|
||||
throws IOException {
|
||||
if (pages == null || pages.isEmpty()) {
|
||||
return bytes;
|
||||
}
|
||||
log.warn("Rasterising page(s) {} to guarantee geometric redaction removal", pages);
|
||||
try (PDDocument rasterised =
|
||||
RedactionRasteriser.rasterisePages(bytes, new HashSet<>(pages))) {
|
||||
CatalogScrubber.scrub(rasterised, literalTargets, patterns);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
rasterised.save(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
/** Build case-insensitive regex patterns from user input. */
|
||||
public static List<Pattern> buildPatterns(
|
||||
String[] rawEntries, boolean useRegex, boolean wholeWordSearch) {
|
||||
List<Pattern> patterns = new ArrayList<>();
|
||||
if (rawEntries == null) {
|
||||
return patterns;
|
||||
}
|
||||
for (String raw : rawEntries) {
|
||||
if (raw == null) {
|
||||
continue;
|
||||
}
|
||||
String trimmed = raw.trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
String core = useRegex ? trimmed : Pattern.quote(trimmed);
|
||||
if (wholeWordSearch) {
|
||||
// Shared with the finder so removal + verification use identical boundaries.
|
||||
core = TextFinderUtils.applyWordBoundaries(trimmed, core);
|
||||
}
|
||||
// Compile via the shared cache (same path as the finder) for consistent
|
||||
// handling of user-supplied regex; ReDoS is bounded by DeadlineCharSequence.
|
||||
patterns.add(RegexPatternUtils.getInstance().createSearchPattern(core, true));
|
||||
} catch (PatternSyntaxException e) {
|
||||
log.debug("Skipping invalid regex '{}': {}", trimmed, e.getMessage());
|
||||
}
|
||||
}
|
||||
return patterns;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any font is not provably reliable for PDFBox glyph extraction (delegates to {@link
|
||||
* RedactionVerifier}); exposed here for the pipeline's callers and tests.
|
||||
*/
|
||||
static boolean documentHasUnreliableFont(PDDocument document) {
|
||||
return RedactionVerifier.documentHasUnreliableFont(document);
|
||||
}
|
||||
|
||||
/** Captured strings plus pages that must be rasterised (surgical removal was unreliable). */
|
||||
public static final class RedactionResult {
|
||||
private final Set<String> capturedStrings;
|
||||
private final Set<Integer> forceRasterPages;
|
||||
|
||||
public RedactionResult(Set<String> capturedStrings, Set<Integer> forceRasterPages) {
|
||||
this.capturedStrings = capturedStrings == null ? Set.of() : capturedStrings;
|
||||
this.forceRasterPages = forceRasterPages == null ? Set.of() : forceRasterPages;
|
||||
}
|
||||
|
||||
public Set<String> getCapturedStrings() {
|
||||
return capturedStrings;
|
||||
}
|
||||
|
||||
public Set<Integer> getForceRasterPages() {
|
||||
return forceRasterPages;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
||||
import org.apache.pdfbox.rendering.ImageType;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/** Rasterisation fallback: renders whole pages to an image so no text/vector content survives. */
|
||||
@Slf4j
|
||||
final class RedactionRasteriser {
|
||||
|
||||
private RedactionRasteriser() {}
|
||||
|
||||
/** Rasterise the listed pages (all when null) at 150 DPI, replacing their content. */
|
||||
static PDDocument rasterisePages(byte[] sourceBytes, Set<Integer> pagesToRaster)
|
||||
throws IOException {
|
||||
// Load the document directly and mutate in place: rewriting
|
||||
PDDocument source = Loader.loadPDF(sourceBytes);
|
||||
try {
|
||||
PDFRenderer renderer = new PDFRenderer(source);
|
||||
int pageCount = source.getNumberOfPages();
|
||||
for (int i = 0; i < pageCount; i++) {
|
||||
if (pagesToRaster != null && !pagesToRaster.contains(i)) {
|
||||
continue;
|
||||
}
|
||||
PDPage page = source.getPage(i);
|
||||
// PDFRenderer renders the CropBox region, so draw the raster over the CropBox (not
|
||||
// the MediaBox) or a CropBox != MediaBox page is stretched/offset.
|
||||
PDRectangle crop = page.getCropBox();
|
||||
|
||||
BufferedImage img = renderer.renderImageWithDPI(i, 150, ImageType.RGB);
|
||||
ByteArrayOutputStream imgOut = new ByteArrayOutputStream();
|
||||
ImageIO.write(img, "png", imgOut);
|
||||
PDImageXObject imageXObject =
|
||||
PDImageXObject.createFromByteArray(
|
||||
source, imgOut.toByteArray(), "redacted-page-" + i);
|
||||
|
||||
// Drop all prior content / resources / annotations / thumbnail; the raster is the
|
||||
// page.
|
||||
page.getCOSObject().removeItem(COSName.CONTENTS);
|
||||
page.setResources(new PDResources());
|
||||
page.getCOSObject().removeItem(COSName.ANNOTS);
|
||||
page.getCOSObject().removeItem(COSName.getPDFName("Thumb"));
|
||||
// Rotation is already baked into the rendered image, so reset it to zero.
|
||||
page.setRotation(0);
|
||||
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
source,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.OVERWRITE,
|
||||
false,
|
||||
true)) {
|
||||
// The rendered image already has the rotation baked in visually
|
||||
cs.drawImage(
|
||||
imageXObject,
|
||||
crop.getLowerLeftX(),
|
||||
crop.getLowerLeftY(),
|
||||
crop.getWidth(),
|
||||
crop.getHeight());
|
||||
}
|
||||
}
|
||||
return source;
|
||||
} catch (IOException | RuntimeException e) {
|
||||
source.close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
/** Thrown when post-redaction verification still finds a target in the saved PDF. */
|
||||
public class RedactionVerificationFailedException extends RuntimeException {
|
||||
|
||||
public RedactionVerificationFailedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public RedactionVerificationFailedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -1,495 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.cos.COSBase;
|
||||
import org.apache.pdfbox.cos.COSDictionary;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType0Font;
|
||||
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.jpdfium.PdfDocument;
|
||||
import stirling.software.jpdfium.text.PdfTextExtractor;
|
||||
|
||||
/**
|
||||
* Independent, fail-closed verification that redacted text is truly gone: an /ActualText-blind
|
||||
* PDFBox pass plus an additive native (PDFium) pass for fonts PDFBox cannot reliably extract, with
|
||||
* per-page leak localisation for the rasterisation fallback.
|
||||
*/
|
||||
@Slf4j
|
||||
final class RedactionVerifier {
|
||||
|
||||
private static final int MAX_XOBJECT_DEPTH = 10;
|
||||
|
||||
// Latched false when the native PDFium binding can't load, so the host falls back to the PDFBox
|
||||
// pass.
|
||||
private static volatile boolean jpdfiumAvailable = true;
|
||||
|
||||
// Skip the additive native pass above this size to bound off-heap copy + native runtime on
|
||||
// adversarial inputs; the PDFBox glyph-blind pass still verifies.
|
||||
private static final long MAX_JPDFIUM_VERIFY_BYTES = 100L * 1024 * 1024;
|
||||
|
||||
private RedactionVerifier() {}
|
||||
|
||||
/** Test hook to simulate the native binding being unavailable (drives the fail-closed path). */
|
||||
static void setJpdfiumAvailableForTest(boolean available) {
|
||||
jpdfiumAvailable = available;
|
||||
}
|
||||
|
||||
/** Warns when the document still carries embedded Type0/TrueType font */
|
||||
static void warnAboutEmbeddedFontGlyphs(PDDocument document) {
|
||||
boolean anyEmbedded = false;
|
||||
Set<PDFont> visited = new HashSet<>();
|
||||
for (PDPage page : document.getPages()) {
|
||||
PDResources resources = page.getResources();
|
||||
if (resources == null) {
|
||||
continue;
|
||||
}
|
||||
for (COSName name : resources.getFontNames()) {
|
||||
PDFont font;
|
||||
try {
|
||||
font = resources.getFont(name);
|
||||
} catch (IOException ioe) {
|
||||
continue;
|
||||
}
|
||||
if (font == null || !visited.add(font)) {
|
||||
continue;
|
||||
}
|
||||
if (font instanceof PDType0Font || font instanceof PDTrueTypeFont) {
|
||||
anyEmbedded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (anyEmbedded) {
|
||||
log.warn(
|
||||
"Redacted document contains embedded Type0/TrueType fonts; glyph outlines for "
|
||||
+ "redacted characters may remain in the font program. Text is not "
|
||||
+ "extractable via content-stream reading, but raw font inspection can "
|
||||
+ "still recover glyph shapes. Use the convert-to-image fallback for "
|
||||
+ "maximum assurance.");
|
||||
}
|
||||
}
|
||||
|
||||
static void verify(
|
||||
byte[] bytes,
|
||||
Set<String> literalTargets,
|
||||
List<Pattern> patterns,
|
||||
Set<Integer> affectedPages) {
|
||||
if ((literalTargets == null || literalTargets.isEmpty())
|
||||
&& (patterns == null || patterns.isEmpty())) {
|
||||
return;
|
||||
}
|
||||
Set<Integer> pageSet =
|
||||
(affectedPages == null || affectedPages.isEmpty())
|
||||
? null
|
||||
: new TreeSet<>(affectedPages);
|
||||
// PDFBox pass, blind to /ActualText so a benign override can't mask real glyphs.
|
||||
boolean needNativePass;
|
||||
try (PDDocument reopened = Loader.loadPDF(bytes)) {
|
||||
assertNoTarget(extractText(reopened, pageSet), literalTargets, patterns);
|
||||
needNativePass = documentHasUnreliableFont(reopened);
|
||||
} catch (IOException e) {
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Failed to reopen redacted PDF for verification", e);
|
||||
}
|
||||
// Additive producer-independent pass: native PDFium sees glyphs PDFBox may miss (fonts with
|
||||
// no ToUnicode).
|
||||
if (needNativePass) {
|
||||
String nativeText = extractTextJPDFium(bytes, pageSet);
|
||||
if (nativeText == null) {
|
||||
// Required independent pass could not run (native unavailable or doc over the size
|
||||
// guard); fail closed.
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Independent native verification could not run for a document whose fonts "
|
||||
+ "PDFBox cannot reliably extract; cannot confirm removal");
|
||||
}
|
||||
assertNoTarget(nativeText, literalTargets, patterns);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any font (on any page or nested form XObject) is not provably reliable for PDFBox
|
||||
* glyph extraction - i.e. it is neither a built-in Standard-14 font nor carries a /ToUnicode
|
||||
* map. These are exactly the fonts (CID/Type3/symbolic without ToUnicode) where the PDFBox pass
|
||||
* can go blind, so the independent native pass earns its cost. Biased to {@code true} on any
|
||||
* inspection failure so the native pass runs whenever reliability is uncertain.
|
||||
*/
|
||||
static boolean documentHasUnreliableFont(PDDocument document) {
|
||||
try {
|
||||
Set<COSBase> visited = new HashSet<>();
|
||||
for (PDPage page : document.getPages()) {
|
||||
if (resourcesHaveUnreliableFont(page.getResources(), visited, 0)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (RuntimeException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean resourcesHaveUnreliableFont(
|
||||
PDResources res, Set<COSBase> visited, int depth) {
|
||||
if (res == null) {
|
||||
return false;
|
||||
}
|
||||
if (depth > MAX_XOBJECT_DEPTH) {
|
||||
return true; // too deeply nested to fully verify - run the native pass to be safe
|
||||
}
|
||||
if (!visited.add(res.getCOSObject())) {
|
||||
return false; // already inspected this resource dictionary
|
||||
}
|
||||
for (COSName name : res.getFontNames()) {
|
||||
PDFont font;
|
||||
try {
|
||||
font = res.getFont(name);
|
||||
} catch (Exception e) {
|
||||
return true; // font won't load for inspection - assume unreliable
|
||||
}
|
||||
// Reliable only for built-in Standard-14 fonts or a /ToUnicode map we can trust.
|
||||
if (font != null
|
||||
&& !font.isStandard14()
|
||||
&& (!font.getCOSObject().containsKey(COSName.TO_UNICODE)
|
||||
|| isSubsetFont(font))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (COSName name : res.getXObjectNames()) {
|
||||
try {
|
||||
if (res.getXObject(name) instanceof PDFormXObject form
|
||||
&& resourcesHaveUnreliableFont(form.getResources(), visited, depth + 1)) {
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return true; // can't inspect the XObject - assume unreliable
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A subset-embedded font carries a 6-uppercase-letter '+' BaseFont tag (e.g. {@code ABCDEF+}).
|
||||
* Its /ToUnicode is custom-built and cannot be trusted for the reliability gate: a partial map
|
||||
* silently loses text, and a crafted map can defeat text-based redaction entirely (only
|
||||
* convert-to-image fully mitigates that adversarial case).
|
||||
*/
|
||||
private static boolean isSubsetFont(PDFont font) {
|
||||
String name = font.getName();
|
||||
if (name == null || name.length() < 8 || name.charAt(6) != '+') {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < 6; i++) {
|
||||
char c = name.charAt(i);
|
||||
if (c < 'A' || c > 'Z') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Fail-closed match check with whitespace-normalised literals and X2 regex semantics. */
|
||||
private static void assertNoTarget(
|
||||
String extracted, Set<String> literalTargets, List<Pattern> patterns) {
|
||||
if (extracted == null) {
|
||||
return;
|
||||
}
|
||||
String normalised = extracted.toLowerCase(Locale.ROOT).replaceAll("\\s+", " ");
|
||||
// De-hyphenated view catches a target split by a soft hyphen (U+00AD) or a line-break
|
||||
// hyphen ("-" + space).
|
||||
String dehyphenated = normalised.replace("\u00ad", "").replaceAll("-\\s+", "");
|
||||
if (literalTargets != null) {
|
||||
for (String target : literalTargets) {
|
||||
if (target == null || target.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String needle = target.toLowerCase(Locale.ROOT).replaceAll("\\s+", " ");
|
||||
if (normalised.contains(needle) || dehyphenated.contains(needle)) {
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Redacted text still extractable: '" + target + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (patterns != null) {
|
||||
for (Pattern pattern : patterns) {
|
||||
try {
|
||||
if (pattern.matcher(DeadlineCharSequence.of(extracted)).find()) {
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Redacted pattern still extractable: " + pattern.pattern());
|
||||
}
|
||||
} catch (RedactionVerificationFailedException rvf) {
|
||||
throw rvf;
|
||||
} catch (RuntimeException | StackOverflowError e) {
|
||||
throw new RedactionVerificationFailedException(
|
||||
"Verification regex failed ("
|
||||
+ pattern.pattern()
|
||||
+ "): "
|
||||
+ e.getMessage(),
|
||||
e instanceof Exception ? (Exception) e : new Exception(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Extract text from pageIndexes (0-based) using an /ActualText-blind stripper. */
|
||||
private static String extractText(PDDocument document, Set<Integer> pageIndexes)
|
||||
throws IOException {
|
||||
PDFTextStripper stripper = new GlyphOnlyTextStripper();
|
||||
if (pageIndexes == null) {
|
||||
return stripper.getText(document);
|
||||
}
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (Integer pageIdx : pageIndexes) {
|
||||
if (pageIdx == null || pageIdx < 0 || pageIdx >= document.getNumberOfPages()) {
|
||||
continue;
|
||||
}
|
||||
stripper.setStartPage(pageIdx + 1);
|
||||
stripper.setEndPage(pageIdx + 1);
|
||||
String pageText = stripper.getText(document);
|
||||
if (pageText != null) {
|
||||
out.append(pageText);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Independent native (PDFium) extraction; null if the binding is unavailable (additive only).
|
||||
*/
|
||||
private static String extractTextJPDFium(byte[] bytes, Set<Integer> pageIndexes) {
|
||||
if (!jpdfiumAvailable || bytes.length > MAX_JPDFIUM_VERIFY_BYTES) {
|
||||
return null;
|
||||
}
|
||||
try (PdfDocument doc = PdfDocument.open(bytes)) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int n = doc.pageCount();
|
||||
if (pageIndexes == null) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
sb.append(jpdfiumPlainText(doc, i)).append('\n');
|
||||
}
|
||||
} else {
|
||||
for (Integer p : pageIndexes) {
|
||||
if (p != null && p >= 0 && p < n) {
|
||||
sb.append(jpdfiumPlainText(doc, p)).append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (RuntimeException | Error e) {
|
||||
onJpdfiumFailure(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String jpdfiumPlainText(PdfDocument doc, int i) {
|
||||
try {
|
||||
return PdfTextExtractor.extractPage(doc, i).plainText();
|
||||
} catch (RuntimeException | Error e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** One native open, all pages' plain text; null if the binding is unavailable. */
|
||||
private static List<String> extractPagesJPDFium(byte[] bytes) {
|
||||
if (!jpdfiumAvailable || bytes.length > MAX_JPDFIUM_VERIFY_BYTES) {
|
||||
return null;
|
||||
}
|
||||
try (PdfDocument doc = PdfDocument.open(bytes)) {
|
||||
List<String> pages = new ArrayList<>();
|
||||
int n = doc.pageCount();
|
||||
for (int i = 0; i < n; i++) {
|
||||
pages.add(jpdfiumPlainText(doc, i));
|
||||
}
|
||||
return pages;
|
||||
} catch (RuntimeException | Error e) {
|
||||
onJpdfiumFailure(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A native-binding load error latches the pass off process-wide (warn once) so a host without
|
||||
* the native stops retrying; a per-document error only skips this one document (debug).
|
||||
*/
|
||||
private static void onJpdfiumFailure(Throwable e) {
|
||||
boolean nativeUnavailable =
|
||||
e instanceof UnsatisfiedLinkError
|
||||
|| e instanceof NoClassDefFoundError
|
||||
|| e instanceof ExceptionInInitializerError
|
||||
|| e.getClass().getSimpleName().contains("NativeLoad");
|
||||
if (nativeUnavailable) {
|
||||
jpdfiumAvailable = false;
|
||||
log.warn(
|
||||
"JPDFium native unavailable; redaction verification will use the PDFBox pass "
|
||||
+ "only: {}",
|
||||
e.toString());
|
||||
} else {
|
||||
log.debug("JPDFium verification skipped for this document: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** Pages whose surviving text (PDFBox glyph-blind OR native PDFium) still matches a target. */
|
||||
static Set<Integer> findLeakingPages(
|
||||
byte[] bytes, Set<String> literalTargets, List<Pattern> patterns) {
|
||||
List<String> jpdfiumPages = extractPagesJPDFium(bytes);
|
||||
try (PDDocument reopened = Loader.loadPDF(bytes)) {
|
||||
// Native pass required but unavailable: PDFBox can't localise the leak, so rasterise
|
||||
// every page.
|
||||
if (jpdfiumPages == null && documentHasUnreliableFont(reopened)) {
|
||||
log.warn(
|
||||
"Independent native pass unavailable on an unreliable-font document; "
|
||||
+ "rasterising all pages to guarantee removal.");
|
||||
return null;
|
||||
}
|
||||
Set<Integer> leaking = new TreeSet<>();
|
||||
GlyphOnlyTextStripper stripper = new GlyphOnlyTextStripper();
|
||||
for (int i = 0; i < reopened.getNumberOfPages(); i++) {
|
||||
stripper.setStartPage(i + 1);
|
||||
stripper.setEndPage(i + 1);
|
||||
String pdfboxText = stripper.getText(reopened);
|
||||
String jpdfiumText =
|
||||
jpdfiumPages != null && i < jpdfiumPages.size() ? jpdfiumPages.get(i) : "";
|
||||
String combined = (pdfboxText == null ? "" : pdfboxText) + "\n" + jpdfiumText;
|
||||
if (pageLeaks(combined, literalTargets, patterns)) {
|
||||
leaking.add(i);
|
||||
}
|
||||
}
|
||||
if (leaking.isEmpty()) {
|
||||
log.warn(
|
||||
"Verification failed but no single page leaks in isolation; rasterising "
|
||||
+ "all pages to be safe.");
|
||||
return null;
|
||||
}
|
||||
log.info("Leak detection: rasterising only page(s) {}", leaking);
|
||||
return leaking;
|
||||
} catch (Exception e) {
|
||||
log.warn("Per-page leak detection failed ({}); rasterising all pages.", e.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean pageLeaks(
|
||||
String pageText, Set<String> literalTargets, List<Pattern> patterns) {
|
||||
try {
|
||||
assertNoTarget(pageText, literalTargets, patterns);
|
||||
return false;
|
||||
} catch (RedactionVerificationFailedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Redacted pages that still show text inside a rect or carry an overlapping annotation. */
|
||||
static Set<Integer> findLeakingRectPages(
|
||||
byte[] bytes, Map<Integer, List<PDRectangle>> rectsByPage) {
|
||||
Set<Integer> leaking = new HashSet<>();
|
||||
if (rectsByPage == null || rectsByPage.isEmpty()) {
|
||||
return leaking;
|
||||
}
|
||||
try (PDDocument reopened = Loader.loadPDF(bytes)) {
|
||||
for (Map.Entry<Integer, List<PDRectangle>> entry : rectsByPage.entrySet()) {
|
||||
int pageIndex = entry.getKey();
|
||||
if (pageIndex < 0 || pageIndex >= reopened.getNumberOfPages()) {
|
||||
continue;
|
||||
}
|
||||
PDPage page = reopened.getPage(pageIndex);
|
||||
if (glyphStillInRects(reopened, page, pageIndex, entry.getValue())
|
||||
|| annotationOverlapsRect(page, entry.getValue())) {
|
||||
leaking.add(pageIndex);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Cannot verify - rasterise every redacted page to be safe.
|
||||
return new HashSet<>(rectsByPage.keySet());
|
||||
}
|
||||
return leaking;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any non-blank glyph is still painted inside a rect. Position-based (not ToUnicode),
|
||||
* so it catches residual CID/Type3/no-ToUnicode glyphs the text stripper would miss; fails
|
||||
* closed.
|
||||
*/
|
||||
private static boolean glyphStillInRects(
|
||||
PDDocument doc, PDPage page, int pageIndex, List<PDRectangle> rects) {
|
||||
try {
|
||||
List<Rectangle2D.Float> areaRects = new ArrayList<>();
|
||||
for (PDRectangle rect : rects) {
|
||||
float pdfY = page.getBBox().getHeight() - rect.getUpperRightY();
|
||||
areaRects.add(
|
||||
new Rectangle2D.Float(
|
||||
rect.getLowerLeftX(), pdfY, rect.getWidth(), rect.getHeight()));
|
||||
}
|
||||
TokenIndexCollector collector = new TokenIndexCollector(areaRects);
|
||||
collector.setStartPage(pageIndex + 1);
|
||||
collector.setEndPage(pageIndex + 1);
|
||||
collector.getText(doc);
|
||||
return collector.anyGlyphInRect();
|
||||
} catch (Exception e) {
|
||||
return true; // cannot prove the rect is clean - rasterise to be safe
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean annotationOverlapsRect(PDPage page, List<PDRectangle> rects) {
|
||||
try {
|
||||
for (var ann : page.getAnnotations()) {
|
||||
PDRectangle ar = ann.getRectangle();
|
||||
if (ar == null) {
|
||||
continue;
|
||||
}
|
||||
Rectangle2D.Float a =
|
||||
new Rectangle2D.Float(
|
||||
ar.getLowerLeftX(),
|
||||
ar.getLowerLeftY(),
|
||||
ar.getWidth(),
|
||||
ar.getHeight());
|
||||
for (PDRectangle rect : rects) {
|
||||
if (a.intersects(
|
||||
rect.getLowerLeftX(),
|
||||
rect.getLowerLeftY(),
|
||||
rect.getWidth(),
|
||||
rect.getHeight())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** PDFTextStripper that strips /ActualText so verification sees the real glyph stream. */
|
||||
private static final class GlyphOnlyTextStripper extends PDFTextStripper {
|
||||
private static final COSName ACTUAL_TEXT = COSName.getPDFName("ActualText");
|
||||
|
||||
GlyphOnlyTextStripper() throws IOException {}
|
||||
|
||||
@Override
|
||||
public void beginMarkedContentSequence(COSName tag, COSDictionary properties) {
|
||||
COSDictionary safe = properties;
|
||||
if (properties != null && properties.containsKey(ACTUAL_TEXT)) {
|
||||
safe = new COSDictionary(properties);
|
||||
safe.removeItem(ACTUAL_TEXT);
|
||||
}
|
||||
super.beginMarkedContentSequence(tag, safe);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.pdfbox.contentstream.operator.Operator;
|
||||
import org.apache.pdfbox.cos.COSBase;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
import org.apache.pdfbox.text.TextPosition;
|
||||
|
||||
/**
|
||||
* Position-based (ToUnicode-independent) glyph locator: records, per text-showing operator, the
|
||||
* 0-based indexes of the non-blank glyphs whose box intersects a rect, plus each operator's total
|
||||
* glyph count. Blank glyphs are ignored so a space left behind by removal is not a "leak".
|
||||
*/
|
||||
final class TokenIndexCollector extends PDFTextStripper {
|
||||
private final List<Rectangle2D.Float> rects;
|
||||
final Map<Integer, Set<Integer>> dropGlyphsByOp = new HashMap<>();
|
||||
final Map<Integer, Integer> glyphCountByOp = new HashMap<>();
|
||||
private int showTextOpCounter = -1;
|
||||
private int glyphInOp = 0;
|
||||
|
||||
TokenIndexCollector(List<Rectangle2D.Float> rects) throws IOException {
|
||||
this.rects = rects;
|
||||
setSortByPosition(false);
|
||||
}
|
||||
|
||||
int totalTextOps() {
|
||||
return showTextOpCounter + 1;
|
||||
}
|
||||
|
||||
boolean anyGlyphInRect() {
|
||||
return !dropGlyphsByOp.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void processTextPosition(TextPosition text) {
|
||||
int op = showTextOpCounter;
|
||||
int idx = glyphInOp++;
|
||||
String u = text.getUnicode();
|
||||
if (u != null && !u.isBlank()) {
|
||||
// PDFBox reports coordinates with top-left origin here.
|
||||
float x = text.getX();
|
||||
float y = text.getY() - text.getHeight();
|
||||
Rectangle2D.Float glyph =
|
||||
new Rectangle2D.Float(x, y, text.getWidth(), text.getHeight());
|
||||
for (Rectangle2D.Float rect : rects) {
|
||||
if (rect.intersects(glyph)) {
|
||||
dropGlyphsByOp.computeIfAbsent(op, k -> new HashSet<>()).add(idx);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
super.processTextPosition(text);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
|
||||
String name = operator.getName();
|
||||
boolean textOp = RedactionPipeline.TEXT_SHOWING_OPERATORS.contains(name);
|
||||
if (textOp) {
|
||||
showTextOpCounter++;
|
||||
glyphInOp = 0;
|
||||
}
|
||||
super.processOperator(operator, operands);
|
||||
if (textOp) {
|
||||
glyphCountByOp.put(showTextOpCounter, glyphInOp);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,21 +86,14 @@ public class TextFinderUtils {
|
||||
return patterns;
|
||||
}
|
||||
|
||||
/** Shared whole-word wrapper so the finder and RedactionPipeline never diverge (see F2). */
|
||||
public static String applyWordBoundaries(String originalTerm, String patternString) {
|
||||
// Lookarounds for single/non-word-edge terms (\b no-ops on chars like '&'); \b otherwise.
|
||||
boolean nonWordEdge =
|
||||
originalTerm.length() == 1
|
||||
|| !isWordChar(originalTerm.charAt(0))
|
||||
|| !isWordChar(originalTerm.charAt(originalTerm.length() - 1));
|
||||
if (nonWordEdge) {
|
||||
private static String applyWordBoundaries(String originalTerm, String patternString) {
|
||||
if (originalTerm.length() == 1 && Character.isDigit(originalTerm.charAt(0))) {
|
||||
return "(?<![\\w])" + patternString + "(?![\\w])";
|
||||
} else if (originalTerm.length() == 1) {
|
||||
return "(?<![\\w])" + patternString + "(?![\\w])";
|
||||
} else {
|
||||
return "\\b" + patternString + "\\b";
|
||||
}
|
||||
return "\\b" + patternString + "\\b";
|
||||
}
|
||||
|
||||
private static boolean isWordChar(char c) {
|
||||
return Character.isLetterOrDigit(c) || c == '_';
|
||||
}
|
||||
|
||||
public static boolean hasProblematicFonts(PDPage page) {
|
||||
|
||||
@@ -366,6 +366,35 @@ aiEngine:
|
||||
enabled: false # Set to 'true' to enable the AI engine integration
|
||||
url: http://localhost:5001 # URL of the Python AI engine
|
||||
timeoutSeconds: 120 # Timeout in seconds for AI engine requests
|
||||
longRunningTimeoutSeconds: 600 # Timeout (seconds) for heavy operations like RAG ingestion of large documents
|
||||
streamTimeoutSeconds: 1800 # SSE stream timeout (seconds) for long-running orchestrator runs
|
||||
pushConfigToEngine: true # Push admin/settings AI config (models, keys, RAG, limits) to the engine on startup + save. Set false to leave the engine fully env-controlled
|
||||
models:
|
||||
provider: anthropic # Model provider: 'anthropic', 'openai', 'ollama', or 'custom' (OpenAI-compatible)
|
||||
smartModel: claude-haiku-4-5 # High-quality tier model name (no provider prefix)
|
||||
fastModel: claude-haiku-4-5 # Cheap/fast tier model name (no provider prefix)
|
||||
smartMaxTokens: 8192 # Max output tokens for the smart tier
|
||||
fastMaxTokens: 2048 # Max output tokens for the fast tier
|
||||
apiKey: "" # API key for the selected provider (secret). Empty = engine uses its native env credentials (e.g. ANTHROPIC_API_KEY)
|
||||
baseUrl: "" # OpenAI-compatible base URL for 'ollama'/'custom' providers (e.g. http://ollama:11434/v1). Ignored for anthropic/openai
|
||||
rag:
|
||||
embeddingProvider: voyageai # Embedding provider: 'voyageai', 'openai', 'ollama', or 'custom' (OpenAI-compatible)
|
||||
embeddingModel: voyage-4 # Embedding model name (no provider prefix)
|
||||
embeddingApiKey: "" # Secret API key for the embedding provider. Empty = engine uses its native env credentials (e.g. VOYAGE_API_KEY)
|
||||
embeddingBaseUrl: "" # OpenAI-compatible base URL for 'ollama'/'custom' embedding providers (e.g. http://ollama:11434/v1). Ignored for voyageai/openai
|
||||
topK: 20 # Number of chunks retrieval returns per search
|
||||
maxSearches: 5 # Per-run cap on knowledge-search tool calls before the agent must answer
|
||||
limits:
|
||||
maxPages: 200 # Upper bound on PDF pages the engine will process per request
|
||||
maxCharacters: 200000 # Upper bound on characters of extracted text per request
|
||||
modelMaxConcurrency: 32 # Process-wide cap on concurrent model API calls (engine restart to apply)
|
||||
features: # Per-capability switches; turn an individual AI tool off without disabling the whole engine
|
||||
chat: true # Assistant chat
|
||||
documentQuestions: true # Ask-questions-about-a-PDF
|
||||
createPdf: true # Generate a PDF from a natural-language spec
|
||||
mathAuditor: true # Numerical/formula contradiction auditing
|
||||
pdfComment: true # AI-authored PDF comments/annotations
|
||||
classify: true # Automatic document classification/labelling
|
||||
|
||||
policies:
|
||||
# Folder automations can read from and write to the directories you allow here, so treat this as a
|
||||
@@ -385,6 +414,8 @@ policies:
|
||||
mcp:
|
||||
enabled: false # Master switch. 'false' (default) means no /mcp endpoint, no metadata, no beans wired.
|
||||
scopesEnabled: true # Enforce mcp.tools.read / mcp.tools.write scopes derived from operation category
|
||||
maxRequestBytes: 10485760 # Max size (bytes) of an incoming MCP tool request payload (default 10 MB)
|
||||
maxInlineResponseBytes: 10485760 # Max size (bytes) of an MCP tool response returned inline before it is rejected (default 10 MB)
|
||||
allowedOperations: [] # Tool allow-list (operation ids, e.g. ['compress-pdf']). Empty = all. When set, ONLY these are exposed over MCP.
|
||||
blockedOperations: [] # Tool deny-list (operation ids). Always removed from MCP even if otherwise allowed.
|
||||
auth:
|
||||
|
||||
+5
-45
@@ -19,7 +19,6 @@ import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -569,15 +568,7 @@ class ManualRedactionServiceTest {
|
||||
byPage.put(0, new ArrayList<>(Arrays.asList(text(0, 72, 690, 300, 710))));
|
||||
|
||||
TempFile result =
|
||||
service.finalizeRedaction(
|
||||
doc,
|
||||
byPage,
|
||||
"#000000",
|
||||
1.0f,
|
||||
false,
|
||||
false,
|
||||
Collections.emptySet(),
|
||||
Collections.emptyList());
|
||||
service.finalizeRedaction(doc, byPage, "#000000", 1.0f, false, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getFile());
|
||||
@@ -599,15 +590,7 @@ class ManualRedactionServiceTest {
|
||||
Map<Integer, List<PDFText>> byPage = new HashMap<>();
|
||||
|
||||
TempFile result =
|
||||
service.finalizeRedaction(
|
||||
doc,
|
||||
byPage,
|
||||
"#000000",
|
||||
0.0f,
|
||||
false,
|
||||
false,
|
||||
Collections.emptySet(),
|
||||
Collections.emptyList());
|
||||
service.finalizeRedaction(doc, byPage, "#000000", 0.0f, false, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getFile().exists());
|
||||
@@ -627,15 +610,7 @@ class ManualRedactionServiceTest {
|
||||
Map<Integer, List<PDFText>> byPage = new HashMap<>();
|
||||
|
||||
TempFile result =
|
||||
service.finalizeRedaction(
|
||||
doc,
|
||||
byPage,
|
||||
"#000000",
|
||||
0.0f,
|
||||
null,
|
||||
false,
|
||||
Collections.emptySet(),
|
||||
Collections.emptyList());
|
||||
service.finalizeRedaction(doc, byPage, "#000000", 0.0f, null, false);
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.getFile().exists());
|
||||
@@ -655,15 +630,7 @@ class ManualRedactionServiceTest {
|
||||
byPage.put(0, new ArrayList<>(Arrays.asList(text(0, 72, 690, 300, 710))));
|
||||
|
||||
TempFile result =
|
||||
service.finalizeRedaction(
|
||||
doc,
|
||||
byPage,
|
||||
"#FF0000",
|
||||
2.0f,
|
||||
false,
|
||||
true,
|
||||
Collections.emptySet(),
|
||||
Collections.emptyList());
|
||||
service.finalizeRedaction(doc, byPage, "#FF0000", 2.0f, false, true);
|
||||
|
||||
assertNotNull(result);
|
||||
try (PDDocument reloaded = Loader.loadPDF(result.getFile())) {
|
||||
@@ -691,14 +658,7 @@ class ManualRedactionServiceTest {
|
||||
IOException.class,
|
||||
() ->
|
||||
service.finalizeRedaction(
|
||||
doc,
|
||||
byPage,
|
||||
"#000000",
|
||||
0.0f,
|
||||
false,
|
||||
false,
|
||||
Collections.emptySet(),
|
||||
Collections.emptyList()));
|
||||
doc, byPage, "#000000", 0.0f, false, false));
|
||||
// The failing temp file is closed on the error path.
|
||||
verify(failing).close();
|
||||
} finally {
|
||||
|
||||
+4
-16
@@ -192,27 +192,15 @@ class RedactControllerTest {
|
||||
when(mockCOSStream.createOutputStream()).thenReturn(mockOutputStream);
|
||||
when(mockCOSStream.createOutputStream(any())).thenReturn(mockOutputStream);
|
||||
|
||||
// The pipeline saves then reloads the bytes to verify, so the mock must emit a real,
|
||||
// reloadable PDF (not a placeholder) or verification throws on reopen.
|
||||
byte[] realPdfBytes = createSimplePdfContent();
|
||||
lenient()
|
||||
.doAnswer(
|
||||
inv -> {
|
||||
File f = inv.getArgument(0);
|
||||
java.nio.file.Files.write(f.toPath(), realPdfBytes);
|
||||
java.nio.file.Files.write(f.toPath(), "mock pdf".getBytes());
|
||||
return null;
|
||||
})
|
||||
.when(mockDocument)
|
||||
.save(any(File.class));
|
||||
lenient()
|
||||
.doAnswer(
|
||||
inv -> {
|
||||
java.io.OutputStream os = inv.getArgument(0);
|
||||
os.write(realPdfBytes);
|
||||
return null;
|
||||
})
|
||||
.when(mockDocument)
|
||||
.save(any(java.io.OutputStream.class));
|
||||
doNothing().when(mockDocument).close();
|
||||
|
||||
// Build real service instances so tests exercise actual logic
|
||||
@@ -359,7 +347,7 @@ class RedactControllerTest {
|
||||
assertNotNull(response);
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
|
||||
verify(mockDocument).save(any(java.io.OutputStream.class));
|
||||
verify(mockDocument).save(any(File.class));
|
||||
verify(mockDocument).close();
|
||||
}
|
||||
}
|
||||
@@ -765,7 +753,7 @@ class RedactControllerTest {
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertNotNull(response.getBody());
|
||||
assertTrue(drainBody(response).length > 0);
|
||||
verify(mockDocument, times(1)).save(any(java.io.OutputStream.class));
|
||||
verify(mockDocument, times(1)).save(any(File.class));
|
||||
verify(mockDocument, times(1)).close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -788,7 +776,7 @@ class RedactControllerTest {
|
||||
if (response != null) {
|
||||
assertNotNull(response);
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
verify(mockDocument, times(1)).save(any(java.io.OutputStream.class));
|
||||
verify(mockDocument, times(1)).save(any(File.class));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.info("Manual redaction test completed with graceful handling: {}", e.getMessage());
|
||||
|
||||
-755
@@ -1,755 +0,0 @@
|
||||
package stirling.software.SPDF.controller.api.security;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
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 java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.cos.COSArray;
|
||||
import org.apache.pdfbox.cos.COSDictionary;
|
||||
import org.apache.pdfbox.cos.COSInteger;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.cos.COSStream;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDFormContentStream;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
import org.apache.pdfbox.pdmodel.common.PDStream;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
|
||||
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType0Font;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType1Font;
|
||||
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
|
||||
import org.apache.pdfbox.pdmodel.font.encoding.MacRomanEncoding;
|
||||
import org.apache.pdfbox.pdmodel.font.encoding.WinAnsiEncoding;
|
||||
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
import org.apache.pdfbox.util.Matrix;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import stirling.software.SPDF.model.api.security.RedactPdfRequest;
|
||||
import stirling.software.SPDF.pdf.redaction.RedactionPipeline;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.TempFile;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
|
||||
/** Security matrix for redaction across PDF shapes: standard and embedded */
|
||||
@DisplayName("Redaction PDF-variety security matrix")
|
||||
class RedactionPdfVarietyTest {
|
||||
|
||||
private static final String LIBERATION =
|
||||
"/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf";
|
||||
private static final float FONT_SIZE = 12f;
|
||||
private static final float LEFT_X = 72f;
|
||||
private static final float TOP_Y = PDRectangle.LETTER.getHeight() - 80f;
|
||||
|
||||
private CustomPDFDocumentFactory pdfDocumentFactory;
|
||||
private TempFileManager tempFileManager;
|
||||
private RedactController controller;
|
||||
|
||||
private final List<File> createdTempFiles = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
pdfDocumentFactory = mock(CustomPDFDocumentFactory.class);
|
||||
tempFileManager = mock(TempFileManager.class);
|
||||
|
||||
lenient()
|
||||
.when(tempFileManager.createManagedTempFile(anyString()))
|
||||
.thenAnswer(
|
||||
inv -> {
|
||||
File f =
|
||||
Files.createTempFile(
|
||||
"redact-variety", inv.<String>getArgument(0))
|
||||
.toFile();
|
||||
createdTempFiles.add(f);
|
||||
TempFile tf = mock(TempFile.class);
|
||||
lenient().when(tf.getFile()).thenReturn(f);
|
||||
lenient().when(tf.getPath()).thenReturn(f.toPath());
|
||||
return tf;
|
||||
});
|
||||
|
||||
controller =
|
||||
new RedactController(
|
||||
pdfDocumentFactory,
|
||||
tempFileManager,
|
||||
new ManualRedactionService(tempFileManager),
|
||||
new TextRedactionService(),
|
||||
mock(RedactExecuteService.class));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
for (File f : createdTempFiles) {
|
||||
if (f != null && f.exists()) {
|
||||
f.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Matrix cases (all through the real /auto-redact controller path)
|
||||
|
||||
@Test
|
||||
@DisplayName("standard Helvetica: target gone, neighbours survive")
|
||||
void standard14Helvetica() throws IOException {
|
||||
byte[] out = autoRedact(helveticaPdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("standard-14 Times and Courier: target gone, neighbours survive")
|
||||
void standard14TimesAndCourier() throws IOException {
|
||||
for (Standard14Fonts.FontName fn :
|
||||
new Standard14Fonts.FontName[] {
|
||||
Standard14Fonts.FontName.TIMES_ROMAN, Standard14Fonts.FontName.COURIER
|
||||
}) {
|
||||
byte[] pdf = std14Pdf(fn, "alpha SECRET omega");
|
||||
byte[] out = autoRedact(pdf, "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).as("%s keeps neighbours", fn).contains("alpha");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("simple TrueType with MacRoman encoding: target gone, neighbours survive")
|
||||
void simpleTrueTypeMacRoman() throws IOException {
|
||||
byte[] out = autoRedact(macRomanTtfPdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("embedded Type0 with /ToUnicode stripped: target still gone, neighbours survive")
|
||||
void type0WithoutToUnicode() throws IOException {
|
||||
byte[] out = autoRedact(type0NoToUnicodePdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("symbolic TrueType (no encoding, no ToUnicode): target not extractable")
|
||||
void symbolicTrueType() throws IOException {
|
||||
// PDFBox extraction is glyph-blind here, so removal is guaranteed by the native pass +
|
||||
// rasterise fallback rather than surgical decode; this pins that the pipeline handles a
|
||||
// symbolic font without error and leaves no extractable target.
|
||||
byte[] out = autoRedact(symbolicTtfPdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("subset-tagged font (ABCDEF+): target gone, neighbours survive")
|
||||
void subsetTaggedFont() throws IOException {
|
||||
byte[] out = autoRedact(subsetTaggedPdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("real Type3 font (glyphs as content streams, no ToUnicode): target gone")
|
||||
void type3GlyphProcs() throws IOException {
|
||||
// crop_test.pdf uses DejaVuSans embedded as a subset Type3 font with no
|
||||
byte[] input;
|
||||
try (InputStream in = getClass().getResourceAsStream("/redaction/type3_dejavu.pdf")) {
|
||||
input = in.readAllBytes();
|
||||
}
|
||||
byte[] out = autoRedact(input, "EXAMPLE");
|
||||
assertGone(out, "EXAMPLE");
|
||||
assertThat(pdfText(out)).contains("CROP");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("embedded subset Type0 (CID) font: target gone, neighbours survive")
|
||||
void embeddedSubsetType0() throws IOException {
|
||||
byte[] out = autoRedact(type0Pdf(true, "alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("embedded full Type0 (CID) font: target gone, neighbours survive")
|
||||
void embeddedFullType0() throws IOException {
|
||||
byte[] out = autoRedact(type0Pdf(false, "alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("embedded Type1 (PFB) font: target gone, neighbours survive")
|
||||
void embeddedType1() throws IOException {
|
||||
byte[] out = autoRedact(type1Pdf("PUBLICA SECRETWORD KEEP"), "SECRETWORD");
|
||||
assertGone(out, "SECRETWORD");
|
||||
assertThat(pdfText(out)).contains("PUBLICA").contains("KEEP");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("embedded CJK Type0 (CIDFontType2) font: CJK target gone, neighbours survive")
|
||||
void embeddedCjkType0() throws IOException {
|
||||
byte[] out = autoRedact(cjkPdf("PUBLICA \u79D8\u5BC6 KEEP"), "\u79D8\u5BC6");
|
||||
assertGone(out, "\u79D8\u5BC6");
|
||||
assertThat(pdfText(out)).contains("PUBLICA").contains("KEEP");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("embedded CIDFontType0 (CFF) font: target gone, neighbours survive")
|
||||
void embeddedCidFontType0() throws IOException {
|
||||
byte[] out = autoRedact(cidFontType0Pdf("PUBLICA SECRETWORD KEEP"), "SECRETWORD");
|
||||
assertGone(out, "SECRETWORD");
|
||||
assertThat(pdfText(out)).contains("PUBLICA").contains("KEEP");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("simple embedded TrueType (WinAnsi) font: target gone, neighbours survive")
|
||||
void simpleTrueTypeWinAnsi() throws IOException {
|
||||
byte[] out = autoRedact(simpleTtfPdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rotated pages (90/180/270): target gone on every rotation")
|
||||
void rotatedPages() throws IOException {
|
||||
for (int rotation : new int[] {90, 180, 270}) {
|
||||
byte[] out = autoRedact(rotatedPdf(rotation, "alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).as("rotation %d keeps neighbours", rotation).contains("alpha");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("target split across TJ array operands is removed")
|
||||
void tjArraySplit() throws IOException {
|
||||
byte[] out = autoRedact(tjSplitPdf(), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("public");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("target split across separate Tj operators is removed, other pages keep text")
|
||||
void crossOperatorSplit() throws IOException {
|
||||
byte[] out = autoRedact(crossOperatorPdf(), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
// Page 2 was never touched; whatever path handled page 1, page 2 text must
|
||||
assertThat(pdfText(out)).contains("PUBLIC PAGE TWO");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("target inside a Form XObject is removed")
|
||||
void formXObjectText() throws IOException {
|
||||
byte[] out = autoRedact(formXObjectPdf(), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CropBox smaller than MediaBox: target gone, neighbours survive")
|
||||
void cropBoxOffset() throws IOException {
|
||||
byte[] out = autoRedact(cropBoxPdf("alpha SECRET omega"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("alpha");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("multi-page: target on middle page only, other pages keep their text")
|
||||
void multiPageMiddleTarget() throws IOException {
|
||||
byte[] out =
|
||||
autoRedact(
|
||||
multiPagePdf("PUBLIC ONE", "middle SECRET line", "PUBLIC THREE"), "SECRET");
|
||||
assertGone(out, "SECRET");
|
||||
assertThat(pdfText(out)).contains("PUBLIC ONE").contains("PUBLIC THREE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("case variant: doc contains 'Secret', target 'SECRET' removes it")
|
||||
void caseVariantRemoved() throws IOException {
|
||||
byte[] out = autoRedact(helveticaPdf("alpha Secret omega"), "SECRET");
|
||||
assertGone(out, "Secret");
|
||||
assertThat(pdfText(out)).contains("alpha").contains("omega");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("whole-word with case variant: 'Cat' removed, substrings survive")
|
||||
void wholeWordCaseVariant() throws IOException {
|
||||
byte[] bytes = helveticaPdf("Cat classification scatter");
|
||||
factoryReturns(bytes);
|
||||
RedactPdfRequest request = baseRequest(bytes, "cat");
|
||||
request.setWholeWordSearch(true);
|
||||
|
||||
byte[] out = drainBody(controller.redactPdf(request));
|
||||
String text = pdfText(out);
|
||||
assertThat(text).contains("classification").contains("scatter");
|
||||
// The standalone word must be gone in any case variant.
|
||||
assertThat(text).doesNotContainPattern("(?i)\\bcat\\b");
|
||||
}
|
||||
|
||||
// Page-scoped rasterisation (pipeline-level, deterministic)
|
||||
|
||||
@Test
|
||||
@DisplayName("verification leak rasterises only the leaking page, others keep text")
|
||||
void leakRasterisesOnlyLeakingPage() throws IOException {
|
||||
// Cross-operator split defeats the per-operand literal rewriter
|
||||
byte[] input = crossOperatorPdf();
|
||||
byte[] out;
|
||||
try (PDDocument doc = Loader.loadPDF(input)) {
|
||||
Set<String> targets = Set.of("SECRET");
|
||||
List<Pattern> patterns =
|
||||
RedactionPipeline.buildPatterns(new String[] {"SECRET"}, false, false);
|
||||
RedactionPipeline.redactLiteralTerms(doc, targets, patterns);
|
||||
out = RedactionPipeline.finalize(doc, targets, patterns);
|
||||
}
|
||||
|
||||
try (PDDocument reopened = Loader.loadPDF(out)) {
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
stripper.setStartPage(1);
|
||||
stripper.setEndPage(1);
|
||||
String page1 = stripper.getText(reopened);
|
||||
stripper.setStartPage(2);
|
||||
stripper.setEndPage(2);
|
||||
String page2 = stripper.getText(reopened);
|
||||
|
||||
assertThat(page1.toLowerCase()).doesNotContain("secret");
|
||||
assertThat(page2).contains("PUBLIC PAGE TWO");
|
||||
}
|
||||
}
|
||||
|
||||
// Drivers and assertions
|
||||
|
||||
private byte[] autoRedact(byte[] pdfBytes, String target) throws IOException {
|
||||
factoryReturns(pdfBytes);
|
||||
RedactPdfRequest request = baseRequest(pdfBytes, target);
|
||||
ResponseEntity<Resource> response = controller.redactPdf(request);
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(200);
|
||||
return drainBody(response);
|
||||
}
|
||||
|
||||
private RedactPdfRequest baseRequest(byte[] pdfBytes, String target) {
|
||||
RedactPdfRequest request = new RedactPdfRequest();
|
||||
request.setFileInput(pdfFile(pdfBytes));
|
||||
request.setListOfText(target);
|
||||
request.setUseRegex(false);
|
||||
request.setWholeWordSearch(false);
|
||||
request.setRedactColor("#000000");
|
||||
request.setConvertPDFToImage(false);
|
||||
return request;
|
||||
}
|
||||
|
||||
private void assertGone(byte[] out, String target) throws IOException {
|
||||
assertThat(pdfText(out).toLowerCase()).doesNotContain(target.toLowerCase());
|
||||
}
|
||||
|
||||
private void factoryReturns(byte[] pdfBytes) throws IOException {
|
||||
lenient()
|
||||
.when(pdfDocumentFactory.load(any(MultipartFile.class)))
|
||||
.thenAnswer(inv -> Loader.loadPDF(pdfBytes));
|
||||
}
|
||||
|
||||
private MockMultipartFile pdfFile(byte[] bytes) {
|
||||
return new MockMultipartFile("fileInput", "doc.pdf", "application/pdf", bytes);
|
||||
}
|
||||
|
||||
private byte[] drainBody(ResponseEntity<Resource> response) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (InputStream in = response.getBody().getInputStream()) {
|
||||
in.transferTo(baos);
|
||||
}
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
private String pdfText(byte[] pdfBytes) throws IOException {
|
||||
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
|
||||
return new PDFTextStripper().getText(doc);
|
||||
}
|
||||
}
|
||||
|
||||
// PDF builders
|
||||
|
||||
private static PDFont helvetica() {
|
||||
return new PDType1Font(Standard14Fonts.FontName.HELVETICA);
|
||||
}
|
||||
|
||||
private byte[] helveticaPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
addTextPage(doc, helvetica(), line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] std14Pdf(Standard14Fonts.FontName fontName, String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
addTextPage(doc, new PDType1Font(fontName), line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] macRomanTtfPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream ttf = PDDocument.class.getResourceAsStream(LIBERATION)) {
|
||||
font = PDTrueTypeFont.load(doc, ttf, MacRomanEncoding.INSTANCE);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
// GID order emitted by generators/gen_cff_cidfont.py: 0=.notdef 1=space then the letters.
|
||||
private static final String CFF_GLYPHS = "\0 ABCDEIKLOPRSTUW";
|
||||
|
||||
private static int cffGid(char c) {
|
||||
int i = CFF_GLYPHS.indexOf(c);
|
||||
return i < 0 ? 0 : i;
|
||||
}
|
||||
|
||||
/**
|
||||
* PDFBox 3.0.7 has no CFF embedder, so hand-assemble a Type0 -> CIDFontType0 (CFF in
|
||||
* /FontFile3, Identity-H, CID==GID, explicit /ToUnicode) from the generated CFF program.
|
||||
*/
|
||||
private byte[] cidFontType0Pdf(String line) throws IOException {
|
||||
byte[] cff;
|
||||
try (InputStream in = getClass().getResourceAsStream("/redaction/cidfont0_cff.bin")) {
|
||||
cff = in.readAllBytes();
|
||||
}
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage(PDRectangle.A4);
|
||||
doc.addPage(page);
|
||||
|
||||
PDStream fontFile = new PDStream(doc);
|
||||
try (var os = fontFile.createOutputStream()) {
|
||||
os.write(cff);
|
||||
}
|
||||
COSStream ff = fontFile.getCOSObject();
|
||||
ff.setItem(COSName.SUBTYPE, COSName.getPDFName("CIDFontType0C"));
|
||||
|
||||
COSDictionary fdesc = new COSDictionary();
|
||||
fdesc.setItem(COSName.TYPE, COSName.FONT_DESC);
|
||||
fdesc.setName(COSName.FONT_NAME, "MinimalCFFCID");
|
||||
fdesc.setInt(COSName.FLAGS, 4);
|
||||
COSArray bbox = new COSArray();
|
||||
for (int v : new int[] {0, -200, 600, 800}) {
|
||||
bbox.add(COSInteger.get(v));
|
||||
}
|
||||
fdesc.setItem(COSName.FONT_BBOX, bbox);
|
||||
fdesc.setInt(COSName.ITALIC_ANGLE, 0);
|
||||
fdesc.setInt(COSName.ASCENT, 800);
|
||||
fdesc.setInt(COSName.DESCENT, -200);
|
||||
fdesc.setInt(COSName.CAP_HEIGHT, 700);
|
||||
fdesc.setInt(COSName.STEM_V, 80);
|
||||
fdesc.setItem(COSName.getPDFName("FontFile3"), ff);
|
||||
|
||||
COSDictionary cidSystemInfo = new COSDictionary();
|
||||
cidSystemInfo.setString(COSName.REGISTRY, "Adobe");
|
||||
cidSystemInfo.setString(COSName.ORDERING, "Identity");
|
||||
cidSystemInfo.setInt(COSName.SUPPLEMENT, 0);
|
||||
|
||||
COSDictionary cidFont = new COSDictionary();
|
||||
cidFont.setItem(COSName.TYPE, COSName.FONT);
|
||||
cidFont.setItem(COSName.SUBTYPE, COSName.CID_FONT_TYPE0);
|
||||
cidFont.setName(COSName.BASE_FONT, "MinimalCFFCID");
|
||||
cidFont.setItem(COSName.CIDSYSTEMINFO, cidSystemInfo);
|
||||
cidFont.setItem(COSName.FONT_DESC, fdesc);
|
||||
cidFont.setInt(COSName.DW, 600);
|
||||
|
||||
COSStream toUni = new PDStream(doc).getCOSObject();
|
||||
try (var os = toUni.createOutputStream()) {
|
||||
os.write(cffToUnicode().getBytes(java.nio.charset.StandardCharsets.US_ASCII));
|
||||
}
|
||||
|
||||
COSDictionary type0 = new COSDictionary();
|
||||
type0.setItem(COSName.TYPE, COSName.FONT);
|
||||
type0.setItem(COSName.SUBTYPE, COSName.TYPE0);
|
||||
type0.setName(COSName.BASE_FONT, "MinimalCFFCID");
|
||||
type0.setItem(COSName.ENCODING, COSName.IDENTITY_H);
|
||||
COSArray descendants = new COSArray();
|
||||
descendants.add(cidFont);
|
||||
type0.setItem(COSName.DESCENDANT_FONTS, descendants);
|
||||
type0.setItem(COSName.TO_UNICODE, toUni);
|
||||
|
||||
PDFont font = org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(type0);
|
||||
PDResources res = new PDResources();
|
||||
COSName fName = res.add(font);
|
||||
page.setResources(res);
|
||||
|
||||
StringBuilder csb = new StringBuilder();
|
||||
csb.append("BT\n/").append(fName.getName()).append(" 24 Tf\n50 700 Td\n<");
|
||||
for (int i = 0; i < line.length(); i++) {
|
||||
csb.append(String.format("%04X", cffGid(line.charAt(i))));
|
||||
}
|
||||
csb.append("> Tj\nET\n");
|
||||
PDStream content = new PDStream(doc);
|
||||
try (var os = content.createOutputStream()) {
|
||||
os.write(csb.toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII));
|
||||
}
|
||||
page.setContents(content);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private static String cffToUnicode() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n");
|
||||
sb.append("/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n");
|
||||
sb.append("/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n");
|
||||
sb.append("1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
|
||||
StringBuilder body = new StringBuilder();
|
||||
int count = 0;
|
||||
for (int gid = 1; gid < CFF_GLYPHS.length(); gid++) {
|
||||
body.append(String.format("<%04X> <%04X>\n", gid, (int) CFF_GLYPHS.charAt(gid)));
|
||||
count++;
|
||||
}
|
||||
sb.append(count).append(" beginbfchar\n").append(body).append("endbfchar\n");
|
||||
sb.append("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private byte[] type1Pdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream pfb = getClass().getResourceAsStream("/redaction/type1_minimal.pfb")) {
|
||||
font = new PDType1Font(doc, pfb, WinAnsiEncoding.INSTANCE);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] cjkPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream ttf = getClass().getResourceAsStream("/redaction/cjk_minimal.ttf")) {
|
||||
font = PDType0Font.load(doc, ttf, true);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] symbolicTtfPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDTrueTypeFont font;
|
||||
try (InputStream ttf = PDDocument.class.getResourceAsStream(LIBERATION)) {
|
||||
font = PDTrueTypeFont.load(doc, ttf, WinAnsiEncoding.INSTANCE);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
// Strip /Encoding and flag the descriptor Symbolic so extraction must use the cmap.
|
||||
font.getCOSObject().removeItem(org.apache.pdfbox.cos.COSName.ENCODING);
|
||||
PDFontDescriptor fd = font.getFontDescriptor();
|
||||
fd.setFlags((fd.getFlags() | 4) & ~32);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] type0NoToUnicodePdf(String line) throws IOException {
|
||||
byte[] pdf;
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream ttf = PDDocument.class.getResourceAsStream(LIBERATION)) {
|
||||
// Full embed, not subset: the subsetter regenerates /ToUnicode at save, undoing the
|
||||
// strip.
|
||||
font = PDType0Font.load(doc, ttf, false);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
font.getCOSObject().removeItem(org.apache.pdfbox.cos.COSName.TO_UNICODE);
|
||||
pdf = save(doc);
|
||||
}
|
||||
// Guard: the strip must survive save so this fixture genuinely exercises the no-mapping
|
||||
// path.
|
||||
try (PDDocument reopened = Loader.loadPDF(pdf)) {
|
||||
PDResources res = reopened.getPage(0).getResources();
|
||||
for (org.apache.pdfbox.cos.COSName n : res.getFontNames()) {
|
||||
assertThat(
|
||||
res.getFont(n)
|
||||
.getCOSObject()
|
||||
.containsKey(org.apache.pdfbox.cos.COSName.TO_UNICODE))
|
||||
.as("no-ToUnicode fixture must not ship /ToUnicode")
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
return pdf;
|
||||
}
|
||||
|
||||
private byte[] subsetTaggedPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream ttf = PDDocument.class.getResourceAsStream(LIBERATION)) {
|
||||
font = PDType0Font.load(doc, ttf, true);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
String tagged = "ABCDEF+" + font.getName();
|
||||
font.getCOSObject().setName(org.apache.pdfbox.cos.COSName.BASE_FONT, tagged);
|
||||
if (font.getFontDescriptor() != null) {
|
||||
font.getFontDescriptor()
|
||||
.getCOSObject()
|
||||
.setName(org.apache.pdfbox.cos.COSName.FONT_NAME, tagged);
|
||||
}
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] type0Pdf(boolean subset, String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream ttf = PDDocument.class.getResourceAsStream(LIBERATION)) {
|
||||
font = PDType0Font.load(doc, ttf, subset);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] simpleTtfPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDFont font;
|
||||
try (InputStream ttf = PDDocument.class.getResourceAsStream(LIBERATION)) {
|
||||
font = PDTrueTypeFont.load(doc, ttf, WinAnsiEncoding.INSTANCE);
|
||||
}
|
||||
addTextPage(doc, font, line, 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] rotatedPdf(int rotation, String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
addTextPage(doc, helvetica(), line, rotation, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] cropBoxPdf(String line) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
addTextPage(doc, helvetica(), line, 0, new PDRectangle(40, 40, 500, 700));
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] multiPagePdf(String... pageLines) throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
for (String line : pageLines) {
|
||||
addTextPage(doc, helvetica(), line, 0, null);
|
||||
}
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
/** One page whose text is emitted as a TJ array: ["public ", "SEC", -20 */
|
||||
private byte[] tjSplitPdf() throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage(PDRectangle.LETTER);
|
||||
doc.addPage(page);
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(helvetica(), FONT_SIZE);
|
||||
cs.newLineAtOffset(LEFT_X, TOP_Y);
|
||||
cs.showTextWithPositioning(
|
||||
new Object[] {"public ", "SEC", Float.valueOf(-20f), "RET", " end"});
|
||||
cs.endText();
|
||||
}
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
/** Page 1 shows "SEC" and "RET" as separate adjacent Tj operators; page 2 */
|
||||
private byte[] crossOperatorPdf() throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage(PDRectangle.LETTER);
|
||||
doc.addPage(page);
|
||||
PDFont font = helvetica();
|
||||
float secWidth = font.getStringWidth("SEC") / 1000f * FONT_SIZE;
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(font, FONT_SIZE);
|
||||
cs.newLineAtOffset(LEFT_X, TOP_Y);
|
||||
cs.showText("SEC");
|
||||
cs.endText();
|
||||
cs.beginText();
|
||||
cs.setFont(font, FONT_SIZE);
|
||||
cs.newLineAtOffset(LEFT_X + secWidth, TOP_Y);
|
||||
cs.showText("RET");
|
||||
cs.endText();
|
||||
}
|
||||
addTextPage(doc, helvetica(), "PUBLIC PAGE TWO", 0, null);
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] formXObjectPdf() throws IOException {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage(PDRectangle.LETTER);
|
||||
doc.addPage(page);
|
||||
|
||||
PDFormXObject form = new PDFormXObject(doc);
|
||||
form.setBBox(new PDRectangle(0, 0, 400, 60));
|
||||
form.setResources(new PDResources());
|
||||
try (PDFormContentStream fcs = new PDFormContentStream(form)) {
|
||||
fcs.beginText();
|
||||
fcs.setFont(helvetica(), FONT_SIZE);
|
||||
fcs.newLineAtOffset(10, 20);
|
||||
fcs.showText("xobj SECRET payload");
|
||||
fcs.endText();
|
||||
}
|
||||
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.saveGraphicsState();
|
||||
cs.transform(Matrix.getTranslateInstance(LEFT_X, TOP_Y - 60));
|
||||
cs.drawForm(form);
|
||||
cs.restoreGraphicsState();
|
||||
}
|
||||
return save(doc);
|
||||
}
|
||||
}
|
||||
|
||||
private void addTextPage(
|
||||
PDDocument doc, PDFont font, String line, int rotation, PDRectangle cropBox)
|
||||
throws IOException {
|
||||
PDPage page = new PDPage(PDRectangle.LETTER);
|
||||
if (rotation != 0) {
|
||||
page.setRotation(rotation);
|
||||
}
|
||||
if (cropBox != null) {
|
||||
page.setCropBox(cropBox);
|
||||
}
|
||||
doc.addPage(page);
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(font, FONT_SIZE);
|
||||
if (rotation != 0) {
|
||||
// Real generators compensate the text matrix so text reads upright
|
||||
cs.setTextMatrix(
|
||||
Matrix.getRotateInstance(
|
||||
Math.toRadians(rotation),
|
||||
PDRectangle.LETTER.getWidth() / 2,
|
||||
PDRectangle.LETTER.getHeight() / 2));
|
||||
} else {
|
||||
cs.newLineAtOffset(LEFT_X, TOP_Y);
|
||||
}
|
||||
cs.showText(line);
|
||||
cs.endText();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] save(PDDocument doc) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
doc.save(baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
}
|
||||
+2
-6
@@ -287,12 +287,8 @@ class TextRedactionServiceExtraTest {
|
||||
|
||||
service.createTokensWithoutTargetText(doc, page, Set.of("SECRET"), false, false);
|
||||
|
||||
// The deep traversal must have rewritten the inner form's own stream in place (F3).
|
||||
String innerContent;
|
||||
try (var in = inner.getContents()) {
|
||||
innerContent = new String(in.readAllBytes(), StandardCharsets.ISO_8859_1);
|
||||
}
|
||||
assertThat(innerContent).doesNotContain("SECRET");
|
||||
// The deep traversal must have rewritten the inner form's content stream.
|
||||
assertThat(inner.getCOSObject().containsKey(COSName.CONTENTS)).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-12
@@ -226,23 +226,19 @@ class TextRedactionServiceMoreTest {
|
||||
}
|
||||
page.setContents(pageStream);
|
||||
|
||||
// Processing the page walks into the XObject graph and rewrites the form's own
|
||||
// stream body in place (F3), so the target is physically gone from the form.
|
||||
// Processing the page walks into the XObject graph; when a match is found inside
|
||||
// the
|
||||
// form, writeRedactedContentToXObject runs and sets a /Contents item on the form's
|
||||
// COS dictionary. Asserting that item appears proves the XObject redaction path
|
||||
// executed end-to-end without throwing.
|
||||
List<Object> tokens =
|
||||
service.createTokensWithoutTargetText(
|
||||
doc, page, Set.of("SECRET"), false, false);
|
||||
|
||||
assertThat(tokens).isNotNull();
|
||||
String rewrittenForm;
|
||||
try (var in = form.getContents()) {
|
||||
rewrittenForm =
|
||||
new String(
|
||||
in.readAllBytes(),
|
||||
java.nio.charset.StandardCharsets.ISO_8859_1);
|
||||
}
|
||||
assertThat(rewrittenForm)
|
||||
.as("form XObject content should have the target removed in place")
|
||||
.doesNotContain("SECRET");
|
||||
assertThat(form.getCOSObject().containsKey(COSName.CONTENTS))
|
||||
.as("form XObject redaction path should have written a new content item")
|
||||
.isTrue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
package stirling.software.SPDF.pdf.redaction;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType1Font;
|
||||
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Integration tests that exercise the real redaction pipeline against PDFs */
|
||||
class RedactionPipelineIntegrationTest {
|
||||
|
||||
private static byte[] loadFixture() throws Exception {
|
||||
try (InputStream in =
|
||||
RedactionPipelineIntegrationTest.class.getResourceAsStream(
|
||||
"/redaction/test_pdf_1.pdf")) {
|
||||
assertNotNull(in, "fixture resource must exist on classpath");
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"finalize on rotated ReportLab PDF without a rewrite pass falls back to rasterisation so target disappears")
|
||||
void finaliseFallsBackToRasterisationWhenTargetWouldSurvive() throws Exception {
|
||||
byte[] fixtureBytes = loadFixture();
|
||||
byte[] outputBytes;
|
||||
try (PDDocument doc = Loader.loadPDF(fixtureBytes)) {
|
||||
Set<String> literalTargets = new LinkedHashSet<>();
|
||||
literalTargets.add("Test");
|
||||
// No content-stream rewriting performed.
|
||||
outputBytes = RedactionPipeline.finalize(doc, literalTargets, Collections.emptyList());
|
||||
}
|
||||
try (PDDocument reopened = Loader.loadPDF(outputBytes)) {
|
||||
String extracted = new PDFTextStripper().getText(reopened);
|
||||
String lower = extracted == null ? "" : extracted.toLowerCase(Locale.ROOT);
|
||||
assertFalse(
|
||||
lower.contains("test"),
|
||||
"Rasterisation fallback must have removed target. Extracted: '"
|
||||
+ extracted
|
||||
+ "'");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"finalize with zero rewrite + synthetic upright PDF triggers RedactionVerificationFailedException only when fallback disabled")
|
||||
void verificationExceptionWiringSanityCheck() throws Exception {
|
||||
// This test proves the verification hook itself still throws -
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage(PDRectangle.A4);
|
||||
doc.addPage(page);
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
|
||||
cs.newLineAtOffset(100, 700);
|
||||
cs.showText("Top Smith Classified");
|
||||
cs.endText();
|
||||
}
|
||||
Set<String> literalTargets = new LinkedHashSet<>();
|
||||
literalTargets.add("Smith");
|
||||
// Even with the rasterisation fallback active, the output must not contain
|
||||
byte[] outBytes =
|
||||
RedactionPipeline.finalize(doc, literalTargets, Collections.emptyList());
|
||||
try (PDDocument reopened = Loader.loadPDF(outBytes)) {
|
||||
String extracted = new PDFTextStripper().getText(reopened);
|
||||
String lower = extracted == null ? "" : extracted.toLowerCase(Locale.ROOT);
|
||||
assertFalse(
|
||||
lower.contains("smith"),
|
||||
"Neither primary pass nor rasterisation removed target. Extracted: '"
|
||||
+ extracted
|
||||
+ "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"auto-word redact on rotated PDF with target packed in single Tj removes the word from text stream")
|
||||
void autoWordRedactRemovesTargetOnRotatedSingleTjPdf() throws Exception {
|
||||
byte[] fixtureBytes = loadFixture();
|
||||
byte[] outputBytes;
|
||||
Set<String> literalTargets = new LinkedHashSet<>();
|
||||
literalTargets.add("Test");
|
||||
List<Pattern> patterns =
|
||||
RedactionPipeline.buildPatterns(new String[] {"Test"}, false, false);
|
||||
|
||||
try (PDDocument doc = Loader.loadPDF(fixtureBytes)) {
|
||||
RedactionPipeline.redactLiteralTerms(doc, literalTargets, patterns);
|
||||
outputBytes = RedactionPipeline.finalize(doc, literalTargets, patterns);
|
||||
}
|
||||
|
||||
try (PDDocument reopened = Loader.loadPDF(outputBytes)) {
|
||||
PDFTextStripper stripper = new PDFTextStripper();
|
||||
String extracted = stripper.getText(reopened);
|
||||
String lower = extracted == null ? "" : extracted.toLowerCase(Locale.ROOT);
|
||||
assertFalse(
|
||||
lower.contains("test"),
|
||||
"Target term must not be extractable after redact. Extracted: '"
|
||||
+ extracted
|
||||
+ "'");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("simple upright Helvetica fixture still gets word redacted via the pipeline")
|
||||
void autoWordRedactRemovesTargetOnSyntheticPdf() throws Exception {
|
||||
byte[] outputBytes;
|
||||
Set<String> literalTargets = new LinkedHashSet<>();
|
||||
literalTargets.add("Secret");
|
||||
List<Pattern> patterns =
|
||||
RedactionPipeline.buildPatterns(new String[] {"Secret"}, false, false);
|
||||
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage(PDRectangle.A4);
|
||||
doc.addPage(page);
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
|
||||
cs.newLineAtOffset(100, 700);
|
||||
cs.showText("Top Secret Classified");
|
||||
cs.endText();
|
||||
}
|
||||
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
|
||||
doc.save(tmp);
|
||||
// reload from bytes so we are processing an already-saved PDF similar
|
||||
try (PDDocument reloaded = Loader.loadPDF(tmp.toByteArray())) {
|
||||
RedactionPipeline.redactLiteralTerms(reloaded, literalTargets, patterns);
|
||||
outputBytes = RedactionPipeline.finalize(reloaded, literalTargets, patterns);
|
||||
}
|
||||
}
|
||||
|
||||
try (PDDocument reopened = Loader.loadPDF(outputBytes)) {
|
||||
String extracted = new PDFTextStripper().getText(reopened);
|
||||
String lower = extracted == null ? "" : extracted.toLowerCase(Locale.ROOT);
|
||||
assertFalse(
|
||||
lower.contains("secret"),
|
||||
"Target term must not be extractable after redact on synthetic PDF. Extracted: '"
|
||||
+ extracted
|
||||
+ "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
-1019
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
@@ -1,118 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a minimal OpenType-CFF (.otf) font for a CIDFontType0 redaction fixture.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
Real-world Adobe/InDesign PDFs embed CFF-based CID fonts (Type0 -> CIDFontType0,
|
||||
program in /FontFile3 /Subtype /CIDFontType0C). PDFBox 3.0.7 can *read* those but
|
||||
ships NO CFF embedder: every PDType0Font.load(...) overload routes CFF outlines
|
||||
through the TrueType path (which either rejects "TTF using CFF outlines" or, via the
|
||||
OTFParser+TrueTypeFont overload, emits a CIDFontType2 and then fails to subset CFF
|
||||
because there is no glyf table). So to build a genuine CIDFontType0 fixture you must:
|
||||
1. generate the CFF .otf with fontTools (this script), and
|
||||
2. assemble the Type0/CIDFontType0 dictionary by hand, attaching the raw CFF table
|
||||
as /FontFile3 /Subtype /CIDFontType0C (see the companion Java harness).
|
||||
|
||||
This script emits BOTH minimal_cff.otf and cff_raw.bin (the raw CFF table bytes,
|
||||
ready to drop into /FontFile3).
|
||||
|
||||
Glyph coverage: only the ASCII letters in "PUBLICA SECRETWORD KEEP"
|
||||
(P U B L I C A S E R T W O D K) plus .notdef and space. Outlines are trivial filled
|
||||
boxes; only the cmap / encoding correctness matters so the drawn text extracts.
|
||||
"""
|
||||
import sys
|
||||
from fontTools.fontBuilder import FontBuilder
|
||||
from fontTools.pens.t2CharStringPen import T2CharStringPen
|
||||
from fontTools.ttLib import TTFont
|
||||
|
||||
UPM = 1000
|
||||
LETTERS = sorted(set("PUBLICASECRETWORDKEEP")) # A B C D E I K L O P R S T U W
|
||||
|
||||
|
||||
def box_charstring(width=600, height=700):
|
||||
"""A simple filled rectangle as a Type2 (CFF) charstring."""
|
||||
pen = T2CharStringPen(width, None)
|
||||
pen.moveTo((50, 0))
|
||||
pen.lineTo((width - 50, 0))
|
||||
pen.lineTo((width - 50, height))
|
||||
pen.lineTo((50, height))
|
||||
pen.closePath()
|
||||
return pen.getCharString()
|
||||
|
||||
|
||||
def build_otf(out_otf):
|
||||
# GID order: .notdef (GID 0), space (GID 1), then the letters. The companion
|
||||
# harness relies on this exact order for its Identity-H CID==GID mapping.
|
||||
glyph_order = [".notdef", "space"] + list(LETTERS)
|
||||
|
||||
fb = FontBuilder(unitsPerEm=UPM, isTTF=False) # isTTF=False -> CFF/OTF
|
||||
fb.setupGlyphOrder(glyph_order)
|
||||
|
||||
# Unicode cmap: codepoint -> glyph name. PDFBox reads this to build /ToUnicode,
|
||||
# and it also lets any consumer resolve the glyphs by character.
|
||||
cmap = {0x20: "space"}
|
||||
for c in LETTERS:
|
||||
cmap[ord(c)] = c
|
||||
fb.setupCharacterMap(cmap)
|
||||
|
||||
charstrings = {
|
||||
".notdef": box_charstring(),
|
||||
"space": box_charstring(width=250, height=0), # empty advance-only glyph
|
||||
}
|
||||
for c in LETTERS:
|
||||
charstrings[c] = box_charstring()
|
||||
|
||||
fb.setupCFF(
|
||||
psName="MinimalCFFCID",
|
||||
charStringsDict=charstrings,
|
||||
fontInfo={
|
||||
"FullName": "Minimal CFF CID",
|
||||
"FamilyName": "MinimalCFFCID",
|
||||
"Weight": "Regular",
|
||||
},
|
||||
privateDict={},
|
||||
)
|
||||
|
||||
metrics = {".notdef": (600, 50), "space": (250, 0)}
|
||||
for c in LETTERS:
|
||||
metrics[c] = (600, 50)
|
||||
fb.setupHorizontalMetrics(metrics)
|
||||
fb.setupHorizontalHeader(ascent=800, descent=-200)
|
||||
|
||||
fb.setupNameTable(
|
||||
{
|
||||
"familyName": "MinimalCFFCID",
|
||||
"styleName": "Regular",
|
||||
"psName": "MinimalCFFCID",
|
||||
"fullName": "Minimal CFF CID",
|
||||
"version": "Version 1.000",
|
||||
"uniqueFontIdentifier": "MinimalCFFCID;1.000",
|
||||
}
|
||||
)
|
||||
fb.setupOS2(
|
||||
sTypoAscender=800,
|
||||
sTypoDescender=-200,
|
||||
usWinAscent=800,
|
||||
usWinDescent=200,
|
||||
sCapHeight=700,
|
||||
)
|
||||
fb.setupPost(keepGlyphNames=True)
|
||||
|
||||
fb.save(out_otf)
|
||||
print("wrote", out_otf, "(", len(glyph_order), "glyphs )")
|
||||
|
||||
|
||||
def dump_cff(out_otf, out_cff):
|
||||
"""Extract the raw CFF table bytes for use as PDF /FontFile3."""
|
||||
f = TTFont(out_otf)
|
||||
cff = f["CFF "].compile(f)
|
||||
with open(out_cff, "wb") as fh:
|
||||
fh.write(cff)
|
||||
print("wrote", out_cff, "(", len(cff), "bytes CFF )")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
otf = sys.argv[1] if len(sys.argv) > 1 else "minimal_cff.otf"
|
||||
cffbin = sys.argv[2] if len(sys.argv) > 2 else "cff_raw.bin"
|
||||
build_otf(otf)
|
||||
dump_cff(otf, cffbin)
|
||||
@@ -1,114 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate a minimal TrueType font (.ttf) that covers exactly the characters
|
||||
needed for a CJK Type0 (Identity-H) redaction test:
|
||||
|
||||
- ASCII letters in "PUBLICA SECRETWORD KEEP": P U B L I C A S E R T W O D K + space
|
||||
- Two CJK ideographs used as the redaction target:
|
||||
U+79D8 (secret1) and U+5BC6 (secret2) -> "秘密"
|
||||
- .notdef
|
||||
|
||||
Glyph outlines are trivial boxes; the point of the test is that the cmap /
|
||||
encoding is correct so PDFBox can build a working /ToUnicode and the text is
|
||||
EXTRACTABLE. When PDFBox loads this via PDType0Font.load(doc, in, true) it
|
||||
becomes an Identity-H Type0 font with a CIDFontType2 descendant.
|
||||
|
||||
Usage: python gen_cjk_font.py <output.ttf>
|
||||
"""
|
||||
import sys
|
||||
from fontTools.fontBuilder import FontBuilder
|
||||
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
||||
|
||||
UPM = 1000
|
||||
|
||||
|
||||
def box_glyph(width_units):
|
||||
"""A trivial filled box outline so the glyph has real contours."""
|
||||
pen = TTGlyphPen(None)
|
||||
x0, y0, x1, y1 = 80, 0, max(120, width_units - 80), 700
|
||||
pen.moveTo((x0, y0))
|
||||
pen.lineTo((x0, y1))
|
||||
pen.lineTo((x1, y1))
|
||||
pen.lineTo((x1, y0))
|
||||
pen.closePath()
|
||||
return pen.glyph()
|
||||
|
||||
|
||||
def empty_glyph():
|
||||
return TTGlyphPen(None).glyph()
|
||||
|
||||
|
||||
def main(out_path):
|
||||
# Characters we must cover. Order defines glyph order (after .notdef).
|
||||
ascii_chars = list("PUBLICA SECRETWORD KEEP")
|
||||
ascii_unique = []
|
||||
for ch in ascii_chars:
|
||||
if ch not in ascii_unique:
|
||||
ascii_unique.append(ch)
|
||||
|
||||
cjk = ["秘", "密"] # 秘 密
|
||||
|
||||
# glyph name -> codepoint mapping
|
||||
def gname(cp):
|
||||
if cp == 0x20:
|
||||
return "space"
|
||||
return "uni%04X" % cp
|
||||
|
||||
codepoints = []
|
||||
for ch in ascii_unique:
|
||||
codepoints.append(ord(ch))
|
||||
for ch in cjk:
|
||||
codepoints.append(ord(ch))
|
||||
|
||||
glyph_order = [".notdef"] + [gname(cp) for cp in codepoints]
|
||||
|
||||
fb = FontBuilder(UPM, isTTF=True)
|
||||
fb.setupGlyphOrder(glyph_order)
|
||||
|
||||
# cmap: map every codepoint to its glyph. FontBuilder builds format-4
|
||||
# (BMP) + format-12 as needed. Both CJK codepoints are BMP so format-4
|
||||
# covers them.
|
||||
cmap = {cp: gname(cp) for cp in codepoints}
|
||||
fb.setupCharacterMap(cmap)
|
||||
|
||||
# Build glyf table with box outlines; advance widths.
|
||||
glyphs = {".notdef": empty_glyph()}
|
||||
metrics = {".notdef": (600, 0)}
|
||||
for cp in codepoints:
|
||||
name = gname(cp)
|
||||
if cp == 0x20:
|
||||
glyphs[name] = empty_glyph()
|
||||
metrics[name] = (300, 0) # space advance, no outline
|
||||
elif cp > 0x2000: # CJK -> full-width
|
||||
glyphs[name] = box_glyph(900)
|
||||
metrics[name] = (1000, 80)
|
||||
else:
|
||||
glyphs[name] = box_glyph(560)
|
||||
metrics[name] = (600, 80)
|
||||
|
||||
fb.setupGlyf(glyphs)
|
||||
fb.setupHorizontalMetrics(metrics)
|
||||
fb.setupHorizontalHeader(ascent=800, descent=-200)
|
||||
|
||||
# Names + the rest of the required tables.
|
||||
fb.setupNameTable({
|
||||
"familyName": "CJKRedactTest",
|
||||
"styleName": "Regular",
|
||||
"psName": "CJKRedactTest-Regular",
|
||||
"fullName": "CJKRedactTest Regular",
|
||||
})
|
||||
fb.setupOS2(sTypoAscender=800, sTypoDescender=-200, usWinAscent=800,
|
||||
usWinDescent=200)
|
||||
fb.setupPost()
|
||||
|
||||
fb.save(out_path)
|
||||
print("Wrote", out_path)
|
||||
print("Glyph order:", glyph_order)
|
||||
print("cmap entries:", {("U+%04X" % k): v for k, v in cmap.items()})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: gen_cjk_font.py <output.ttf>", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
main(sys.argv[1])
|
||||
@@ -1,128 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a minimal real Type1 font as a classic PFB (0x80 0x01 segment format).
|
||||
|
||||
Pure-python, uses fontTools.t1Lib.T1Font.createData() + writePFB. The font contains
|
||||
.notdef plus the ASCII letters needed for "PUBLICA SECRETWORD KEEP", with a proper
|
||||
Encoding array + standard PostScript glyph names. Because the glyph names are the
|
||||
standard ones and the PDF font uses WinAnsiEncoding, PDFBox extracts text via the
|
||||
base encoding (code -> glyphname -> Unicode); no /ToUnicode CMap is required.
|
||||
|
||||
Usage: python gen_type1.py <out.pfb>
|
||||
"""
|
||||
import sys
|
||||
from fontTools import t1Lib
|
||||
from fontTools.misc import psCharStrings
|
||||
|
||||
|
||||
# Glyph name for each character we must render. PostScript standard glyph names.
|
||||
CHARS = {
|
||||
"P": "P", "U": "U", "B": "B", "L": "L", "I": "I", "C": "C", "A": "A",
|
||||
"S": "S", "E": "E", "R": "R", "T": "T", "W": "W", "O": "O", "D": "D",
|
||||
"K": "K", " ": "space",
|
||||
}
|
||||
|
||||
EM = 1000
|
||||
WIDTH = 600
|
||||
BOX_L, BOX_B, BOX_R, BOX_T = 50, 0, 550, 700
|
||||
|
||||
|
||||
def box_charstring(width):
|
||||
"""A trivial filled box outline. hsbw sets sidebearing+width; then a closed rect."""
|
||||
prog = [
|
||||
0, width, "hsbw", # sb=0, width
|
||||
BOX_L, BOX_B, "rmoveto", # move to bottom-left (relative from 0,0)
|
||||
(BOX_R - BOX_L), "hlineto", # right
|
||||
(BOX_T - BOX_B), "vlineto", # up
|
||||
-(BOX_R - BOX_L), "hlineto", # left
|
||||
"closepath",
|
||||
"endchar",
|
||||
]
|
||||
cs = psCharStrings.T1CharString(program=prog)
|
||||
return cs
|
||||
|
||||
|
||||
def space_charstring(width):
|
||||
prog = [0, width, "hsbw", "endchar"]
|
||||
return psCharStrings.T1CharString(program=prog)
|
||||
|
||||
|
||||
def build_font(font_name="MinType1Test"):
|
||||
# 256-slot encoding, default .notdef, filled at each char's codepoint.
|
||||
encoding = [".notdef"] * 256
|
||||
for ch, gname in CHARS.items():
|
||||
encoding[ord(ch)] = gname
|
||||
|
||||
charstrings = {".notdef": box_charstring(WIDTH)}
|
||||
for ch, gname in CHARS.items():
|
||||
if gname == "space":
|
||||
charstrings[gname] = space_charstring(WIDTH)
|
||||
else:
|
||||
charstrings[gname] = box_charstring(WIDTH)
|
||||
|
||||
# Subrs: the 5 standard Type1 subrs (division/hint machinery). Provide as
|
||||
# T1CharString objects so createData can compile+encrypt them.
|
||||
subrs = [psCharStrings.T1CharString(bytecode=s) for s in t1Lib.std_subrs]
|
||||
|
||||
# Order matters. fontTools emits a stray "put" after the Subrs array; fontbox's
|
||||
# Type1Parser breaks its Private loop on the first non-LITERAL after Subrs, so
|
||||
# every key AFTER Subrs is dropped. Keep Subrs LAST so nothing gets skipped.
|
||||
private = {
|
||||
"RD": t1Lib.RD_value, # ('string','currentfile','exch','readstring','pop')
|
||||
"ND": t1Lib.ND_values[0], # ('def',) codespell:ignore
|
||||
"NP": t1Lib.PD_values[0], # ('put',)
|
||||
"MinFeature": [16, 16],
|
||||
# PDFBox reads BlueValues[2] for CapHeight, so >=3 entries required.
|
||||
# Pairs: baseline (0 0), then cap-height zone (700 712).
|
||||
"BlueValues": [0, 0, BOX_T, BOX_T + 12],
|
||||
"StdHW": [60],
|
||||
"StdVW": [80],
|
||||
"lenIV": 4,
|
||||
"password": 5839,
|
||||
"Subrs": subrs,
|
||||
}
|
||||
|
||||
font_info = {
|
||||
"version": "001.001",
|
||||
"FullName": font_name,
|
||||
"FamilyName": font_name,
|
||||
"Weight": "Regular",
|
||||
"ItalicAngle": 0,
|
||||
"isFixedPitch": False,
|
||||
"UnderlinePosition": -100,
|
||||
"UnderlineThickness": 50,
|
||||
}
|
||||
|
||||
font = {
|
||||
"FontName": font_name,
|
||||
"FontInfo": font_info,
|
||||
"FontType": 1,
|
||||
"PaintType": 0,
|
||||
"FontMatrix": [0.001, 0, 0, 0.001, 0, 0],
|
||||
"FontBBox": [0, 0, WIDTH, BOX_T],
|
||||
"Encoding": encoding,
|
||||
"Private": private,
|
||||
"CharStrings": charstrings,
|
||||
}
|
||||
return font
|
||||
|
||||
|
||||
def main():
|
||||
out = sys.argv[1] if len(sys.argv) > 1 else "min.pfb"
|
||||
# Construct a T1Font without reading a file, then hand-build .font.
|
||||
t1 = t1Lib.T1Font.__new__(t1Lib.T1Font)
|
||||
t1.encoding = "ascii"
|
||||
t1.font = build_font()
|
||||
data = t1.createData() # full ASCII+eexec Type1 program (binary eexec inline)
|
||||
t1.data = data
|
||||
t1.saveAs(out, "PFB") # split into 0x80 0x01 / 0x80 0x02 / 0x80 0x03 segments
|
||||
# Report first bytes to confirm PFB marker.
|
||||
with open(out, "rb") as f:
|
||||
head = f.read(6)
|
||||
print("WROTE", out)
|
||||
print("PFB head bytes:", " ".join(f"{b:02x}" for b in head))
|
||||
assert head[0] == 0x80 and head[1] == 0x01, "not a classic PFB 0x80 0x01 header"
|
||||
print("OK: classic PFB 0x80 0x01 ASCII segment marker present")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
+7
-5
@@ -7,7 +7,6 @@ import java.util.concurrent.Executor;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -28,6 +27,7 @@ import jakarta.validation.Valid;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.job.ResultFile;
|
||||
import stirling.software.common.service.JobOwnershipService;
|
||||
import stirling.software.common.service.TaskManager;
|
||||
@@ -63,12 +63,11 @@ public class AiEngineController {
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
/**
|
||||
* SSE emitter timeout. Long enough to accommodate multi-gigabyte PDF workflows (OCR on a
|
||||
* SSE emitter timeout in ms. Long enough to accommodate multi-gigabyte PDF workflows (OCR on a
|
||||
* 1000-page scan, splitting a huge PDF, etc.) without the emitter completing out from under the
|
||||
* executor. Configurable via {@code stirling.ai.streamTimeoutMs}.
|
||||
* executor. Derived from {@code aiEngine.streamTimeoutSeconds}.
|
||||
*/
|
||||
@Value("${stirling.ai.streamTimeoutMs:1800000}")
|
||||
private long streamTimeoutMs;
|
||||
private final long streamTimeoutMs;
|
||||
|
||||
public AiEngineController(
|
||||
AiEngineClient aiEngineClient,
|
||||
@@ -78,6 +77,7 @@ public class AiEngineController {
|
||||
TaskManager taskManager,
|
||||
JobOwnershipService jobOwnershipService,
|
||||
AiEngineEndpointResolver endpointResolver,
|
||||
ApplicationProperties applicationProperties,
|
||||
@Autowired(required = false) UserServiceInterface userService) {
|
||||
this.aiEngineClient = aiEngineClient;
|
||||
this.aiWorkflowService = aiWorkflowService;
|
||||
@@ -87,6 +87,8 @@ public class AiEngineController {
|
||||
this.jobOwnershipService = jobOwnershipService;
|
||||
this.endpointResolver = endpointResolver;
|
||||
this.userService = userService;
|
||||
this.streamTimeoutMs =
|
||||
applicationProperties.getAiEngine().getStreamTimeoutSeconds() * 1000L;
|
||||
}
|
||||
|
||||
private String currentUserId() {
|
||||
|
||||
+5
@@ -36,6 +36,7 @@ import stirling.software.proprietary.classification.store.ClassificationLabelSto
|
||||
import stirling.software.proprietary.model.api.ai.AiPageText;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.service.AiEngineClient;
|
||||
import stirling.software.proprietary.service.AiFeatureGate;
|
||||
import stirling.software.proprietary.service.PdfContentExtractor;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
@@ -68,6 +69,7 @@ public class ClassifyLabelController {
|
||||
private final PdfContentExtractor pdfContentExtractor;
|
||||
private final PdfMetadataService pdfMetadataService;
|
||||
private final AiEngineClient aiEngineClient;
|
||||
private final AiFeatureGate aiFeatureGate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
@@ -86,6 +88,7 @@ public class ClassifyLabelController {
|
||||
PdfContentExtractor pdfContentExtractor,
|
||||
PdfMetadataService pdfMetadataService,
|
||||
AiEngineClient aiEngineClient,
|
||||
AiFeatureGate aiFeatureGate,
|
||||
ObjectMapper objectMapper,
|
||||
@Autowired(required = false) UserServiceInterface userService,
|
||||
@Autowired(required = false) ClassificationLabelStore labelStore,
|
||||
@@ -95,6 +98,7 @@ public class ClassifyLabelController {
|
||||
this.pdfContentExtractor = pdfContentExtractor;
|
||||
this.pdfMetadataService = pdfMetadataService;
|
||||
this.aiEngineClient = aiEngineClient;
|
||||
this.aiFeatureGate = aiFeatureGate;
|
||||
this.objectMapper = objectMapper;
|
||||
this.userService = userService;
|
||||
this.labelStore = labelStore;
|
||||
@@ -111,6 +115,7 @@ public class ClassifyLabelController {
|
||||
+ " intended for direct client use.")
|
||||
public ResponseEntity<Resource> classifyAndLabel(
|
||||
@RequestParam("fileInput") MultipartFile fileInput) throws IOException {
|
||||
aiFeatureGate.requireClassify();
|
||||
try (PDDocument document = pdfDocumentFactory.load(fileInput, true)) {
|
||||
String fileName = safeFileName(fileInput.getOriginalFilename());
|
||||
|
||||
|
||||
+40
-4
@@ -43,6 +43,10 @@ public class IntegrationConfigService {
|
||||
private final OwnershipService ownership;
|
||||
private final SecretMasker secretMasker;
|
||||
private final ResourceGrantRepository grantRepository;
|
||||
// Bean-discovered extension points: features that understand a type contribute its config
|
||||
// schema and report what still references a config, without this module depending on them.
|
||||
private final List<IntegrationConfigValidator> validators;
|
||||
private final List<IntegrationConfigUsageCheck> usageChecks;
|
||||
|
||||
// ---- commands ----
|
||||
|
||||
@@ -66,13 +70,21 @@ public class IntegrationConfigService {
|
||||
? DefaultAccessPolicy.EXPLICIT_ONLY
|
||||
: request.defaultAccess());
|
||||
|
||||
// TEAM scope may omit the team id: default to the caller's own team so clients (the
|
||||
// portal) need not know it. assignOwnership still enforces admin-or-leader of that team.
|
||||
Long ownerTeamId = request.ownerTeamId();
|
||||
if (ownerTeamId == null && scope == OwnerScope.TEAM && currentUser.getTeam() != null) {
|
||||
ownerTeamId = currentUser.getTeam().getId();
|
||||
}
|
||||
ownership.assignOwnership(
|
||||
cfg,
|
||||
scope,
|
||||
request.ownerTeamId(),
|
||||
ownerTeamId,
|
||||
currentUser,
|
||||
() -> lockedServerExists(cfg.getIntegrationType()));
|
||||
cfg.setConfig(writeJson(secretMasker.sanitize(request.config())));
|
||||
Map<String, Object> config = secretMasker.sanitize(request.config());
|
||||
validateConfig(cfg.getIntegrationType(), config);
|
||||
cfg.setConfig(writeJson(config));
|
||||
return repository.save(cfg);
|
||||
}
|
||||
|
||||
@@ -101,8 +113,10 @@ public class IntegrationConfigService {
|
||||
cfg.setDefaultAccess(request.defaultAccess());
|
||||
}
|
||||
if (request.config() != null) {
|
||||
cfg.setConfig(
|
||||
writeJson(secretMasker.merge(readJson(cfg.getConfig()), request.config())));
|
||||
Map<String, Object> merged =
|
||||
secretMasker.merge(readJson(cfg.getConfig()), request.config());
|
||||
validateConfig(cfg.getIntegrationType(), merged);
|
||||
cfg.setConfig(writeJson(merged));
|
||||
}
|
||||
return repository.save(cfg);
|
||||
}
|
||||
@@ -113,6 +127,15 @@ public class IntegrationConfigService {
|
||||
if (!ownership.canManage(TYPE, cfg, currentUser)) {
|
||||
throw forbidden("You cannot manage this integration");
|
||||
}
|
||||
// Refuse to pull a connection out from under whatever still references it.
|
||||
List<String> usages =
|
||||
usageChecks.stream()
|
||||
.flatMap(check -> check.usagesOf(cfg.getId()).stream())
|
||||
.toList();
|
||||
if (!usages.isEmpty()) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.CONFLICT, "Integration is in use by: " + String.join(", ", usages));
|
||||
}
|
||||
// Drop grants sharing this config so they do not dangle as dead rows.
|
||||
grantRepository.deleteByResourceTypeAndResourceId(TYPE, String.valueOf(cfg.getId()));
|
||||
repository.delete(cfg);
|
||||
@@ -188,6 +211,19 @@ public class IntegrationConfigService {
|
||||
|
||||
// ---- integration-specific glue ----
|
||||
|
||||
/** Runs every registered validator for the type; unknown types save free-form. */
|
||||
private void validateConfig(IntegrationType type, Map<String, Object> config) {
|
||||
for (IntegrationConfigValidator validator : validators) {
|
||||
if (validator.type() == type) {
|
||||
try {
|
||||
validator.validate(config == null ? Map.of() : config);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A non-admin can't create a personal config of a type an admin has locked at server scope. */
|
||||
private boolean lockedServerExists(IntegrationType type) {
|
||||
return repository.findByScope(OwnerScope.SERVER).stream()
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package stirling.software.proprietary.integration.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Reports what still references an integration config, so deletion can be refused instead of
|
||||
* pulling a connection out from under a live consumer. Implementations are beans discovered by
|
||||
* {@link IntegrationConfigService} (e.g. the policy subsystem reporting sources and pipelines that
|
||||
* reference a connection).
|
||||
*/
|
||||
public interface IntegrationConfigUsageCheck {
|
||||
|
||||
/** Human-readable labels of everything still using the config; empty when unreferenced. */
|
||||
List<String> usagesOf(long configId);
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package stirling.software.proprietary.integration.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
|
||||
/**
|
||||
* Validates one integration type's config map at save time. Implementations are beans discovered by
|
||||
* {@link IntegrationConfigService}, so the feature that understands a type (e.g. the policy S3
|
||||
* backend) owns its schema without the integration module depending on it. Types with no registered
|
||||
* validator save free-form.
|
||||
*/
|
||||
public interface IntegrationConfigValidator {
|
||||
|
||||
/** The type this validator understands. */
|
||||
IntegrationType type();
|
||||
|
||||
/**
|
||||
* Validates the config as it will be stored (secrets already sanitized/merged, so values are
|
||||
* real, never the redaction mask). Throws {@link IllegalArgumentException} on bad config.
|
||||
*/
|
||||
void validate(Map<String, Object> config);
|
||||
}
|
||||
+20
@@ -120,6 +120,7 @@ public class PolicyController {
|
||||
throws IOException {
|
||||
stampPolicyAudit(definition);
|
||||
requireRunnable(definition);
|
||||
validateAdHocOutput(definition);
|
||||
PolicyInputs inputs = toInputs(files);
|
||||
PolicyRunHandle handle =
|
||||
policyRunner.runAdHoc(definition, inputs, PolicyProgressListener.NOOP);
|
||||
@@ -140,6 +141,7 @@ public class PolicyController {
|
||||
throws IOException {
|
||||
stampPolicyAudit(definition);
|
||||
requireRunnable(definition);
|
||||
validateAdHocOutput(definition);
|
||||
PolicyInputs inputs = toInputs(files);
|
||||
|
||||
SseEmitter emitter =
|
||||
@@ -530,6 +532,24 @@ public class PolicyController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization-check an ad-hoc run's output while the caller's principal is present (this
|
||||
* request thread). The worker thread that later delivers carries no security context, so an S3
|
||||
* output's connection-access check would be skipped there; without this gate a caller could
|
||||
* reference another tenant's connection by id and write to it (confused deputy). Stored
|
||||
* policies are covered by save-time {@link PolicyValidator#validate} instead.
|
||||
*/
|
||||
private void validateAdHocOutput(PipelineDefinition definition) {
|
||||
if (definition.output() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
policyValidator.validateOutput(definition.output());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ad-hoc runs (AI / one-off pipelines) are still editor activity, so their supplied documents
|
||||
* feed the same virtual editor source as stored editor policies, counted against the caller's
|
||||
|
||||
+13
-1
@@ -52,7 +52,19 @@ public class PolicyValidator {
|
||||
InputSpec spec = source.toInputSpec();
|
||||
inputSourceFor(spec).validate(spec);
|
||||
}
|
||||
outputSinkFor(policy.output()).validate(policy.output());
|
||||
validateOutput(policy.output());
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an output spec against its sink. Must be called on a request thread (caller's
|
||||
* principal present) so an S3 output's connection is authorization-checked against the caller -
|
||||
* ad-hoc runs are never persisted and so never hit {@link #validate(Policy)}, and the worker
|
||||
* thread that later delivers has no principal, so this is their only access gate.
|
||||
*
|
||||
* @throws IllegalArgumentException if the type is unknown or the config is invalid/inaccessible
|
||||
*/
|
||||
public void validateOutput(OutputSpec output) {
|
||||
outputSinkFor(output).validate(output);
|
||||
}
|
||||
|
||||
private PolicyTrigger triggerFor(TriggerConfig config) {
|
||||
|
||||
+14
-13
@@ -18,6 +18,7 @@ import stirling.software.proprietary.policy.model.InputSpec;
|
||||
import stirling.software.proprietary.policy.model.PolicyInputs;
|
||||
import stirling.software.proprietary.policy.s3.S3Config;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionResolver;
|
||||
import stirling.software.proprietary.policy.s3.S3Identities;
|
||||
|
||||
import software.amazon.awssdk.core.exception.SdkException;
|
||||
@@ -36,15 +37,14 @@ import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
* Reads input files from an Amazon S3 (or S3-compatible) bucket; each listed object is its own unit
|
||||
* of work, claimed through the {@link ResolveContext} ledger and tracked in place. Identity and
|
||||
* version gate come from {@link S3Identities}, so the steady-state sweep never downloads content.
|
||||
* Options (see {@link S3Config}): "bucket" (required), "region" (default us-east-1), "prefix" (only
|
||||
* keys starting with it are read), "endpoint" (S3-compatible stores such as MinIO; path-style
|
||||
* addressing is used automatically), "accessKeyId" and "secretAccessKey" (required; requests are
|
||||
* never signed with the server's own AWS identity), and "mode" which is "consume" (default: a
|
||||
* processed object is deleted once every policy that claimed it has settled successfully and it is
|
||||
* still the version that ran; failures stay in place and are not retried until they change) or
|
||||
* "snapshot" (stateless, every run sees the full set). Keys ending in "/" (folder placeholders) and
|
||||
* keys with a dot-prefixed path segment are never picked up, mirroring the folder source's
|
||||
* hidden-file rule.
|
||||
* Options: "connectionId" references the stored S3 connection (an {@code IntegrationConfig} owning
|
||||
* bucket, region, endpoint, and credentials - resolved by {@link S3ConnectionResolver}); "prefix"
|
||||
* (only keys starting with it are read) and "mode" are per-source, where mode is "consume"
|
||||
* (default: a processed object is deleted once every policy that claimed it has settled
|
||||
* successfully and it is still the version that ran; failures stay in place and are not retried
|
||||
* until they change) or "snapshot" (stateless, every run sees the full set). Keys ending in "/"
|
||||
* (folder placeholders) and keys with a dot-prefixed path segment are never picked up, mirroring
|
||||
* the folder source's hidden-file rule.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -55,6 +55,7 @@ public class S3InputSource implements InputSource {
|
||||
private static final String TYPE = "s3";
|
||||
|
||||
private final S3ConnectionPool connectionPool;
|
||||
private final S3ConnectionResolver connectionResolver;
|
||||
|
||||
@Override
|
||||
public String type() {
|
||||
@@ -67,12 +68,12 @@ public class S3InputSource implements InputSource {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails fast at save time: bad config shape, a private endpoint without the operator opt-in, or
|
||||
* a bucket the supplied credentials cannot list.
|
||||
* Fails fast at save time: an unknown/disabled/unusable connection, bad config shape, a private
|
||||
* endpoint without the operator opt-in, or a bucket the connection cannot list.
|
||||
*/
|
||||
@Override
|
||||
public void validate(InputSpec spec) {
|
||||
S3Config config = S3Config.from(spec.options());
|
||||
S3Config config = connectionResolver.resolve(spec.options());
|
||||
try {
|
||||
connectionPool.clientFor(config).listObjectsV2(listRequest(config).maxKeys(1).build());
|
||||
} catch (SdkException e) {
|
||||
@@ -89,7 +90,7 @@ public class S3InputSource implements InputSource {
|
||||
|
||||
@Override
|
||||
public List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {
|
||||
S3Config config = S3Config.from(spec.options());
|
||||
S3Config config = connectionResolver.resolve(spec.options());
|
||||
S3Client client = connectionPool.clientFor(config);
|
||||
// A listing failure propagates so the sweep reads it as "could not list" (which vetoes
|
||||
// presence cleanup), never as "verifiably no objects".
|
||||
|
||||
+7
-5
@@ -27,6 +27,7 @@ import stirling.software.proprietary.policy.ledger.ProcessedLedger;
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.s3.S3Config;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionResolver;
|
||||
import stirling.software.proprietary.policy.s3.S3Identities;
|
||||
|
||||
import software.amazon.awssdk.core.exception.SdkException;
|
||||
@@ -59,6 +60,7 @@ public class S3OutputSink implements PolicyOutputSink {
|
||||
private static final String TYPE = "s3";
|
||||
|
||||
private final S3ConnectionPool connectionPool;
|
||||
private final S3ConnectionResolver connectionResolver;
|
||||
private final ProcessedLedger processedLedger;
|
||||
|
||||
@Override
|
||||
@@ -72,19 +74,19 @@ public class S3OutputSink implements PolicyOutputSink {
|
||||
}
|
||||
|
||||
/**
|
||||
* Config shape and endpoint guard only - no network probe, since write-only credentials
|
||||
* (s3:PutObject without s3:ListBucket) are a legitimate setup for an output bucket and a
|
||||
* listing probe would wrongly reject them.
|
||||
* Connection resolution (including the saving user's right to use it) and endpoint guard only -
|
||||
* no network probe, since write-only credentials (s3:PutObject without s3:ListBucket) are a
|
||||
* legitimate setup for an output bucket and a listing probe would wrongly reject them.
|
||||
*/
|
||||
@Override
|
||||
public void validate(OutputSpec spec) {
|
||||
connectionPool.clientFor(S3Config.from(spec.options()));
|
||||
connectionPool.clientFor(connectionResolver.resolve(spec.options()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResultFile> deliver(
|
||||
OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {
|
||||
S3Config config = S3Config.from(spec.options());
|
||||
S3Config config = connectionResolver.resolve(spec.options());
|
||||
S3Client client = connectionPool.clientFor(config);
|
||||
|
||||
List<ResultFile> results = new ArrayList<>();
|
||||
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.integration.model.IntegrationConfig;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.model.Policy;
|
||||
import stirling.software.proprietary.policy.source.Source;
|
||||
import stirling.software.proprietary.policy.source.SourceStore;
|
||||
import stirling.software.proprietary.policy.store.PolicyStore;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* One-time, idempotent extraction of legacy embedded S3 credentials into stored connections:
|
||||
* sources and policy outputs written before connections shipped carry bucket/credentials in their
|
||||
* own options; this rewrites each to reference a (deduplicated) S3 {@link IntegrationConfig} and
|
||||
* keeps only per-use options (prefix, mode). MUST be programmatic - the option JSON is encrypted at
|
||||
* the application layer, so no SQL migration can read it.
|
||||
*
|
||||
* <p>Idempotent by construction: rewritten rows no longer embed credentials, so re-runs find
|
||||
* nothing to do. Connections are deduplicated against both this run's extractions and existing S3
|
||||
* connections; a concurrent multi-node boot can at worst create a redundant connection row, never
|
||||
* corrupt a source. Ownership follows the owning row: team-scoped when the source/policy has a
|
||||
* team, server-scoped otherwise (single-operator self-hosted).
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class EmbeddedS3CredentialMigration {
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private static final List<String> CONNECTION_OPTIONS =
|
||||
List.of("bucket", "region", "endpoint", "accessKeyId", "secretAccessKey");
|
||||
// Field separator for the dedup key: a unit-separator control char that cannot appear in a
|
||||
// bucket/region/endpoint/credential, so distinct field sets can never collide.
|
||||
private static final char DELIMITER = '\u001f';
|
||||
|
||||
private final SourceStore sourceStore;
|
||||
private final PolicyStore policyStore;
|
||||
private final IntegrationConfigRepository connections;
|
||||
private final TeamRepository teamRepository;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Transactional
|
||||
public void migrate() {
|
||||
Map<String, IntegrationConfig> byCredentialKey = indexExistingConnections();
|
||||
int migrated = 0;
|
||||
for (Source source : sourceStore.all()) {
|
||||
if (!"s3".equals(source.type()) || !embedsCredentials(source.options())) {
|
||||
continue;
|
||||
}
|
||||
IntegrationConfig connection =
|
||||
connectionFor(source.options(), source.teamId(), byCredentialKey);
|
||||
sourceStore.save(withOptions(source, referencing(connection, source.options(), true)));
|
||||
migrated++;
|
||||
}
|
||||
for (Policy policy : policyStore.all()) {
|
||||
OutputSpec output = policy.output();
|
||||
if (!"s3".equals(output.type()) || !embedsCredentials(output.options())) {
|
||||
continue;
|
||||
}
|
||||
IntegrationConfig connection =
|
||||
connectionFor(output.options(), policy.teamId(), byCredentialKey);
|
||||
policyStore.save(
|
||||
withOutput(
|
||||
policy,
|
||||
new OutputSpec(
|
||||
output.type(),
|
||||
referencing(connection, output.options(), false))));
|
||||
migrated++;
|
||||
}
|
||||
if (migrated > 0) {
|
||||
log.info("Extracted embedded S3 credentials from {} row(s) into connections", migrated);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean embedsCredentials(Map<String, Object> options) {
|
||||
return options.get("accessKeyId") != null;
|
||||
}
|
||||
|
||||
/** Reuses an existing connection with identical coordinates+credentials, else creates one. */
|
||||
private IntegrationConfig connectionFor(
|
||||
Map<String, Object> options, Long teamId, Map<String, IntegrationConfig> byKey) {
|
||||
String key = credentialKey(options);
|
||||
IntegrationConfig existing = byKey.get(key);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
IntegrationConfig connection = new IntegrationConfig();
|
||||
connection.setIntegrationType(IntegrationType.S3);
|
||||
connection.setName(connectionName(options, byKey));
|
||||
connection.setEnabled(true);
|
||||
connection.setLocked(false);
|
||||
connection.setDefaultAccess(DefaultAccessPolicy.EXPLICIT_ONLY);
|
||||
Team team = teamId == null ? null : teamRepository.findById(teamId).orElse(null);
|
||||
if (team != null) {
|
||||
connection.setScope(OwnerScope.TEAM);
|
||||
connection.setOwnerTeam(team);
|
||||
} else {
|
||||
// No team (teamless self-hosted, or a source whose team was since deleted): server
|
||||
// scope, i.e. admin-owned. An orphaned-team source's non-admin editor would then need
|
||||
// an admin to re-share the connection - acceptable for the narrow orphaned case.
|
||||
connection.setScope(OwnerScope.SERVER);
|
||||
}
|
||||
Map<String, Object> config = new LinkedHashMap<>();
|
||||
for (String option : CONNECTION_OPTIONS) {
|
||||
Object value = options.get(option);
|
||||
if (value != null && !value.toString().isBlank()) {
|
||||
config.put(option, value);
|
||||
}
|
||||
}
|
||||
connection.setConfig(OBJECT_MAPPER.writeValueAsString(config));
|
||||
IntegrationConfig saved = connections.save(connection);
|
||||
byKey.put(key, saved);
|
||||
return saved;
|
||||
}
|
||||
|
||||
/** The rewritten options: the connection reference plus per-use settings only. */
|
||||
private static Map<String, Object> referencing(
|
||||
IntegrationConfig connection, Map<String, Object> legacy, boolean keepMode) {
|
||||
Map<String, Object> options = new LinkedHashMap<>();
|
||||
options.put(S3ConnectionResolver.CONNECTION_ID_OPTION, connection.getId());
|
||||
Object prefix = legacy.get("prefix");
|
||||
if (prefix != null && !prefix.toString().isBlank()) {
|
||||
options.put("prefix", prefix);
|
||||
}
|
||||
Object mode = legacy.get("mode");
|
||||
if (keepMode && mode != null && !mode.toString().isBlank()) {
|
||||
options.put("mode", mode);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
private Map<String, IntegrationConfig> indexExistingConnections() {
|
||||
Map<String, IntegrationConfig> byKey = new LinkedHashMap<>();
|
||||
for (IntegrationConfig connection : connections.findAll()) {
|
||||
if (connection.getIntegrationType() != IntegrationType.S3) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
Map<String, Object> config =
|
||||
OBJECT_MAPPER.readValue(connection.getConfig(), Map.class);
|
||||
byKey.putIfAbsent(credentialKey(config), connection);
|
||||
} catch (Exception e) {
|
||||
log.debug(
|
||||
"Skipping unreadable S3 connection {} while indexing: {}",
|
||||
connection.getId(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
return byKey;
|
||||
}
|
||||
|
||||
private static String credentialKey(Map<String, Object> options) {
|
||||
StringBuilder key = new StringBuilder();
|
||||
for (String option : CONNECTION_OPTIONS) {
|
||||
Object value = options.get(option);
|
||||
key.append(value == null ? "" : value.toString().trim()).append(DELIMITER);
|
||||
}
|
||||
return key.toString();
|
||||
}
|
||||
|
||||
private static String connectionName(
|
||||
Map<String, Object> options, Map<String, IntegrationConfig> byKey) {
|
||||
String base = "S3: " + options.getOrDefault("bucket", "bucket");
|
||||
long sameName = byKey.values().stream().filter(c -> c.getName().startsWith(base)).count();
|
||||
return sameName == 0 ? base : base + " (" + (sameName + 1) + ")";
|
||||
}
|
||||
|
||||
private static Source withOptions(Source source, Map<String, Object> options) {
|
||||
return new Source(
|
||||
source.id(),
|
||||
source.name(),
|
||||
source.type(),
|
||||
options,
|
||||
source.enabled(),
|
||||
source.owner(),
|
||||
source.teamId());
|
||||
}
|
||||
|
||||
private static Policy withOutput(Policy policy, OutputSpec output) {
|
||||
return new Policy(
|
||||
policy.id(),
|
||||
policy.name(),
|
||||
policy.owner(),
|
||||
policy.enabled(),
|
||||
policy.trigger(),
|
||||
policy.sourceIds(),
|
||||
policy.steps(),
|
||||
output,
|
||||
policy.teamId());
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.integration.service.IntegrationConfigUsageCheck;
|
||||
import stirling.software.proprietary.policy.model.Policy;
|
||||
import stirling.software.proprietary.policy.source.Source;
|
||||
import stirling.software.proprietary.policy.source.SourceStore;
|
||||
import stirling.software.proprietary.policy.store.PolicyStore;
|
||||
|
||||
/**
|
||||
* Reports the policy sources and pipeline outputs referencing an S3 connection, so the connection
|
||||
* cannot be deleted out from under them (mirrors {@code SourceController}'s referenced-source
|
||||
* delete guard). Scans in memory - fine at admin-dashboard scale, always consistent with the live
|
||||
* stores.
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class PolicyS3ConnectionUsageCheck implements IntegrationConfigUsageCheck {
|
||||
|
||||
private final SourceStore sourceStore;
|
||||
private final PolicyStore policyStore;
|
||||
|
||||
@Override
|
||||
public List<String> usagesOf(long configId) {
|
||||
List<String> usages = new ArrayList<>();
|
||||
for (Source source : sourceStore.all()) {
|
||||
if (references(source.options(), configId)) {
|
||||
usages.add("source '" + source.name() + "'");
|
||||
}
|
||||
}
|
||||
for (Policy policy : policyStore.all()) {
|
||||
if (references(policy.output().options(), configId)) {
|
||||
usages.add("pipeline '" + policy.name() + "'");
|
||||
}
|
||||
}
|
||||
return usages;
|
||||
}
|
||||
|
||||
private static boolean references(Map<String, Object> options, long configId) {
|
||||
try {
|
||||
Long reference = S3ConnectionResolver.connectionId(options);
|
||||
return reference != null && reference == configId;
|
||||
} catch (IllegalArgumentException unparseable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import java.net.URISyntaxException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Connection settings shared by the S3 input source and output sink, parsed from a spec's options
|
||||
* map. Credentials are required: there is deliberately no fallback to the server's own AWS
|
||||
* credential chain, so user-supplied config can never borrow the host's identity. {@code snapshot}
|
||||
* is input-only and ignored by the sink.
|
||||
* The fully resolved connection settings the S3 input source and output sink run with - normally
|
||||
* produced by {@link S3ConnectionResolver} merging a stored connection (bucket, region, endpoint,
|
||||
* credentials) with per-use options (prefix, mode), or parsed directly from legacy options that
|
||||
* still embed credentials. Credentials are required: there is deliberately no fallback to the
|
||||
* server's own AWS credential chain, so user-supplied config can never borrow the host's identity.
|
||||
* {@code snapshot} is input-only and ignored by the sink.
|
||||
*/
|
||||
public record S3Config(
|
||||
String bucket,
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
import stirling.software.proprietary.access.service.OwnershipService;
|
||||
import stirling.software.proprietary.integration.model.IntegrationConfig;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Turns a source's or output's options into a full {@link S3Config} by dereferencing its {@code
|
||||
* connectionId} to a stored S3 {@link IntegrationConfig} (the connection owns bucket, region,
|
||||
* endpoint, and credentials; the options own per-use settings such as prefix and mode). Options
|
||||
* with no {@code connectionId} fall back to legacy embedded credentials, so rows written before
|
||||
* connections shipped keep working until {@link EmbeddedS3CredentialMigration} rewrites them.
|
||||
*
|
||||
* <p>When an authenticated caller is present (save-time validation), they must be allowed to use
|
||||
* the connection. Background sweeps and deliveries run with no caller and skip that check: the
|
||||
* referencing source or policy was access-checked when it was saved.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class S3ConnectionResolver {
|
||||
|
||||
static final String CONNECTION_ID_OPTION = "connectionId";
|
||||
private static final String PREFIX_OPTION = "prefix";
|
||||
private static final String MODE_OPTION = "mode";
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
private final IntegrationConfigRepository connections;
|
||||
private final OwnershipService ownership;
|
||||
private final UserService userService;
|
||||
|
||||
public S3Config resolve(Map<String, Object> options) {
|
||||
Long connectionId = connectionId(options);
|
||||
if (connectionId == null) {
|
||||
// Legacy embedded credentials, pending migration.
|
||||
return S3Config.from(options);
|
||||
}
|
||||
IntegrationConfig connection =
|
||||
connections
|
||||
.findById(connectionId)
|
||||
.filter(cfg -> cfg.getIntegrationType() == IntegrationType.S3)
|
||||
.filter(this::usableByCurrentUser)
|
||||
// Existence and access collapse into one error: a caller must not be able
|
||||
// to tell "no such connection" from "someone else's connection" and
|
||||
// enumerate ids. The id/name are never echoed.
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new IllegalArgumentException(
|
||||
"unknown or inaccessible s3 connection"));
|
||||
if (!connection.isEnabled()) {
|
||||
throw new IllegalArgumentException("s3 connection is disabled");
|
||||
}
|
||||
Map<String, Object> merged = new LinkedHashMap<>(connectionConfig(connection));
|
||||
copyPerUseOption(options, merged, PREFIX_OPTION);
|
||||
copyPerUseOption(options, merged, MODE_OPTION);
|
||||
return S3Config.from(merged);
|
||||
}
|
||||
|
||||
/** The {@code connectionId} option as a long, or null when the options are legacy-embedded. */
|
||||
static Long connectionId(Map<String, Object> options) {
|
||||
Object reference = options.get(CONNECTION_ID_OPTION);
|
||||
if (reference == null || (reference instanceof String s && s.isBlank())) {
|
||||
return null;
|
||||
}
|
||||
if (reference instanceof Number number) {
|
||||
return number.longValue();
|
||||
}
|
||||
try {
|
||||
return Long.valueOf(reference.toString().trim());
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"s3 'connectionId' is not a valid connection reference: " + reference);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the current caller may use this connection. With no principal - a background sweep or
|
||||
* delivery on a worker thread that carries no {@code SecurityContext} - access is treated as
|
||||
* already established: stored policies are validated with the caller present at save time, and
|
||||
* ad-hoc runs are validated on the request thread before dispatch (see {@code
|
||||
* PolicyValidator#validateOutput}). A missing principal must therefore never be the ONLY thing
|
||||
* standing between a caller and a connection, or the check becomes a confused deputy.
|
||||
*/
|
||||
private boolean usableByCurrentUser(IntegrationConfig connection) {
|
||||
User user = currentUser();
|
||||
return user == null || ownership.canUse(ResourceType.INTEGRATION_CONFIG, connection, user);
|
||||
}
|
||||
|
||||
// Mirrors ResourceAccessSecurity's principal resolution; null when unauthenticated.
|
||||
private User currentUser() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
return null;
|
||||
}
|
||||
Object principal = auth.getPrincipal();
|
||||
if (principal instanceof User user) {
|
||||
return user;
|
||||
}
|
||||
if (principal instanceof UserDetails userDetails) {
|
||||
return userService.findByUsername(userDetails.getUsername()).orElse(null);
|
||||
}
|
||||
if (principal instanceof String username && !"anonymousUser".equals(username)) {
|
||||
return userService.findByUsername(username).orElse(null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Map<String, Object> connectionConfig(IntegrationConfig connection) {
|
||||
String json = connection.getConfig();
|
||||
if (json == null || json.isBlank()) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(
|
||||
json, new TypeReference<LinkedHashMap<String, Object>>() {});
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(
|
||||
"s3 connection '" + connection.getName() + "' has unreadable config", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void copyPerUseOption(
|
||||
Map<String, Object> options, Map<String, Object> merged, String key) {
|
||||
Object value = options.get(key);
|
||||
if (value != null && !value.toString().isBlank()) {
|
||||
merged.put(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.cluster.s3.S3Clients;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
import stirling.software.proprietary.integration.service.IntegrationConfigValidator;
|
||||
|
||||
/**
|
||||
* The S3 connection schema, enforced when an S3 {@link IntegrationType} config is saved: bucket and
|
||||
* credentials required, endpoint an http(s) URL that must not reach private addresses without the
|
||||
* operator opt-in - the same rules {@link S3ConnectionPool} enforces before signing, moved to save
|
||||
* time so a bad connection fails in the form rather than in a sweep.
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class S3IntegrationValidator implements IntegrationConfigValidator {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
@Override
|
||||
public IntegrationType type() {
|
||||
return IntegrationType.S3;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Map<String, Object> config) {
|
||||
S3Config parsed = S3Config.from(config);
|
||||
if (parsed.endpoint() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
S3Clients.validateEndpointHost(
|
||||
URI.create(parsed.endpoint()),
|
||||
applicationProperties.getPolicies().isAllowPrivateS3Endpoints(),
|
||||
"S3 connection endpoint",
|
||||
"set policies.allowPrivateS3Endpoints=true to opt in (e.g. for a local"
|
||||
+ " MinIO).");
|
||||
} catch (IllegalStateException e) {
|
||||
throw new IllegalArgumentException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
-2
@@ -8,6 +8,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -45,6 +46,7 @@ import stirling.software.common.util.RegexPatternUtils;
|
||||
import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;
|
||||
import stirling.software.proprietary.service.AiEngineConfigSync;
|
||||
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
@@ -58,6 +60,7 @@ public class AdminSettingsController {
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ApplicationContext applicationContext;
|
||||
private final AiEngineConfigSync aiEngineConfigSync;
|
||||
|
||||
// Track settings that have been modified but not yet applied (require restart)
|
||||
private static final ConcurrentHashMap<String, Object> pendingChanges =
|
||||
@@ -172,6 +175,28 @@ public class AdminSettingsController {
|
||||
.body(Map.of("error", "No settings provided to update"));
|
||||
}
|
||||
|
||||
// Work on a mutable copy so the removal below works even if the caller passed an
|
||||
// immutable map, then drop masked sensitive values so a UI round-trip never overwrites
|
||||
// a real secret (e.g. an API key) with the "********" placeholder from the GET
|
||||
// response.
|
||||
settings = new LinkedHashMap<>(settings);
|
||||
settings.entrySet()
|
||||
.removeIf(
|
||||
e -> {
|
||||
if (!"********".equals(e.getValue())) {
|
||||
return false;
|
||||
}
|
||||
String key = e.getKey();
|
||||
String leaf =
|
||||
key.contains(".")
|
||||
? key.substring(key.lastIndexOf('.') + 1)
|
||||
: key;
|
||||
return isSensitiveFieldWithPath(leaf, key);
|
||||
});
|
||||
if (settings.isEmpty()) {
|
||||
return ResponseEntity.ok(Map.of("message", "No changed settings to update."));
|
||||
}
|
||||
|
||||
// Validate all settings first before applying any changes
|
||||
for (Map.Entry<String, Object> entry : settings.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
@@ -206,6 +231,10 @@ public class AdminSettingsController {
|
||||
pendingChanges.put(key, value != null ? value : "");
|
||||
}
|
||||
|
||||
// If AI settings changed, push them to the engine live so model/RAG/limit changes
|
||||
// apply without waiting for a processor restart.
|
||||
maybePushAiEngineLive();
|
||||
|
||||
return ResponseEntity.ok(
|
||||
Map.of(
|
||||
"message",
|
||||
@@ -600,6 +629,23 @@ public class AdminSettingsController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward any pending {@code aiEngine.*} changes to the AI engine immediately. The running bean
|
||||
* overlaid with these pending values is the current settings.yml state; {@link
|
||||
* AiEngineConfigSync} no-ops unless AI is enabled and an engine-relevant key changed.
|
||||
*/
|
||||
private void maybePushAiEngineLive() {
|
||||
Map<String, Object> aiEnginePending = new HashMap<>();
|
||||
for (Map.Entry<String, Object> entry : pendingChanges.entrySet()) {
|
||||
if (entry.getKey().startsWith("aiEngine.")) {
|
||||
aiEnginePending.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
if (!aiEnginePending.isEmpty()) {
|
||||
aiEngineConfigSync.pushLiveAfterSave(aiEnginePending);
|
||||
}
|
||||
}
|
||||
|
||||
private Object getSectionData(String sectionName) {
|
||||
if (sectionName == null || sectionName.trim().isEmpty()) {
|
||||
return null;
|
||||
@@ -843,8 +889,13 @@ public class AdminSettingsController {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for fields containing 'password' or 'secret'
|
||||
return lowerField.contains("password") || lowerField.contains("secret");
|
||||
// Substring match for secret-bearing field names. Covers provider credentials such as
|
||||
// aiEngine.models.apiKey and aiEngine.rag.embeddingApiKey (which the exact-name set would
|
||||
// miss) so keys are never returned to the client in cleartext.
|
||||
return lowerField.contains("password")
|
||||
|| lowerField.contains("secret")
|
||||
|| lowerField.contains("apikey")
|
||||
|| lowerField.contains("token");
|
||||
}
|
||||
|
||||
/** Create a masked representation for sensitive fields */
|
||||
|
||||
@@ -103,7 +103,6 @@ public class User implements UserDetails, Serializable {
|
||||
|
||||
@ElementCollection
|
||||
@MapKeyColumn(name = "setting_key")
|
||||
@Lob
|
||||
@Column(name = "setting_value", columnDefinition = "text")
|
||||
@CollectionTable(name = "user_settings", joinColumns = @JoinColumn(name = "user_id"))
|
||||
@JsonIgnore
|
||||
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.AiEngine;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* Pushes the admin-configured AI settings (model provider/name, per-provider API key, RAG choices,
|
||||
* limits) to the Python engine so a self-hosted deployment can drive the engine's model and API key
|
||||
* from the Stirling settings UI. Pushed on processor startup and again live whenever AI settings
|
||||
* are saved (so model/RAG/limit changes apply without a restart). The engine applies it live
|
||||
* (rebuilds its models) and caches it, so it self-restores on its own reboot. Empty
|
||||
* key/baseUrl/model fields mean "keep the engine's own environment credential".
|
||||
*
|
||||
* <p>Gated by {@code aiEngine.pushConfigToEngine} (default true). Environment-driven deployments
|
||||
* pin it false (SaaS does so in application-saas.properties) so the engine stays entirely
|
||||
* env-controlled and the processor never pushes settings-derived config to it. Best-effort and
|
||||
* non-blocking: a slow or unreachable engine never delays or fails Stirling startup.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AiEngineConfigSync {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 5;
|
||||
private static final long RETRY_DELAY_MS = 3000L;
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final AiEngineClient aiEngineClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void pushConfigOnStartup() {
|
||||
AiEngine cfg = applicationProperties.getAiEngine();
|
||||
if (!cfg.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (!cfg.isPushConfigToEngine()) {
|
||||
log.debug(
|
||||
"Skipping AI engine config push: aiEngine.pushConfigToEngine is disabled"
|
||||
+ " (the engine is configured from its own environment)");
|
||||
return;
|
||||
}
|
||||
// Engine may still be booting; push on a virtual thread with a few retries so we never
|
||||
// block or crash Stirling startup when the engine is slow or briefly unreachable.
|
||||
Thread.ofVirtual().name("ai-engine-config-sync").start(() -> pushWithRetries(cfg));
|
||||
}
|
||||
|
||||
/**
|
||||
* Push AI settings to the engine immediately after an admin save so model/RAG/limit changes
|
||||
* reach the engine without waiting for a processor restart. {@code pendingAiEngine} are the
|
||||
* pending {@code aiEngine.*} dot-notation changes; the running bean overlaid with these is the
|
||||
* current settings.yml state. No-op unless AI is enabled and an engine-relevant key changed.
|
||||
*/
|
||||
public void pushLiveAfterSave(Map<String, Object> pendingAiEngine) {
|
||||
// Gate on the RUNNING bean: AiEngineClient refuses calls while the bean is disabled, so
|
||||
// pushing on a pending-but-not-restarted enable would always fail. The post-restart
|
||||
// startup push covers first-time enablement.
|
||||
AiEngine cfg = applicationProperties.getAiEngine();
|
||||
if (pendingAiEngine == null
|
||||
|| pendingAiEngine.isEmpty()
|
||||
|| !cfg.isPushConfigToEngine()
|
||||
|| !cfg.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
boolean engineRelevant =
|
||||
pendingAiEngine.keySet().stream().anyMatch(AiEngineConfigSync::isEngineRelevantKey);
|
||||
if (!engineRelevant) {
|
||||
return;
|
||||
}
|
||||
ObjectNode node = buildConfigNode(cfg);
|
||||
pendingAiEngine.forEach((k, v) -> overlayIfEngineRelevant(node, k, v));
|
||||
String body = node.toString();
|
||||
Thread.ofVirtual().name("ai-engine-config-live-push").start(() -> pushOnce(body));
|
||||
}
|
||||
|
||||
private void pushOnce(String body) {
|
||||
try {
|
||||
aiEngineClient.post("/api/v1/config", body, null);
|
||||
log.info("Pushed AI engine configuration after settings change");
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"Live AI engine config push failed: {} (will re-sync on next restart)",
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Only models/rag/limits are forwarded to the engine; enabled/url/timeouts/features are
|
||||
// processor-side and don't need a live engine push.
|
||||
private static boolean isEngineRelevantKey(String key) {
|
||||
return key.startsWith("aiEngine.models.")
|
||||
|| key.startsWith("aiEngine.rag.")
|
||||
|| key.startsWith("aiEngine.limits.");
|
||||
}
|
||||
|
||||
private void overlayIfEngineRelevant(ObjectNode node, String key, Object value) {
|
||||
if (!isEngineRelevantKey(key)) {
|
||||
return;
|
||||
}
|
||||
String[] parts = key.substring("aiEngine.".length()).split("\\.");
|
||||
ObjectNode parent = node;
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
JsonNode child = parent.get(parts[i]);
|
||||
parent = (child instanceof ObjectNode on) ? on : parent.putObject(parts[i]);
|
||||
}
|
||||
parent.set(parts[parts.length - 1], objectMapper.valueToTree(value));
|
||||
}
|
||||
|
||||
private void pushWithRetries(AiEngine cfg) {
|
||||
String body = buildConfigNode(cfg).toString();
|
||||
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
aiEngineClient.post("/api/v1/config", body, null);
|
||||
log.info("Pushed AI engine configuration on startup (attempt {})", attempt);
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"AI engine config push failed (attempt {}/{}): {}",
|
||||
attempt,
|
||||
MAX_ATTEMPTS,
|
||||
e.getMessage());
|
||||
if (attempt < MAX_ATTEMPTS) {
|
||||
try {
|
||||
Thread.sleep(RETRY_DELAY_MS);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
log.warn(
|
||||
"Giving up pushing AI engine configuration after {} attempts; the engine will use"
|
||||
+ " its own environment configuration until the next restart.",
|
||||
MAX_ATTEMPTS);
|
||||
}
|
||||
|
||||
private ObjectNode buildConfigNode(AiEngine cfg) {
|
||||
AiEngine.Models m = cfg.getModels();
|
||||
AiEngine.Rag r = cfg.getRag();
|
||||
AiEngine.Limits l = cfg.getLimits();
|
||||
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
|
||||
ObjectNode models = root.putObject("models");
|
||||
models.put("provider", m.getProvider());
|
||||
models.put("smartModel", m.getSmartModel());
|
||||
models.put("fastModel", m.getFastModel());
|
||||
models.put("smartMaxTokens", m.getSmartMaxTokens());
|
||||
models.put("fastMaxTokens", m.getFastMaxTokens());
|
||||
models.put("apiKey", m.getApiKey());
|
||||
models.put("baseUrl", m.getBaseUrl());
|
||||
|
||||
ObjectNode rag = root.putObject("rag");
|
||||
rag.put("embeddingProvider", r.getEmbeddingProvider());
|
||||
rag.put("embeddingModel", r.getEmbeddingModel());
|
||||
rag.put("embeddingApiKey", r.getEmbeddingApiKey());
|
||||
rag.put("embeddingBaseUrl", r.getEmbeddingBaseUrl());
|
||||
rag.put("topK", r.getTopK());
|
||||
rag.put("maxSearches", r.getMaxSearches());
|
||||
|
||||
ObjectNode limits = root.putObject("limits");
|
||||
limits.put("maxPages", l.getMaxPages());
|
||||
limits.put("maxCharacters", l.getMaxCharacters());
|
||||
limits.put("modelMaxConcurrency", l.getModelMaxConcurrency());
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.AiEngine.Features;
|
||||
|
||||
/**
|
||||
* Central gate for the per-capability AI feature switches ({@code aiEngine.features.*}). Each AI
|
||||
* capability entry point calls the matching {@code require*} method so an admin who turns a feature
|
||||
* off in the settings UI gets a clean 503 instead of the request silently reaching the engine. All
|
||||
* checks also fail closed when the AI engine itself is disabled.
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AiFeatureGate {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
private Features features() {
|
||||
return applicationProperties.getAiEngine().getFeatures();
|
||||
}
|
||||
|
||||
private void require(boolean featureEnabled, String feature) {
|
||||
if (!applicationProperties.getAiEngine().isEnabled() || !featureEnabled) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.SERVICE_UNAVAILABLE, "AI feature '" + feature + "' is disabled");
|
||||
}
|
||||
}
|
||||
|
||||
public void requireChat() {
|
||||
require(features().isChat(), "chat");
|
||||
}
|
||||
|
||||
public void requireDocumentQuestions() {
|
||||
require(features().isDocumentQuestions(), "documentQuestions");
|
||||
}
|
||||
|
||||
public void requireCreatePdf() {
|
||||
require(features().isCreatePdf(), "createPdf");
|
||||
}
|
||||
|
||||
public void requireMathAuditor() {
|
||||
require(features().isMathAuditor(), "mathAuditor");
|
||||
}
|
||||
|
||||
public void requirePdfComment() {
|
||||
require(features().isPdfComment(), "pdfComment");
|
||||
}
|
||||
|
||||
public void requireClassify() {
|
||||
require(features().isClassify(), "classify");
|
||||
}
|
||||
}
|
||||
+3
@@ -32,6 +32,7 @@ import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
import stirling.software.proprietary.classification.store.InProcessClassificationLabelStore;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.service.AiEngineClient;
|
||||
import stirling.software.proprietary.service.AiFeatureGate;
|
||||
import stirling.software.proprietary.service.PdfContentExtractor;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
@@ -49,6 +50,7 @@ class ClassifyLabelControllerTest {
|
||||
@Mock private PdfContentExtractor pdfContentExtractor;
|
||||
@Mock private PdfMetadataService pdfMetadataService;
|
||||
@Mock private AiEngineClient aiEngineClient;
|
||||
@Mock private AiFeatureGate aiFeatureGate;
|
||||
@Mock private PolicyManagementAuthority policyManagementAuthority;
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder().build();
|
||||
@@ -65,6 +67,7 @@ class ClassifyLabelControllerTest {
|
||||
pdfContentExtractor,
|
||||
pdfMetadataService,
|
||||
aiEngineClient,
|
||||
aiFeatureGate,
|
||||
objectMapper,
|
||||
null,
|
||||
labelStore,
|
||||
|
||||
+53
-2
@@ -13,9 +13,9 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.springframework.http.HttpStatus;
|
||||
@@ -52,7 +52,58 @@ class IntegrationConfigServiceTest {
|
||||
@Mock
|
||||
private stirling.software.proprietary.access.repository.ResourceGrantRepository grantRepository;
|
||||
|
||||
@InjectMocks private IntegrationConfigService service;
|
||||
@Mock private IntegrationConfigValidator validator;
|
||||
@Mock private IntegrationConfigUsageCheck usageCheck;
|
||||
|
||||
private IntegrationConfigService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service =
|
||||
new IntegrationConfigService(
|
||||
repository,
|
||||
ownership,
|
||||
secretMasker,
|
||||
grantRepository,
|
||||
List.of(validator),
|
||||
List.of(usageCheck));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsAConfigItsTypeValidatorRefuses() {
|
||||
when(secretMasker.sanitize(any())).thenReturn(Map.of());
|
||||
when(validator.type()).thenReturn(IntegrationType.API);
|
||||
org.mockito.Mockito.doThrow(new IllegalArgumentException("api config needs a 'url'"))
|
||||
.when(validator)
|
||||
.validate(any());
|
||||
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
service.create(
|
||||
request(IntegrationType.API, OwnerScope.USER, null),
|
||||
user(7)))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(
|
||||
e ->
|
||||
assertThat(((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRefusedWhileAnythingStillReferencesTheConfig() {
|
||||
IntegrationConfig cfg = config(9L);
|
||||
when(repository.findById(9L)).thenReturn(Optional.of(cfg));
|
||||
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(true);
|
||||
when(usageCheck.usagesOf(9L)).thenReturn(List.of("source 'Claims intake'"));
|
||||
|
||||
assertThatThrownBy(() -> service.delete(9L, user(7)))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(
|
||||
e ->
|
||||
assertThat(((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.CONFLICT));
|
||||
verify(repository, org.mockito.Mockito.never()).delete(any(IntegrationConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDelegatesOwnershipAndSanitizesConfig() {
|
||||
|
||||
+24
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -194,6 +195,29 @@ class PolicyControllerTest {
|
||||
assertThat(((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects an ad-hoc output the caller cannot use, on the request thread")
|
||||
void rejectsUnauthorizedAdHocOutput() {
|
||||
// The confused-deputy guard: an S3 output referencing a connection the caller may not
|
||||
// use is validated here (principal present) and refused before any worker dispatch.
|
||||
PipelineDefinition definition =
|
||||
new PipelineDefinition(
|
||||
"pipe",
|
||||
List.of(new PipelineStep("/api/v1/misc/compress-pdf", null)),
|
||||
new OutputSpec("s3", Map.of("connectionId", 999)));
|
||||
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
|
||||
.when(policyValidator)
|
||||
.validateOutput(any());
|
||||
|
||||
assertThatThrownBy(() -> controller.run(definition, new PolicyRunFiles()))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(
|
||||
e ->
|
||||
assertThat(((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
verify(policyRunner, never()).runAdHoc(any(), any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
+22
@@ -82,6 +82,28 @@ class PolicyValidatorTest {
|
||||
assertTrue(ex.getMessage().contains("schedule"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateOutputDelegatesToTheSink() {
|
||||
when(outputSink.supports(any())).thenReturn(true);
|
||||
OutputSpec output = new OutputSpec("s3", Map.of("connectionId", 1));
|
||||
|
||||
validator.validateOutput(output);
|
||||
|
||||
verify(outputSink).validate(output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateOutputSurfacesAnInaccessibleConnection() {
|
||||
when(outputSink.supports(any())).thenReturn(true);
|
||||
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
|
||||
.when(outputSink)
|
||||
.validate(any());
|
||||
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> validator.validateOutput(new OutputSpec("s3", Map.of("connectionId", 1))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnUnknownTriggerType() {
|
||||
when(trigger.type()).thenReturn("schedule");
|
||||
|
||||
+7
-2
@@ -23,6 +23,7 @@ import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
|
||||
import stirling.software.proprietary.policy.model.InputSpec;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
|
||||
import stirling.software.proprietary.policy.s3.S3TestConnections;
|
||||
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
@@ -82,7 +83,9 @@ class S3InputSourceMinioTest {
|
||||
// The MinIO endpoint resolves to loopback, so the operator opt-in must be on.
|
||||
ApplicationProperties properties = new ApplicationProperties();
|
||||
properties.getPolicies().setAllowPrivateS3Endpoints(true);
|
||||
source = new S3InputSource(new S3ConnectionPool(properties));
|
||||
source =
|
||||
new S3InputSource(
|
||||
new S3ConnectionPool(properties), S3TestConnections.legacyResolver());
|
||||
ledger = new InProcessProcessedLedger();
|
||||
ctx = new RecordingContext();
|
||||
}
|
||||
@@ -161,7 +164,9 @@ class S3InputSourceMinioTest {
|
||||
@Test
|
||||
void aPrivateEndpointIsRejectedWithoutTheOperatorOptIn() {
|
||||
S3InputSource guarded =
|
||||
new S3InputSource(new S3ConnectionPool(new ApplicationProperties()));
|
||||
new S3InputSource(
|
||||
new S3ConnectionPool(new ApplicationProperties()),
|
||||
S3TestConnections.legacyResolver());
|
||||
|
||||
assertThatThrownBy(() -> guarded.validate(spec(Map.of())))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
|
||||
+3
-1
@@ -29,6 +29,7 @@ import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
|
||||
import stirling.software.proprietary.policy.model.InputSpec;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
|
||||
import stirling.software.proprietary.policy.s3.S3TestConnections;
|
||||
|
||||
import software.amazon.awssdk.core.ResponseInputStream;
|
||||
import software.amazon.awssdk.core.exception.SdkClientException;
|
||||
@@ -64,7 +65,8 @@ class S3InputSourceTest {
|
||||
void setUp() {
|
||||
source =
|
||||
new S3InputSource(
|
||||
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client));
|
||||
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client),
|
||||
S3TestConnections.legacyResolver());
|
||||
ledger = new InProcessProcessedLedger();
|
||||
ctx = new RecordingContext();
|
||||
}
|
||||
|
||||
+3
-2
@@ -28,6 +28,7 @@ import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
|
||||
import stirling.software.proprietary.policy.model.InputSpec;
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
|
||||
import stirling.software.proprietary.policy.s3.S3TestConnections;
|
||||
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
@@ -90,8 +91,8 @@ class S3OutputSinkMinioTest {
|
||||
properties.getPolicies().setAllowPrivateS3Endpoints(true);
|
||||
S3ConnectionPool pool = new S3ConnectionPool(properties);
|
||||
ledger = new InProcessProcessedLedger();
|
||||
sink = new S3OutputSink(pool, ledger);
|
||||
source = new S3InputSource(pool);
|
||||
sink = new S3OutputSink(pool, S3TestConnections.legacyResolver(), ledger);
|
||||
source = new S3InputSource(pool, S3TestConnections.legacyResolver());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
@@ -32,6 +32,7 @@ import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
|
||||
import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
|
||||
import stirling.software.proprietary.policy.s3.S3TestConnections;
|
||||
|
||||
import software.amazon.awssdk.awscore.exception.AwsServiceException;
|
||||
import software.amazon.awssdk.core.exception.SdkClientException;
|
||||
@@ -66,6 +67,7 @@ class S3OutputSinkTest {
|
||||
sink =
|
||||
new S3OutputSink(
|
||||
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client),
|
||||
S3TestConnections.legacyResolver(),
|
||||
ledger);
|
||||
}
|
||||
|
||||
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.integration.model.IntegrationConfig;
|
||||
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.model.PipelineStep;
|
||||
import stirling.software.proprietary.policy.model.Policy;
|
||||
import stirling.software.proprietary.policy.source.InProcessSourceStore;
|
||||
import stirling.software.proprietary.policy.source.Source;
|
||||
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
|
||||
/**
|
||||
* Tests for {@link EmbeddedS3CredentialMigration}: legacy embedded credentials become deduplicated
|
||||
* team-scoped connections, rewritten rows keep only per-use options, and re-runs are no-ops.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EmbeddedS3CredentialMigrationTest {
|
||||
|
||||
@Mock private IntegrationConfigRepository connections;
|
||||
@Mock private TeamRepository teamRepository;
|
||||
|
||||
private final InProcessSourceStore sourceStore = new InProcessSourceStore();
|
||||
private final InProcessPolicyStore policyStore = new InProcessPolicyStore();
|
||||
private EmbeddedS3CredentialMigration migration;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
migration =
|
||||
new EmbeddedS3CredentialMigration(
|
||||
sourceStore, policyStore, connections, teamRepository);
|
||||
AtomicLong ids = new AtomicLong(100);
|
||||
// Lenient: the nothing-to-migrate cases never create a connection.
|
||||
lenient().when(connections.findAll()).thenReturn(List.of());
|
||||
lenient()
|
||||
.when(connections.save(any()))
|
||||
.thenAnswer(
|
||||
invocation -> {
|
||||
IntegrationConfig saved = invocation.getArgument(0);
|
||||
if (saved.getId() == null) {
|
||||
saved.setId(ids.incrementAndGet());
|
||||
}
|
||||
return saved;
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractsSharedCredentialsIntoOneTeamScopedConnection() {
|
||||
Team team = new Team();
|
||||
team.setId(7L);
|
||||
when(teamRepository.findById(7L)).thenReturn(Optional.of(team));
|
||||
Source source =
|
||||
sourceStore.save(
|
||||
new Source(
|
||||
null,
|
||||
"Claims intake",
|
||||
"s3",
|
||||
Map.of(
|
||||
"bucket", "inbox",
|
||||
"prefix", "incoming/",
|
||||
"mode", "snapshot",
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh"),
|
||||
true,
|
||||
"alice",
|
||||
7L));
|
||||
Policy policy =
|
||||
policyStore.save(
|
||||
new Policy(
|
||||
null,
|
||||
"Rotate",
|
||||
"alice",
|
||||
true,
|
||||
null,
|
||||
List.of(source.id()),
|
||||
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
|
||||
new OutputSpec(
|
||||
"s3",
|
||||
Map.of(
|
||||
"bucket", "inbox",
|
||||
"prefix", "processed/",
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh")),
|
||||
7L));
|
||||
|
||||
migration.migrate();
|
||||
|
||||
// Same bucket + credentials on both rows: exactly one connection extracted.
|
||||
verify(connections, times(1)).save(any());
|
||||
Map<String, Object> sourceOptions = sourceStore.get(source.id()).orElseThrow().options();
|
||||
assertEquals(101L, sourceOptions.get("connectionId"));
|
||||
assertEquals("incoming/", sourceOptions.get("prefix"));
|
||||
assertEquals("snapshot", sourceOptions.get("mode"));
|
||||
assertNull(sourceOptions.get("accessKeyId"));
|
||||
assertNull(sourceOptions.get("secretAccessKey"));
|
||||
assertNull(sourceOptions.get("bucket"));
|
||||
|
||||
Map<String, Object> outputOptions =
|
||||
policyStore.get(policy.id()).orElseThrow().output().options();
|
||||
assertEquals(101L, outputOptions.get("connectionId"));
|
||||
assertEquals("processed/", outputOptions.get("prefix"));
|
||||
assertNull(outputOptions.get("secretAccessKey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionOwnershipFollowsTheSourceTeam() {
|
||||
Team team = new Team();
|
||||
team.setId(7L);
|
||||
when(teamRepository.findById(7L)).thenReturn(Optional.of(team));
|
||||
sourceStore.save(s3Source("teamed", 7L));
|
||||
|
||||
migration.migrate();
|
||||
|
||||
verify(connections)
|
||||
.save(
|
||||
org.mockito.ArgumentMatchers.argThat(
|
||||
connection ->
|
||||
connection.getScope() == OwnerScope.TEAM
|
||||
&& connection.getOwnerTeam() == team));
|
||||
}
|
||||
|
||||
@Test
|
||||
void teamlessRowsBecomeServerScopedConnections() {
|
||||
sourceStore.save(s3Source("solo", null));
|
||||
|
||||
migration.migrate();
|
||||
|
||||
verify(connections)
|
||||
.save(
|
||||
org.mockito.ArgumentMatchers.argThat(
|
||||
connection -> connection.getScope() == OwnerScope.SERVER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecondRunFindsNothingToDo() {
|
||||
sourceStore.save(s3Source("once", null));
|
||||
|
||||
migration.migrate();
|
||||
migration.migrate();
|
||||
|
||||
// One connection from the first run; the rewritten source no longer embeds credentials.
|
||||
verify(connections, times(1)).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonS3AndAlreadyMigratedRowsAreUntouched() {
|
||||
Source folder =
|
||||
sourceStore.save(
|
||||
new Source(
|
||||
null,
|
||||
"Folder",
|
||||
"folder",
|
||||
Map.of("directory", "/in"),
|
||||
true,
|
||||
"alice",
|
||||
null));
|
||||
Source migrated =
|
||||
sourceStore.save(
|
||||
new Source(
|
||||
null,
|
||||
"Done already",
|
||||
"s3",
|
||||
Map.of("connectionId", 55L, "prefix", "in/"),
|
||||
true,
|
||||
"alice",
|
||||
null));
|
||||
|
||||
migration.migrate();
|
||||
|
||||
verify(connections, times(0)).save(any());
|
||||
assertEquals(
|
||||
Map.of("directory", "/in"), sourceStore.get(folder.id()).orElseThrow().options());
|
||||
assertEquals(
|
||||
Map.of("connectionId", 55L, "prefix", "in/"),
|
||||
sourceStore.get(migrated.id()).orElseThrow().options());
|
||||
}
|
||||
|
||||
private static Source s3Source(String name, Long teamId) {
|
||||
return new Source(
|
||||
null,
|
||||
name,
|
||||
"s3",
|
||||
Map.of(
|
||||
"bucket", "inbox",
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh"),
|
||||
true,
|
||||
"alice",
|
||||
teamId);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import stirling.software.proprietary.policy.model.OutputSpec;
|
||||
import stirling.software.proprietary.policy.model.PipelineStep;
|
||||
import stirling.software.proprietary.policy.model.Policy;
|
||||
import stirling.software.proprietary.policy.source.InProcessSourceStore;
|
||||
import stirling.software.proprietary.policy.source.Source;
|
||||
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
|
||||
|
||||
/** Tests for {@link PolicyS3ConnectionUsageCheck}'s reference scan across sources and outputs. */
|
||||
class PolicyS3ConnectionUsageCheckTest {
|
||||
|
||||
private final InProcessSourceStore sourceStore = new InProcessSourceStore();
|
||||
private final InProcessPolicyStore policyStore = new InProcessPolicyStore();
|
||||
private final PolicyS3ConnectionUsageCheck check =
|
||||
new PolicyS3ConnectionUsageCheck(sourceStore, policyStore);
|
||||
|
||||
@Test
|
||||
void reportsSourcesAndOutputsReferencingTheConnection() {
|
||||
sourceStore.save(
|
||||
new Source(
|
||||
null,
|
||||
"Claims intake",
|
||||
"s3",
|
||||
Map.of("connectionId", 5L, "prefix", "in/"),
|
||||
true,
|
||||
"alice",
|
||||
null));
|
||||
policyStore.save(
|
||||
new Policy(
|
||||
null,
|
||||
"Rotate",
|
||||
"alice",
|
||||
true,
|
||||
null,
|
||||
List.of(),
|
||||
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
|
||||
new OutputSpec("s3", Map.of("connectionId", "5")),
|
||||
null));
|
||||
|
||||
assertThat(check.usagesOf(5))
|
||||
.containsExactlyInAnyOrder("source 'Claims intake'", "pipeline 'Rotate'");
|
||||
assertThat(check.usagesOf(6)).isEmpty();
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import stirling.software.proprietary.access.service.OwnershipService;
|
||||
import stirling.software.proprietary.integration.model.IntegrationConfig;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
/**
|
||||
* Tests for {@link S3ConnectionResolver}: connection dereferencing with per-use overrides, the
|
||||
* legacy embedded fallback, and the save-time access check that background sweeps skip.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class S3ConnectionResolverTest {
|
||||
|
||||
@Mock private IntegrationConfigRepository connections;
|
||||
@Mock private OwnershipService ownership;
|
||||
@Mock private UserService userService;
|
||||
|
||||
@AfterEach
|
||||
void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesAConnectionAndMergesPerUseOptions() {
|
||||
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
|
||||
|
||||
S3Config config =
|
||||
resolver()
|
||||
.resolve(
|
||||
Map.of(
|
||||
"connectionId", 9L,
|
||||
"prefix", "incoming/",
|
||||
"mode", "snapshot"));
|
||||
|
||||
assertEquals("inbox", config.bucket());
|
||||
assertEquals("AKIAEXAMPLE", config.accessKeyId());
|
||||
assertEquals("incoming/", config.prefix());
|
||||
assertTrue(config.snapshot());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsAStringConnectionReference() {
|
||||
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
|
||||
|
||||
assertEquals("inbox", resolver().resolve(Map.of("connectionId", "9")).bucket());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToLegacyEmbeddedCredentials() {
|
||||
S3Config config =
|
||||
resolver()
|
||||
.resolve(
|
||||
Map.of(
|
||||
"bucket", "legacy",
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh"));
|
||||
|
||||
assertEquals("legacy", config.bucket());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnknownDisabledOrWrongTypeConnections() {
|
||||
when(connections.findById(1L)).thenReturn(Optional.empty());
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> resolver().resolve(Map.of("connectionId", 1L)));
|
||||
|
||||
when(connections.findById(2L)).thenReturn(Optional.of(s3Connection(2L, false)));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> resolver().resolve(Map.of("connectionId", 2L)));
|
||||
|
||||
IntegrationConfig mcp = s3Connection(3L, true);
|
||||
mcp.setIntegrationType(IntegrationType.MCP);
|
||||
when(connections.findById(3L)).thenReturn(Optional.of(mcp));
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> resolver().resolve(Map.of("connectionId", 3L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAuthenticatedSaverMustBeAllowedToUseTheConnection() {
|
||||
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
|
||||
User saver = new User();
|
||||
saver.setUsername("alice");
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(saver, null, java.util.List.of()));
|
||||
when(ownership.canUse(any(), any(IntegrationConfig.class), eq(saver))).thenReturn(false);
|
||||
|
||||
// Denied reads the same as unknown and never echoes the connection name, so ids can't be
|
||||
// enumerated by probing.
|
||||
assertThrows(
|
||||
IllegalArgumentException.class,
|
||||
() -> resolver().resolve(Map.of("connectionId", 9L)));
|
||||
try {
|
||||
resolver().resolve(Map.of("connectionId", 9L));
|
||||
} catch (IllegalArgumentException e) {
|
||||
org.junit.jupiter.api.Assertions.assertFalse(
|
||||
e.getMessage().contains("Claims bucket"),
|
||||
"access-denied error must not leak the connection name");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void backgroundSweepsWithNoUserSkipTheAccessCheck() {
|
||||
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
|
||||
|
||||
// No authentication in the context: resolution succeeds without consulting ownership.
|
||||
assertEquals("inbox", resolver().resolve(Map.of("connectionId", 9L)).bucket());
|
||||
}
|
||||
|
||||
private S3ConnectionResolver resolver() {
|
||||
return new S3ConnectionResolver(connections, ownership, userService);
|
||||
}
|
||||
|
||||
private static IntegrationConfig s3Connection(long id, boolean enabled) {
|
||||
IntegrationConfig connection = new IntegrationConfig();
|
||||
connection.setId(id);
|
||||
connection.setIntegrationType(IntegrationType.S3);
|
||||
connection.setName("Claims bucket");
|
||||
connection.setEnabled(enabled);
|
||||
connection.setConfig(
|
||||
"{\"bucket\":\"inbox\",\"accessKeyId\":\"AKIAEXAMPLE\","
|
||||
+ "\"secretAccessKey\":\"shh\"}");
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
|
||||
/**
|
||||
* Tests for {@link S3IntegrationValidator}: the S3 connection schema fails at save time - missing
|
||||
* credentials, bad endpoints, and private endpoints without the operator opt-in.
|
||||
*/
|
||||
class S3IntegrationValidatorTest {
|
||||
|
||||
@Test
|
||||
void acceptsACompleteConnection() {
|
||||
assertThatCode(
|
||||
() ->
|
||||
validator(false)
|
||||
.validate(
|
||||
Map.of(
|
||||
"bucket", "inbox",
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh")))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingCredentialsOrBucket() {
|
||||
assertThatThrownBy(() -> validator(false).validate(Map.of("bucket", "inbox")))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
validator(false)
|
||||
.validate(
|
||||
Map.of(
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh")))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAPrivateEndpointWithoutTheOperatorOptIn() {
|
||||
Map<String, Object> config =
|
||||
Map.of(
|
||||
"bucket", "inbox",
|
||||
"accessKeyId", "AKIAEXAMPLE",
|
||||
"secretAccessKey", "shh",
|
||||
"endpoint", "http://localhost:9000");
|
||||
|
||||
assertThatThrownBy(() -> validator(false).validate(config))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("allowPrivateS3Endpoints");
|
||||
assertThatCode(() -> validator(true).validate(config)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void itOnlyClaimsTheS3Type() {
|
||||
org.junit.jupiter.api.Assertions.assertEquals(IntegrationType.S3, validator(false).type());
|
||||
}
|
||||
|
||||
private static S3IntegrationValidator validator(boolean allowPrivateEndpoints) {
|
||||
ApplicationProperties properties = new ApplicationProperties();
|
||||
properties.getPolicies().setAllowPrivateS3Endpoints(allowPrivateEndpoints);
|
||||
return new S3IntegrationValidator(properties);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package stirling.software.proprietary.policy.s3;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import stirling.software.proprietary.access.service.OwnershipService;
|
||||
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
/** Test fixtures for S3 connection plumbing shared across the policy S3 tests. */
|
||||
public final class S3TestConnections {
|
||||
|
||||
private S3TestConnections() {}
|
||||
|
||||
/**
|
||||
* A resolver for tests whose options embed credentials directly (the legacy pass-through path),
|
||||
* so its collaborators are never touched.
|
||||
*/
|
||||
public static S3ConnectionResolver legacyResolver() {
|
||||
return new S3ConnectionResolver(
|
||||
mock(IntegrationConfigRepository.class),
|
||||
mock(OwnershipService.class),
|
||||
mock(UserService.class));
|
||||
}
|
||||
}
|
||||
+55
-1
@@ -1,10 +1,13 @@
|
||||
package stirling.software.proprietary.security.controller.api;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -26,6 +29,7 @@ import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;
|
||||
import stirling.software.proprietary.service.AiEngineConfigSync;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
@@ -37,6 +41,7 @@ class AdminSettingsControllerTest {
|
||||
private ApplicationProperties applicationProperties;
|
||||
private ObjectMapper objectMapper;
|
||||
private ApplicationContext applicationContext;
|
||||
private AiEngineConfigSync aiEngineConfigSync;
|
||||
|
||||
private AdminSettingsController controller;
|
||||
|
||||
@@ -45,9 +50,13 @@ class AdminSettingsControllerTest {
|
||||
applicationProperties = new ApplicationProperties();
|
||||
objectMapper = JsonMapper.builder().build();
|
||||
applicationContext = org.mockito.Mockito.mock(ApplicationContext.class);
|
||||
aiEngineConfigSync = org.mockito.Mockito.mock(AiEngineConfigSync.class);
|
||||
controller =
|
||||
new AdminSettingsController(
|
||||
applicationProperties, objectMapper, applicationContext);
|
||||
applicationProperties,
|
||||
objectMapper,
|
||||
applicationContext,
|
||||
aiEngineConfigSync);
|
||||
clearPendingChanges();
|
||||
}
|
||||
|
||||
@@ -277,6 +286,51 @@ class AdminSettingsControllerTest {
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("drops a masked ******** secret so a UI round-trip can't overwrite a real key")
|
||||
void dropsMaskedSecretValue() {
|
||||
UpdateSettingsRequest request = new UpdateSettingsRequest();
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("aiEngine.models.apiKey", "********");
|
||||
settings.put("ui.appName", "My App");
|
||||
request.setSettings(settings);
|
||||
|
||||
try (MockedStatic<GeneralUtils> mocked = mockStatic(GeneralUtils.class)) {
|
||||
ResponseEntity<Map<String, Object>> response = controller.updateSettings(request);
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
// The masked secret is stripped; only the real change is persisted.
|
||||
mocked.verify(
|
||||
() ->
|
||||
GeneralUtils.updateSettingsTransactional(
|
||||
argThat(
|
||||
(Map<String, Object> m) ->
|
||||
!m.containsKey("aiEngine.models.apiKey")
|
||||
&& m.containsKey("ui.appName"))));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("forwards only aiEngine.* pending keys to the engine live-push")
|
||||
void forwardsOnlyAiEngineKeysToLivePush() {
|
||||
UpdateSettingsRequest request = new UpdateSettingsRequest();
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("aiEngine.models.provider", "ollama");
|
||||
settings.put("ui.appName", "My App");
|
||||
request.setSettings(settings);
|
||||
|
||||
try (MockedStatic<GeneralUtils> mocked = mockStatic(GeneralUtils.class)) {
|
||||
controller.updateSettings(request);
|
||||
|
||||
verify(aiEngineConfigSync)
|
||||
.pushLiveAfterSave(
|
||||
argThat(
|
||||
(Map<String, Object> m) ->
|
||||
m.containsKey("aiEngine.models.provider")
|
||||
&& !m.containsKey("ui.appName")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.AiEngine;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The config-push bridge is a self-hosted-only feature: it lets the admin UI drive the engine's
|
||||
* model/key/RAG/limit config. Environment-driven deployments pin {@code
|
||||
* aiEngine.pushConfigToEngine} false (SaaS does so in application-saas.properties) so the engine
|
||||
* stays entirely env-controlled - these tests lock in that the processor stays silent then while
|
||||
* still pushing when it is enabled.
|
||||
*/
|
||||
class AiEngineConfigSyncTest {
|
||||
|
||||
private ApplicationProperties applicationProperties;
|
||||
private AiEngineClient aiEngineClient;
|
||||
private AiEngineConfigSync sync;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
applicationProperties = new ApplicationProperties();
|
||||
applicationProperties.getAiEngine().setEnabled(true);
|
||||
applicationProperties.getAiEngine().setPushConfigToEngine(true);
|
||||
aiEngineClient = mock(AiEngineClient.class);
|
||||
ObjectMapper objectMapper = JsonMapper.builder().build();
|
||||
sync = new AiEngineConfigSync(applicationProperties, aiEngineClient, objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSkippedWhenPushDisabled() throws Exception {
|
||||
applicationProperties.getAiEngine().setPushConfigToEngine(false);
|
||||
|
||||
sync.pushConfigOnStartup();
|
||||
|
||||
// Returns synchronously before spawning the push thread, so no interaction ever happens.
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSkippedWhenDisabled() throws Exception {
|
||||
applicationProperties.getAiEngine().setEnabled(false);
|
||||
|
||||
sync.pushConfigOnStartup();
|
||||
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSentWhenEnabledAndPushOn() throws Exception {
|
||||
sync.pushConfigOnStartup();
|
||||
|
||||
// Push runs on a virtual thread; wait for the single POST to /api/v1/config.
|
||||
verify(aiEngineClient, timeout(3000)).post(eq("/api/v1/config"), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void livePushSkippedWhenPushDisabled() throws Exception {
|
||||
applicationProperties.getAiEngine().setPushConfigToEngine(false);
|
||||
|
||||
sync.pushLiveAfterSave(Map.of("aiEngine.models.provider", "ollama"));
|
||||
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void livePushSentForEngineRelevantChangeWhenPushOn() throws Exception {
|
||||
sync.pushLiveAfterSave(Map.of("aiEngine.models.provider", "ollama"));
|
||||
|
||||
verify(aiEngineClient, timeout(3000)).post(eq("/api/v1/config"), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSerialisesTheEngineWireContract() throws Exception {
|
||||
// Distinct values so a dropped/renamed field is detectable. Mirrors
|
||||
// engine/tests/fixtures/processor_config_push.json - keep the two in sync; the engine's
|
||||
// test_config_contract.py validates that same shape on the receiving side.
|
||||
AiEngine ai = applicationProperties.getAiEngine();
|
||||
ai.getModels().setProvider("ollama");
|
||||
ai.getModels().setSmartModel("smart-model-x");
|
||||
ai.getModels().setFastModel("fast-model-x");
|
||||
ai.getModels().setSmartMaxTokens(1111);
|
||||
ai.getModels().setFastMaxTokens(2222);
|
||||
ai.getModels().setApiKey("provider-key-abc");
|
||||
ai.getModels().setBaseUrl("http://engine.example/v1");
|
||||
ai.getRag().setEmbeddingProvider("custom");
|
||||
ai.getRag().setEmbeddingModel("embed-model-x");
|
||||
ai.getRag().setEmbeddingApiKey("embed-key-abc");
|
||||
ai.getRag().setEmbeddingBaseUrl("http://embed.example/v1");
|
||||
ai.getRag().setTopK(33);
|
||||
ai.getRag().setMaxSearches(7);
|
||||
ai.getLimits().setMaxPages(111);
|
||||
ai.getLimits().setMaxCharacters(222222);
|
||||
ai.getLimits().setModelMaxConcurrency(9);
|
||||
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
sync.pushConfigOnStartup();
|
||||
verify(aiEngineClient, timeout(3000)).post(eq("/api/v1/config"), body.capture(), isNull());
|
||||
|
||||
JsonNode root = JsonMapper.builder().build().readTree(body.getValue());
|
||||
|
||||
JsonNode models = root.get("models");
|
||||
assertEquals("ollama", models.get("provider").asText());
|
||||
assertEquals("smart-model-x", models.get("smartModel").asText());
|
||||
assertEquals("fast-model-x", models.get("fastModel").asText());
|
||||
assertEquals(1111, models.get("smartMaxTokens").asInt());
|
||||
assertEquals(2222, models.get("fastMaxTokens").asInt());
|
||||
assertEquals("provider-key-abc", models.get("apiKey").asText());
|
||||
assertEquals("http://engine.example/v1", models.get("baseUrl").asText());
|
||||
|
||||
JsonNode rag = root.get("rag");
|
||||
assertEquals("custom", rag.get("embeddingProvider").asText());
|
||||
assertEquals("embed-model-x", rag.get("embeddingModel").asText());
|
||||
assertEquals("embed-key-abc", rag.get("embeddingApiKey").asText());
|
||||
assertEquals("http://embed.example/v1", rag.get("embeddingBaseUrl").asText());
|
||||
assertEquals(33, rag.get("topK").asInt());
|
||||
assertEquals(7, rag.get("maxSearches").asInt());
|
||||
|
||||
JsonNode limits = root.get("limits");
|
||||
assertEquals(111, limits.get("maxPages").asInt());
|
||||
assertEquals(222222, limits.get("maxCharacters").asInt());
|
||||
assertEquals(9, limits.get("modelMaxConcurrency").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void livePushSkippedForNonEngineRelevantChange() throws Exception {
|
||||
// features.* is processor-side only; no engine push is warranted.
|
||||
sync.pushLiveAfterSave(Map.of("aiEngine.features.chat", false));
|
||||
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
|
||||
/**
|
||||
* Every AI capability entry point calls the matching {@code require*} before reaching the engine.
|
||||
* These lock in fail-closed behaviour: a 503 when the engine is disabled OR the individual feature
|
||||
* flag is off, and a clean pass only when both are on.
|
||||
*/
|
||||
class AiFeatureGateTest {
|
||||
|
||||
private ApplicationProperties props;
|
||||
private AiFeatureGate gate;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
props = new ApplicationProperties();
|
||||
props.getAiEngine().setEnabled(true); // features default all-on
|
||||
gate = new AiFeatureGate(props);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesWhenEngineEnabledAndFeatureOn() {
|
||||
assertDoesNotThrow(() -> gate.requireClassify());
|
||||
assertDoesNotThrow(() -> gate.requireChat());
|
||||
}
|
||||
|
||||
@Test
|
||||
void throws503WhenFeatureFlagOff() {
|
||||
props.getAiEngine().getFeatures().setClassify(false);
|
||||
|
||||
ResponseStatusException ex =
|
||||
assertThrows(ResponseStatusException.class, () -> gate.requireClassify());
|
||||
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, ex.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void throws503WhenEngineDisabledEvenIfFeatureOn() {
|
||||
props.getAiEngine().setEnabled(false); // feature flag still true
|
||||
|
||||
ResponseStatusException ex =
|
||||
assertThrows(ResponseStatusException.class, () -> gate.requireChat());
|
||||
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, ex.getStatusCode());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
# Stirling-PDF SaaS profile. Pure multi-tenant cloud.
|
||||
# Activated when the :saas module is on the classpath.
|
||||
|
||||
# ---------- AI engine ----------
|
||||
# The SaaS AI backend is env-driven and reached through the saas AiProxyController, so the
|
||||
# processor must never push settings-derived config to it. Pin the config-push off; the engine
|
||||
# stays entirely environment-controlled.
|
||||
aiEngine.pushConfigToEngine=false
|
||||
|
||||
# ---------- Datasource ----------
|
||||
system.datasource.enableCustomDatabase=true
|
||||
system.datasource.customDatabaseUrl=${SAAS_DB_URL:}
|
||||
|
||||
+1
-1
@@ -91,7 +91,7 @@ springBoot {
|
||||
|
||||
allprojects {
|
||||
group = 'stirling.software'
|
||||
version = '2.14.1'
|
||||
version = '2.14.2'
|
||||
|
||||
configurations.configureEach {
|
||||
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
|
||||
|
||||
@@ -88,3 +88,8 @@ STIRLING_LOG_FILE=
|
||||
# Use when diagnosing worker stalls: a hung call shows a "Request" line with
|
||||
# no matching "Response" line. Noisy; leave off in normal use.
|
||||
STIRLING_HTTP_DEBUG=false
|
||||
|
||||
# Allow the Java processor to push admin-configured AI settings (model,
|
||||
# credentials, limits) to POST /api/v1/config at startup. Set false in
|
||||
# environment-driven deployments so the environment is the single source of truth.
|
||||
#STIRLING_ALLOW_CONFIG_PUSH=true
|
||||
|
||||
@@ -4,6 +4,7 @@ version = "0.1.0"
|
||||
description = "AI Document Engine"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"cryptography>=44.0.0",
|
||||
"fastapi>=0.116.0",
|
||||
"jinja2>=3.1.0",
|
||||
"pgvector>=0.3.6",
|
||||
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
from pydantic import Field
|
||||
from pydantic_ai import Agent
|
||||
|
||||
from stirling.agents.output_mode import output_retries
|
||||
from stirling.contracts import (
|
||||
MathAuditorToolReportArtifact,
|
||||
OrchestratorRequest,
|
||||
@@ -68,6 +69,10 @@ class MathIntentClassifier:
|
||||
self._agent: Agent[None, _MathIntentDecision] = Agent(
|
||||
model=runtime.fast_model,
|
||||
output_type=_MathIntentDecision,
|
||||
# Local models emit valid structured output only intermittently (they
|
||||
# sometimes wrap the JSON in prose); a few extra retries make this
|
||||
# hot-path classifier reliable. No-op for real providers.
|
||||
retries=output_retries(runtime.settings.chat_provider),
|
||||
system_prompt=_MATH_INTENT_SYSTEM_PROMPT,
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
|
||||
@@ -2,12 +2,14 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import assert_never
|
||||
from typing import Literal, assert_never
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import ToolOutput
|
||||
from pydantic_ai.output import NativeOutput, ToolOutput
|
||||
from pydantic_ai.tools import RunContext
|
||||
|
||||
from stirling.agents.output_mode import output_retries, uses_tool_output
|
||||
from stirling.agents.pdf_create import PdfCreateAgent
|
||||
from stirling.agents.pdf_edit import PdfEditAgent
|
||||
from stirling.agents.pdf_questions import PdfQuestionAgent
|
||||
@@ -27,6 +29,7 @@ from stirling.contracts import (
|
||||
format_file_names,
|
||||
)
|
||||
from stirling.contracts.pdf_create import PdfCreateOrchestrateResponse
|
||||
from stirling.models import ApiModel
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -38,6 +41,38 @@ class OrchestratorDeps:
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
# Enum-style routing used for Ollama/custom (OpenAI-compatible local) models. The
|
||||
# function-ToolOutput delegates below take no arguments (they read everything from
|
||||
# ctx), but local models reliably try to pass the user's message as tool args, which
|
||||
# the zero-arg delegate schemas reject. Having the model pick a capability by name and
|
||||
# dispatching in Python (via the same _run_* methods used on resume) sidesteps that.
|
||||
_RouteCapability = Literal["pdf_edit", "pdf_question", "user_spec", "pdf_review", "pdf_create", "unsupported"]
|
||||
|
||||
|
||||
class _RouteDecision(ApiModel):
|
||||
# Local models routinely add stray tool args (the filename, the question echoed back)
|
||||
# and send null for optional fields; tolerate both so routing never fails on cosmetics.
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
capability: _RouteCapability
|
||||
message: str | None = Field(
|
||||
default=None,
|
||||
description="Only for capability='unsupported': a short, helpful message to show the user.",
|
||||
)
|
||||
|
||||
|
||||
_ROUTER_SYSTEM_PROMPT = (
|
||||
"You are the top-level router. Choose exactly one capability that best handles the request:\n"
|
||||
"- pdf_edit: modify or convert one or more attached PDFs.\n"
|
||||
"- pdf_question: answer questions about the contents of the attached PDFs.\n"
|
||||
"- user_spec: create or define an agent spec.\n"
|
||||
"- pdf_review: return the PDF with review comments/annotations attached.\n"
|
||||
"- pdf_create: generate a NEW document from scratch (invoice, report, letter) - no input file.\n"
|
||||
"- unsupported: none of the above fit, or the user asks about the assistant itself; put a "
|
||||
"helpful message in 'message'.\n"
|
||||
"Respond with the capability and (only for unsupported) a message."
|
||||
)
|
||||
|
||||
|
||||
class OrchestratorAgent:
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
@@ -86,6 +121,9 @@ class OrchestratorAgent:
|
||||
description="Return this when none of the delegate outputs fit the request.",
|
||||
),
|
||||
],
|
||||
# Local models (Ollama/custom) pick a delegate less reliably; give the
|
||||
# routing a few extra validation retries. No-op for real providers.
|
||||
retries=output_retries(runtime.settings.chat_provider),
|
||||
deps_type=OrchestratorDeps,
|
||||
system_prompt=(
|
||||
"You are the top-level orchestrator. "
|
||||
@@ -103,6 +141,24 @@ class OrchestratorAgent:
|
||||
),
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
# Local models can't drive the zero-arg function-delegate routing above, so
|
||||
# route them by capability name and dispatch in Python instead.
|
||||
self._route_via_enum = uses_tool_output(runtime.settings.chat_provider)
|
||||
# The router has no tools of its own, so NativeOutput (a direct structured
|
||||
# response) works on Ollama here - unlike tool-using agents, which need
|
||||
# ToolOutput. A single output tool would tempt a local model to answer in
|
||||
# plain text and never call it ("include your response in a tool call").
|
||||
self._router = (
|
||||
Agent(
|
||||
model=runtime.fast_model,
|
||||
output_type=NativeOutput([_RouteDecision]),
|
||||
retries=output_retries(runtime.settings.chat_provider),
|
||||
system_prompt=_ROUTER_SYSTEM_PROMPT,
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
if self._route_via_enum
|
||||
else None
|
||||
)
|
||||
|
||||
async def handle(self, request: OrchestratorRequest) -> OrchestratorResponse:
|
||||
logger.info(
|
||||
@@ -114,6 +170,8 @@ class OrchestratorAgent:
|
||||
)
|
||||
if request.resume_with is not None:
|
||||
return await self._resume(request, request.resume_with)
|
||||
if self._router is not None:
|
||||
return await self._route_and_dispatch(request)
|
||||
result = await self.agent.run(
|
||||
self._build_prompt(request),
|
||||
deps=OrchestratorDeps(runtime=self.runtime, request=request),
|
||||
@@ -121,6 +179,31 @@ class OrchestratorAgent:
|
||||
logger.info("[orchestrator] routed -> %s", type(result.output).__name__)
|
||||
return result.output
|
||||
|
||||
async def _route_and_dispatch(self, request: OrchestratorRequest) -> OrchestratorResponse:
|
||||
"""Local-model routing: pick a capability by name, then dispatch in Python."""
|
||||
assert self._router is not None
|
||||
result = await self._router.run(self._build_prompt(request))
|
||||
decision = result.output
|
||||
logger.info("[orchestrator] enum-routed -> %s", decision.capability)
|
||||
match decision.capability:
|
||||
case "pdf_edit":
|
||||
return await self._run_pdf_edit(request)
|
||||
case "pdf_question":
|
||||
return await self._run_pdf_question(request)
|
||||
case "user_spec":
|
||||
return await self._run_agent_draft(request)
|
||||
case "pdf_review":
|
||||
return await self._run_pdf_review(request)
|
||||
case "pdf_create":
|
||||
return await self._run_pdf_create(request)
|
||||
case "unsupported":
|
||||
return UnsupportedCapabilityResponse(
|
||||
capability="orchestrate",
|
||||
message=decision.message or "I can't help with that request.",
|
||||
)
|
||||
case _ as unreachable:
|
||||
assert_never(unreachable)
|
||||
|
||||
async def _resume(self, request: OrchestratorRequest, capability: SupportedCapability) -> OrchestratorResponse:
|
||||
"""Fast-path to get back to the correct endpoint without having to call AI.
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Provider-aware structured-output strategy.
|
||||
|
||||
OpenAI-compatible local models (Ollama, and 'custom' OpenAI-compatible endpoints)
|
||||
block tool-calling whenever a native json-schema ``response_format`` is set: the
|
||||
API constrains every completion to the output schema, so the model can never emit
|
||||
a tool-call turn. Agents that combine structured output with tools (RAG search,
|
||||
whole-document read, etc.) therefore get an ungrounded answer - the model fills the
|
||||
schema directly instead of calling a retrieval tool.
|
||||
|
||||
Delivering the structured result via a tool call (:class:`ToolOutput`) sidesteps
|
||||
this: it's all tool-calling, which these endpoints handle, so the model can call a
|
||||
retrieval tool and then the output tool. Real providers (Anthropic, OpenAI) keep
|
||||
:class:`NativeOutput`, which is unaffected and preferred there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from pydantic_ai.output import NativeOutput, ToolOutput
|
||||
|
||||
# Providers whose OpenAI-compatible endpoint needs tool-delivered structured output.
|
||||
_TOOL_OUTPUT_PROVIDERS = frozenset({"ollama", "custom"})
|
||||
|
||||
|
||||
def uses_tool_output(chat_provider: str) -> bool:
|
||||
return chat_provider in _TOOL_OUTPUT_PROVIDERS
|
||||
|
||||
|
||||
def structured_output(output_types: Sequence[Any], *, chat_provider: str) -> Any:
|
||||
"""Pick a structured-output spec compatible with the active chat provider.
|
||||
|
||||
Ollama/custom deliver each output variant via a :class:`ToolOutput`; every other
|
||||
provider uses a single :class:`NativeOutput` over the variants.
|
||||
"""
|
||||
types = list(output_types)
|
||||
if uses_tool_output(chat_provider):
|
||||
return [ToolOutput(t) for t in types]
|
||||
return NativeOutput(types)
|
||||
|
||||
|
||||
def output_retries(chat_provider: str, *, native: int = 1, tool: int = 6) -> int:
|
||||
"""Local models delivering via ToolOutput need more output-validation retries -
|
||||
small models produce valid complex/nested structured output only intermittently."""
|
||||
return tool if uses_tool_output(chat_provider) else native
|
||||
@@ -3,10 +3,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents.contradiction import ContradictionCapability, ContradictionDetector
|
||||
from stirling.agents.math_presentation import MathIntentClassifier, extract_math_verdict
|
||||
from stirling.agents.output_mode import output_retries, structured_output
|
||||
from stirling.agents.shared import ChunkedReasoner, WholeDocReaderCapability
|
||||
from stirling.contracts import (
|
||||
AiFile,
|
||||
@@ -196,9 +196,17 @@ class PdfQuestionAgent:
|
||||
files=request.files,
|
||||
principals=principals,
|
||||
)
|
||||
# Ollama/custom (OpenAI-compatible local) models block tool-calling under a
|
||||
# native json-schema response format, so deliver the structured result via a
|
||||
# tool call instead - otherwise the model never calls the retrieval tools and
|
||||
# answers ungrounded. Real providers keep NativeOutput. See agents.output_mode.
|
||||
provider = self.runtime.settings.chat_provider
|
||||
agent = Agent(
|
||||
model=self.runtime.smart_model,
|
||||
output_type=NativeOutput([PdfQuestionAnswerResponse, PdfQuestionNotFoundResponse]),
|
||||
output_type=structured_output(
|
||||
[PdfQuestionAnswerResponse, PdfQuestionNotFoundResponse], chat_provider=provider
|
||||
),
|
||||
retries=output_retries(provider),
|
||||
system_prompt=PDF_QUESTION_SYSTEM_PROMPT,
|
||||
# pydantic-ai accepts a list of (string-or-callable) instruction sources;
|
||||
# it resolves each at run time and concatenates them for the model.
|
||||
|
||||
@@ -3,28 +3,20 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.models import Model
|
||||
from pydantic_ai.models.instrumented import InstrumentationSettings
|
||||
|
||||
from stirling.agents import (
|
||||
DocumentClassifierAgent,
|
||||
ExecutionPlanningAgent,
|
||||
OrchestratorAgent,
|
||||
PdfEditAgent,
|
||||
PdfQuestionAgent,
|
||||
UserSpecAgent,
|
||||
)
|
||||
from stirling.agents.ledger import MathAuditorAgent
|
||||
from stirling.agents.pdf_comment import PdfCommentAgent
|
||||
from stirling.api.bootstrap import apply_app_state, build_app_state
|
||||
from stirling.api.dependencies import enforce_required_user_id
|
||||
from stirling.api.engine_auth import EngineSharedSecretMiddleware
|
||||
from stirling.api.middleware import UserIdMiddleware
|
||||
from stirling.api.routes import (
|
||||
agent_capabilities_router,
|
||||
agent_draft_router,
|
||||
config_router,
|
||||
document_classifier_router,
|
||||
document_router,
|
||||
execution_router,
|
||||
@@ -34,10 +26,12 @@ from stirling.api.routes import (
|
||||
pdf_edit_router,
|
||||
pdf_question_router,
|
||||
)
|
||||
from stirling.api.routes.config import CONFIG_APPLY_ERRORS, resolve_and_apply
|
||||
from stirling.config import AppSettings, load_settings
|
||||
from stirling.config.config_cache import load_config
|
||||
from stirling.contracts import HealthResponse
|
||||
from stirling.documents import DocumentService
|
||||
from stirling.services import build_runtime, setup_posthog_tracking
|
||||
from stirling.documents import DocumentService, EmbeddingService
|
||||
from stirling.services import setup_posthog_tracking
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -83,22 +77,52 @@ def _load_startup_settings(fast_api: FastAPI) -> AppSettings:
|
||||
return load_settings()
|
||||
|
||||
|
||||
def _restore_cached_config(
|
||||
settings: AppSettings,
|
||||
) -> tuple[AppSettings, Model | None, Model | None, EmbeddingService | None]:
|
||||
"""Restore the last-applied pushed config from the encrypted on-disk cache.
|
||||
|
||||
Returns the effective settings plus the pre-built smart/fast models and
|
||||
embedder to inject into the initial app state. Falls back to the env settings
|
||||
(all-None) when config push is disabled, no cache exists, or the cached config
|
||||
can't be applied (bad/unavailable model) - the cache never crashes boot.
|
||||
"""
|
||||
if not settings.allow_config_push:
|
||||
return settings, None, None, None
|
||||
cached = load_config()
|
||||
if cached is None:
|
||||
return settings, None, None, None
|
||||
try:
|
||||
effective, smart_model, fast_model, embedder, notes = resolve_and_apply(settings, cached)
|
||||
except CONFIG_APPLY_ERRORS:
|
||||
logger.warning("Cached AI config could not be applied; falling back to env settings", exc_info=True)
|
||||
return settings, None, None, None
|
||||
logger.info(
|
||||
"Restored cached AI config: smart_model=%s fast_model=%s%s",
|
||||
effective.smart_model_name,
|
||||
effective.fast_model_name,
|
||||
f"; {'; '.join(notes)}" if notes else "",
|
||||
)
|
||||
return effective, smart_model, fast_model, embedder
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(fast_api: FastAPI):
|
||||
# Load env vars on startup so we can immediately crash if required env vars aren't set
|
||||
settings = _load_startup_settings(fast_api)
|
||||
runtime = build_runtime(settings)
|
||||
fast_api.state.settings = settings
|
||||
fast_api.state.runtime = runtime
|
||||
fast_api.state.orchestrator_agent = OrchestratorAgent(runtime)
|
||||
fast_api.state.pdf_edit_agent = PdfEditAgent(runtime)
|
||||
fast_api.state.pdf_question_agent = PdfQuestionAgent(runtime)
|
||||
fast_api.state.user_spec_agent = UserSpecAgent(runtime)
|
||||
fast_api.state.execution_planning_agent = ExecutionPlanningAgent(runtime)
|
||||
fast_api.state.math_auditor_agent = MathAuditorAgent(runtime)
|
||||
fast_api.state.pdf_comment_agent = PdfCommentAgent(runtime)
|
||||
fast_api.state.document_classifier_agent = DocumentClassifierAgent(runtime)
|
||||
tracer_provider = setup_posthog_tracking(settings)
|
||||
# Precedence: env < persisted cache < live push. Restore the last-applied pushed
|
||||
# config unless config push is disabled (then env is the single source of truth).
|
||||
effective, smart_model, fast_model, embedder = _restore_cached_config(settings)
|
||||
app_state = build_app_state(
|
||||
effective,
|
||||
fast_model=fast_model,
|
||||
smart_model=smart_model,
|
||||
embedder=embedder,
|
||||
)
|
||||
fast_api.state.settings = effective
|
||||
apply_app_state(fast_api.state, app_state)
|
||||
runtime = app_state.runtime
|
||||
tracer_provider = setup_posthog_tracking(effective)
|
||||
if tracer_provider:
|
||||
Agent.instrument_all(InstrumentationSettings(tracer_provider=tracer_provider))
|
||||
reaper_task = asyncio.create_task(
|
||||
@@ -135,10 +159,18 @@ app.include_router(ledger_router, dependencies=_user_gate)
|
||||
app.include_router(pdf_comments_router, dependencies=_user_gate)
|
||||
app.include_router(agent_capabilities_router, dependencies=_user_gate)
|
||||
app.include_router(document_classifier_router, dependencies=_user_gate)
|
||||
# Config push is a system/admin sync from the Java processor with no X-User-Id, so
|
||||
# it is guarded by the X-Engine-Auth shared secret (global middleware) and the
|
||||
# allow_config_push flag only, deliberately NOT the per-user identity gate.
|
||||
app.include_router(config_router)
|
||||
|
||||
|
||||
@app.get("/health", response_model=HealthResponse)
|
||||
async def healthcheck(settings: Annotated[AppSettings, Depends(load_settings)]) -> HealthResponse:
|
||||
async def healthcheck(http_request: Request) -> HealthResponse:
|
||||
# Report the LIVE config (env < cache < push) held on app.state, not the
|
||||
# boot-time env cache, so an admin "Test connection" check shows the model
|
||||
# actually in use after a config push. Falls back to env if state isn't up yet.
|
||||
settings: AppSettings = getattr(http_request.app.state, "settings", None) or load_settings()
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
smart_model=settings.smart_model_name,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Assemble the runtime + every agent into a single swappable bundle.
|
||||
|
||||
Both the lifespan startup and the config-push endpoint build the same object
|
||||
graph: one :class:`AppRuntime` plus one agent instance per flow, each of which
|
||||
captures ``runtime.smart_model``/``runtime.fast_model`` at construction. To change
|
||||
models at runtime the whole bundle has to be rebuilt and swapped into
|
||||
``app.state`` atomically, which is what :func:`build_app_state` /
|
||||
:func:`apply_app_state` exist for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
|
||||
from pydantic_ai.models import Model
|
||||
|
||||
from stirling.agents import (
|
||||
DocumentClassifierAgent,
|
||||
ExecutionPlanningAgent,
|
||||
OrchestratorAgent,
|
||||
PdfEditAgent,
|
||||
PdfQuestionAgent,
|
||||
UserSpecAgent,
|
||||
)
|
||||
from stirling.agents.ledger import MathAuditorAgent
|
||||
from stirling.agents.pdf_comment import PdfCommentAgent
|
||||
from stirling.config import AppSettings
|
||||
from stirling.documents import DocumentService, EmbeddingService
|
||||
from stirling.services import AppRuntime, build_runtime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AppState:
|
||||
"""Every object the lifespan assigns onto ``fast_api.state``."""
|
||||
|
||||
runtime: AppRuntime
|
||||
orchestrator_agent: OrchestratorAgent
|
||||
pdf_edit_agent: PdfEditAgent
|
||||
pdf_question_agent: PdfQuestionAgent
|
||||
user_spec_agent: UserSpecAgent
|
||||
execution_planning_agent: ExecutionPlanningAgent
|
||||
math_auditor_agent: MathAuditorAgent
|
||||
pdf_comment_agent: PdfCommentAgent
|
||||
document_classifier_agent: DocumentClassifierAgent
|
||||
|
||||
|
||||
def build_app_state(
|
||||
settings: AppSettings,
|
||||
*,
|
||||
documents: DocumentService | None = None,
|
||||
fast_model: Model | None = None,
|
||||
smart_model: Model | None = None,
|
||||
embedder: EmbeddingService | None = None,
|
||||
) -> AppState:
|
||||
"""Build the runtime and every agent from ``settings``.
|
||||
|
||||
The keyword arguments are threaded straight to :func:`build_runtime` so a
|
||||
config-push rebuild can reuse the live document store and inject already
|
||||
validated models (and, on a cache-restore boot, a pre-built embedder); all
|
||||
None reproduces the original startup path.
|
||||
"""
|
||||
runtime = build_runtime(
|
||||
settings,
|
||||
documents=documents,
|
||||
fast_model=fast_model,
|
||||
smart_model=smart_model,
|
||||
embedder=embedder,
|
||||
)
|
||||
return AppState(
|
||||
runtime=runtime,
|
||||
orchestrator_agent=OrchestratorAgent(runtime),
|
||||
pdf_edit_agent=PdfEditAgent(runtime),
|
||||
pdf_question_agent=PdfQuestionAgent(runtime),
|
||||
user_spec_agent=UserSpecAgent(runtime),
|
||||
execution_planning_agent=ExecutionPlanningAgent(runtime),
|
||||
math_auditor_agent=MathAuditorAgent(runtime),
|
||||
pdf_comment_agent=PdfCommentAgent(runtime),
|
||||
document_classifier_agent=DocumentClassifierAgent(runtime),
|
||||
)
|
||||
|
||||
|
||||
def apply_app_state(state: Any, app_state: AppState) -> None:
|
||||
"""Copy every field of ``app_state`` onto a Starlette ``app.state`` object."""
|
||||
for field in fields(app_state):
|
||||
setattr(state, field.name, getattr(app_state, field.name))
|
||||
@@ -1,5 +1,6 @@
|
||||
from .agent_capabilities import router as agent_capabilities_router
|
||||
from .agent_drafts import router as agent_draft_router
|
||||
from .config import router as config_router
|
||||
from .document_classifier import router as document_classifier_router
|
||||
from .documents import router as document_router
|
||||
from .execution import router as execution_router
|
||||
@@ -12,6 +13,7 @@ from .pdf_questions import router as pdf_question_router
|
||||
__all__ = [
|
||||
"agent_capabilities_router",
|
||||
"agent_draft_router",
|
||||
"config_router",
|
||||
"document_classifier_router",
|
||||
"document_router",
|
||||
"execution_router",
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, status
|
||||
from openai import OpenAIError
|
||||
from pydantic_ai.exceptions import UserError
|
||||
from pydantic_ai.models import Model
|
||||
|
||||
from stirling.api.bootstrap import apply_app_state, build_app_state
|
||||
from stirling.config import AppSettings
|
||||
from stirling.config.config_cache import save_config
|
||||
from stirling.contracts import ConfigApplyResponse, ConfigPushRequest
|
||||
from stirling.documents import EmbeddingService
|
||||
from stirling.services import AppRuntime
|
||||
from stirling.services.runtime import _build_model, validate_structured_output_support
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/config", tags=["config"])
|
||||
|
||||
# Model/provider construction + validation failures. The HTTP route maps these to a
|
||||
# 400 (no swap); boot catches them to fall back to env when a cached config is bad.
|
||||
CONFIG_APPLY_ERRORS = (ValueError, UserError, OpenAIError)
|
||||
|
||||
_REINDEX_NOTE = (
|
||||
"Embedding model changed; existing indexed documents were embedded with the previous model and "
|
||||
"must be re-indexed. If the embedding dimensionality changed, re-ingest before searching."
|
||||
)
|
||||
|
||||
|
||||
def _strip_provider_prefix(model_name: str) -> str:
|
||||
"""Drop a leading ``provider:`` from an env model string ("anthropic:x" -> "x").
|
||||
|
||||
Only used when falling back to the env-configured name under an explicit
|
||||
pushed provider; a bare pushed name (which may itself contain ``:`` such as
|
||||
"llama3:8b") is used verbatim and never passed through here.
|
||||
"""
|
||||
_, sep, rest = model_name.partition(":")
|
||||
return rest if sep else model_name
|
||||
|
||||
|
||||
def _compose_embedding_model(provider: str, model: str) -> str:
|
||||
"""Compose the engine's ``provider:model`` embedding string from pushed parts."""
|
||||
provider = provider.strip()
|
||||
return f"{provider}:{model}" if provider else model
|
||||
|
||||
|
||||
def _split_embedding_ref(ref: str) -> tuple[str, str]:
|
||||
"""Split an env embedding string ("voyageai:voyage-4") into (provider, model)."""
|
||||
provider, sep, model = ref.partition(":")
|
||||
return (provider, model) if sep else ("", ref)
|
||||
|
||||
|
||||
def _keep(pushed: int | None, current: int) -> int:
|
||||
"""Return the pushed value, or the current one when the push omitted it."""
|
||||
return pushed if pushed is not None else current
|
||||
|
||||
|
||||
def _is_loopback_client(request: Request) -> bool:
|
||||
"""True when the request originates from the local host (127.0.0.0/8, ::1)."""
|
||||
client = request.client
|
||||
if client is None:
|
||||
return False
|
||||
try:
|
||||
return ipaddress.ip_address(client.host).is_loopback
|
||||
except ValueError:
|
||||
return client.host == "localhost"
|
||||
|
||||
|
||||
def resolve_and_apply(
|
||||
current: AppSettings,
|
||||
request: ConfigPushRequest,
|
||||
) -> tuple[AppSettings, Model, Model, EmbeddingService | None, list[str]]:
|
||||
"""Resolve a pushed config against the running settings.
|
||||
|
||||
Builds and validates the smart/fast models, resolves the scalar overrides,
|
||||
and builds a new embedder when the embedding config changed. Empty/None pushed
|
||||
fields keep the current value. Returns the effective settings, the two built
|
||||
models, an optional new embedder (None when the embedding config is unchanged),
|
||||
and human-readable notes.
|
||||
|
||||
Raises one of :data:`CONFIG_APPLY_ERRORS` if a chosen model/embedder fails to
|
||||
build or validate; callers decide whether that becomes a 400 (HTTP route) or an
|
||||
env fallback (boot). It never swaps any live state - the caller owns that.
|
||||
"""
|
||||
models = request.models
|
||||
rag = request.rag
|
||||
limits = request.limits
|
||||
notes: list[str] = []
|
||||
|
||||
provider = models.provider.strip()
|
||||
api_key = models.api_key
|
||||
base_url = models.base_url
|
||||
use_explicit_provider = bool(provider or api_key or base_url)
|
||||
|
||||
if use_explicit_provider:
|
||||
smart_name = models.smart_model or _strip_provider_prefix(current.smart_model_name)
|
||||
fast_name = models.fast_model or _strip_provider_prefix(current.fast_model_name)
|
||||
else:
|
||||
# No provider/credentials pushed: keep the fully env-driven model strings.
|
||||
smart_name = models.smart_model or current.smart_model_name
|
||||
fast_name = models.fast_model or current.fast_model_name
|
||||
|
||||
def _build(bare: str) -> Model:
|
||||
if use_explicit_provider:
|
||||
return _build_model(bare, provider=provider or None, api_key=api_key or None, base_url=base_url or None)
|
||||
return _build_model(bare)
|
||||
|
||||
smart_model = _build(smart_name)
|
||||
fast_model = _build(fast_name)
|
||||
validate_structured_output_support(smart_model, smart_name)
|
||||
validate_structured_output_support(fast_model, fast_name)
|
||||
|
||||
# Scalars: None / empty keep the current value.
|
||||
smart_max_tokens = _keep(models.smart_max_tokens, current.smart_model_max_tokens)
|
||||
fast_max_tokens = _keep(models.fast_max_tokens, current.fast_model_max_tokens)
|
||||
top_k = _keep(rag.top_k, current.rag_default_top_k)
|
||||
max_searches = _keep(rag.max_searches, current.rag_max_searches)
|
||||
max_pages = _keep(limits.max_pages, current.max_pages)
|
||||
max_characters = _keep(limits.max_characters, current.max_characters)
|
||||
model_max_concurrency = _keep(limits.model_max_concurrency, current.model_max_concurrency)
|
||||
|
||||
# Embedding: any non-empty embedding field triggers a rebuild; empty fields fall
|
||||
# back to the running provider/model/creds so a partial push never clobbers env.
|
||||
embedding_changed = bool(
|
||||
rag.embedding_provider.strip() or rag.embedding_model.strip() or rag.embedding_api_key or rag.embedding_base_url
|
||||
)
|
||||
rag_embedding_model = current.rag_embedding_model
|
||||
new_embedder: EmbeddingService | None = None
|
||||
if embedding_changed:
|
||||
current_provider, current_model = _split_embedding_ref(current.rag_embedding_model)
|
||||
embed_provider = rag.embedding_provider.strip() or current_provider
|
||||
embed_model = rag.embedding_model.strip() or current_model
|
||||
rag_embedding_model = _compose_embedding_model(embed_provider, embed_model)
|
||||
new_embedder = EmbeddingService(
|
||||
model_name=embed_model,
|
||||
chunk_size=current.rag_chunk_size,
|
||||
chunk_overlap=current.rag_chunk_overlap,
|
||||
provider=embed_provider or None,
|
||||
api_key=rag.embedding_api_key or None,
|
||||
base_url=rag.embedding_base_url or None,
|
||||
)
|
||||
notes.append(_REINDEX_NOTE)
|
||||
|
||||
effective = current.model_copy(
|
||||
update={
|
||||
"chat_provider": provider,
|
||||
"smart_model_name": smart_name,
|
||||
"fast_model_name": fast_name,
|
||||
"smart_model_max_tokens": smart_max_tokens,
|
||||
"fast_model_max_tokens": fast_max_tokens,
|
||||
"rag_embedding_model": rag_embedding_model,
|
||||
"rag_default_top_k": top_k,
|
||||
"rag_max_searches": max_searches,
|
||||
"max_pages": max_pages,
|
||||
"max_characters": max_characters,
|
||||
"model_max_concurrency": model_max_concurrency,
|
||||
}
|
||||
)
|
||||
return effective, smart_model, fast_model, new_embedder, notes
|
||||
|
||||
|
||||
@router.post("", response_model=ConfigApplyResponse)
|
||||
async def apply_config(request: ConfigPushRequest, http_request: Request) -> ConfigApplyResponse:
|
||||
"""Apply admin-pushed AI settings by rebuilding the runtime + agents in place.
|
||||
|
||||
Gated by the X-Engine-Auth shared secret (global middleware) plus the
|
||||
``allow_config_push`` flag. Empty credential/model fields keep the engine's
|
||||
env-configured values. Returns 403 when config push is disabled, 400 (without
|
||||
swapping state) when a chosen model fails to build/validate. On success the
|
||||
config is also persisted (encrypted) so it survives an engine restart.
|
||||
"""
|
||||
app = http_request.app
|
||||
current: AppSettings = app.state.settings
|
||||
if not current.allow_config_push:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Config push is disabled on this deployment (STIRLING_ALLOW_CONFIG_PUSH is false).",
|
||||
)
|
||||
# Secure-by-default for this sensitive endpoint. When a shared secret is set the
|
||||
# global middleware has already authenticated the caller (only the processor has the
|
||||
# secret). When NO secret is set, only trust a loopback caller - a remote party must
|
||||
# never be able to push a config unauthenticated, since a pushed base_url/model could
|
||||
# repoint the engine to exfiltrate document content.
|
||||
if not current.engine_shared_secret and not _is_loopback_client(http_request):
|
||||
client_host = http_request.client.host if http_request.client else "unknown"
|
||||
logger.warning("Rejected config push from non-local caller %s with no shared secret set", client_host)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=(
|
||||
"Config push from a non-local caller requires STIRLING_ENGINE_SHARED_SECRET"
|
||||
" to be set on both the engine and the processor."
|
||||
),
|
||||
)
|
||||
|
||||
runtime: AppRuntime = app.state.runtime
|
||||
try:
|
||||
effective, smart_model, fast_model, new_embedder, notes = resolve_and_apply(current, request)
|
||||
except CONFIG_APPLY_ERRORS as exc:
|
||||
# Reject without touching the running config.
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
|
||||
|
||||
# Rebuild runtime + every agent, reusing the existing document store, then
|
||||
# swap the whole bundle onto app.state so in-flight lookups see one config.
|
||||
new_state = build_app_state(
|
||||
effective,
|
||||
documents=runtime.documents,
|
||||
fast_model=fast_model,
|
||||
smart_model=smart_model,
|
||||
)
|
||||
app.state.settings = effective
|
||||
apply_app_state(app.state, new_state)
|
||||
# Retune retrieval breadth on the reused store without rebuilding it.
|
||||
runtime.documents.default_top_k = effective.rag_default_top_k
|
||||
if new_embedder is not None:
|
||||
# Swap the embedder onto the reused DocumentService so we never tear down
|
||||
# the live vector store / connection pool.
|
||||
runtime.documents.embedder = new_embedder
|
||||
|
||||
# Persist the applied config (encrypted) so it is restored on the next boot.
|
||||
try:
|
||||
save_config(request)
|
||||
except OSError:
|
||||
logger.warning("Applied AI config but failed to persist the encrypted cache", exc_info=True)
|
||||
notes.append("Config applied but could not be persisted; it will not survive an engine restart.")
|
||||
|
||||
logger.info(
|
||||
"Applied pushed AI config: provider=%s smart_model=%s fast_model=%s top_k=%s",
|
||||
request.models.provider.strip() or "<env>",
|
||||
effective.smart_model_name,
|
||||
effective.fast_model_name,
|
||||
effective.rag_default_top_k,
|
||||
)
|
||||
|
||||
return ConfigApplyResponse(
|
||||
status="applied",
|
||||
provider=request.models.provider.strip(),
|
||||
smart_model=effective.smart_model_name,
|
||||
fast_model=effective.fast_model_name,
|
||||
smart_max_tokens=effective.smart_model_max_tokens,
|
||||
fast_max_tokens=effective.fast_model_max_tokens,
|
||||
rag_embedding_model=effective.rag_embedding_model,
|
||||
rag_top_k=effective.rag_default_top_k,
|
||||
rag_max_searches=effective.rag_max_searches,
|
||||
max_pages=effective.max_pages,
|
||||
max_characters=effective.max_characters,
|
||||
model_max_concurrency=effective.model_max_concurrency,
|
||||
notes=notes,
|
||||
)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Persistent, encrypted cache of the last-applied config-push.
|
||||
|
||||
The engine otherwise holds pushed config in RAM only, so a restart reverts to the
|
||||
env values until the processor pushes again. We persist the last-applied
|
||||
:class:`ConfigPushRequest` to ``<engine data dir>/ai_config_cache.enc`` (Fernet
|
||||
encrypted) and reload it on boot so the effective config survives restarts.
|
||||
|
||||
Key derivation: when ``STIRLING_ENGINE_SHARED_SECRET`` is set, the Fernet key is
|
||||
HKDF-SHA256 over that secret (constant salt/info) so no key material touches disk.
|
||||
Otherwise a random Fernet key is generated once and stored in a sibling
|
||||
``ai_config_cache.key`` (0600, best-effort) with a one-time warning.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
|
||||
from stirling.config.settings import ENGINE_ROOT, load_settings
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CACHE_FILENAME = "ai_config_cache.enc"
|
||||
_KEY_FILENAME = "ai_config_cache.key"
|
||||
# Constant salt/info so the same shared secret always derives the same Fernet key.
|
||||
_HKDF_SALT = b"stirling-ai-config-cache/v1/salt"
|
||||
_HKDF_INFO = b"stirling-ai-config-cache/v1/fernet-key"
|
||||
|
||||
_keyfile_warned = False
|
||||
|
||||
|
||||
def _default_data_dir() -> Path:
|
||||
"""The engine data dir (where the sqlite store lives by default)."""
|
||||
return ENGINE_ROOT / "data"
|
||||
|
||||
|
||||
def _shared_secret() -> str:
|
||||
return load_settings().engine_shared_secret
|
||||
|
||||
|
||||
def _derive_key_from_secret(secret: str) -> bytes:
|
||||
hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=_HKDF_SALT, info=_HKDF_INFO)
|
||||
return base64.urlsafe_b64encode(hkdf.derive(secret.encode("utf-8")))
|
||||
|
||||
|
||||
def _chmod_600(path: Path) -> None:
|
||||
# Best-effort owner-only perms; silently ignored where unsupported (e.g. Windows).
|
||||
try:
|
||||
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _load_or_create_keyfile(data_dir: Path) -> bytes:
|
||||
global _keyfile_warned
|
||||
key_path = data_dir / _KEY_FILENAME
|
||||
if key_path.exists():
|
||||
return key_path.read_bytes().strip()
|
||||
key = Fernet.generate_key()
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
key_path.write_bytes(key)
|
||||
_chmod_600(key_path)
|
||||
if not _keyfile_warned:
|
||||
logger.warning(
|
||||
"STIRLING_ENGINE_SHARED_SECRET is not set; encrypting the AI config cache with a local"
|
||||
" keyfile at %s (0600, best-effort). This is modest protection only - set a shared secret"
|
||||
" for HKDF key derivation in any deployment where the cache must be strongly protected.",
|
||||
key_path,
|
||||
)
|
||||
_keyfile_warned = True
|
||||
return key
|
||||
|
||||
|
||||
def _fernet(data_dir: Path) -> Fernet:
|
||||
secret = _shared_secret()
|
||||
if secret:
|
||||
return Fernet(_derive_key_from_secret(secret))
|
||||
return Fernet(_load_or_create_keyfile(data_dir))
|
||||
|
||||
|
||||
def save_config(request: ConfigPushRequest, *, data_dir: Path | None = None) -> None:
|
||||
"""Encrypt and persist the last-applied pushed config, overwriting any prior file."""
|
||||
data_dir = data_dir or _default_data_dir()
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
payload = request.model_dump_json(by_alias=True).encode("utf-8")
|
||||
token = _fernet(data_dir).encrypt(payload)
|
||||
(data_dir / _CACHE_FILENAME).write_bytes(token)
|
||||
|
||||
|
||||
def load_config(*, data_dir: Path | None = None) -> ConfigPushRequest | None:
|
||||
"""Load + decrypt the persisted pushed config.
|
||||
|
||||
Returns None (never raises) when the cache is absent, corrupt, or was written
|
||||
under a different key, so a bad cache can never crash boot.
|
||||
"""
|
||||
data_dir = data_dir or _default_data_dir()
|
||||
cache_path = data_dir / _CACHE_FILENAME
|
||||
if not cache_path.exists():
|
||||
return None
|
||||
try:
|
||||
token = cache_path.read_bytes()
|
||||
payload = _fernet(data_dir).decrypt(token)
|
||||
return ConfigPushRequest.model_validate_json(payload)
|
||||
except (InvalidToken, ValueError, OSError) as exc:
|
||||
logger.warning("Ignoring unreadable AI config cache at %s: %s", cache_path, exc)
|
||||
return None
|
||||
@@ -25,6 +25,12 @@ class AppSettings(BaseSettings):
|
||||
|
||||
smart_model_name: str = Field(validation_alias="STIRLING_SMART_MODEL")
|
||||
fast_model_name: str = Field(validation_alias="STIRLING_FAST_MODEL")
|
||||
# Provider backing the active chat models. Empty for env/native providers; set to
|
||||
# 'ollama'/'custom' by a config push. Agents that combine structured output with
|
||||
# tools read this to pick a tool-compatible output strategy, because OpenAI-compatible
|
||||
# local models (Ollama) block tool calls when a native json-schema response format is
|
||||
# set, so their structured result must be delivered via a tool call instead.
|
||||
chat_provider: str = Field(default="")
|
||||
smart_model_max_tokens: int = Field(validation_alias="STIRLING_SMART_MODEL_MAX_TOKENS")
|
||||
fast_model_max_tokens: int = Field(validation_alias="STIRLING_FAST_MODEL_MAX_TOKENS")
|
||||
# Process-wide ceiling on concurrent model API calls, shared by both model
|
||||
@@ -123,6 +129,11 @@ class AppSettings(BaseSettings):
|
||||
engine_shared_secret: str = Field(default="", validation_alias="STIRLING_ENGINE_SHARED_SECRET")
|
||||
engine_require_auth: bool = Field(default=False, validation_alias="STIRLING_ENGINE_REQUIRE_AUTH")
|
||||
|
||||
# When true, the Java processor may push admin-configured AI settings (model,
|
||||
# credentials, limits) to POST /api/v1/config at startup. Turn this off in
|
||||
# environment-driven deployments so the environment is the single source of truth.
|
||||
allow_config_push: bool = Field(default=True, validation_alias="STIRLING_ALLOW_CONFIG_PUSH")
|
||||
|
||||
|
||||
def _configure_logging(level_name: str, log_file: str, http_debug: bool) -> None:
|
||||
"""Configure the ``stirling`` logger hierarchy."""
|
||||
|
||||
@@ -29,6 +29,13 @@ from .common import (
|
||||
format_conversation_history,
|
||||
format_file_names,
|
||||
)
|
||||
from .config import (
|
||||
ConfigApplyResponse,
|
||||
ConfigLimitsSection,
|
||||
ConfigModelsSection,
|
||||
ConfigPushRequest,
|
||||
ConfigRagSection,
|
||||
)
|
||||
from .contradiction import (
|
||||
Claim,
|
||||
Contradiction,
|
||||
@@ -139,6 +146,11 @@ __all__ = [
|
||||
"Claim",
|
||||
"CommentSpec",
|
||||
"CompletedExecutionAction",
|
||||
"ConfigApplyResponse",
|
||||
"ConfigLimitsSection",
|
||||
"ConfigModelsSection",
|
||||
"ConfigPushRequest",
|
||||
"ConfigRagSection",
|
||||
"Contradiction",
|
||||
"ContradictionReport",
|
||||
"ContradictionSeverity",
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from stirling.models import ApiModel
|
||||
|
||||
# Tolerate unknown fields so a newer processor pushing a field this engine version
|
||||
# doesn't know is ignored rather than rejecting the whole push. Overrides only the
|
||||
# ``extra`` policy from ApiModel; the camelCase alias generator is inherited.
|
||||
_TOLERANT = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
class ConfigModelsSection(ApiModel):
|
||||
"""Model provider + credentials pushed by the Java processor.
|
||||
|
||||
Field names on the wire are camelCase (``smartModel`` etc.) via the
|
||||
:class:`ApiModel` alias generator. Empty ``provider``/``apiKey``/``baseUrl``
|
||||
or empty model names mean "keep the engine's env-configured value".
|
||||
"""
|
||||
|
||||
model_config = _TOLERANT
|
||||
|
||||
provider: str = ""
|
||||
smart_model: str = ""
|
||||
fast_model: str = ""
|
||||
smart_max_tokens: int | None = None
|
||||
fast_max_tokens: int | None = None
|
||||
api_key: str = ""
|
||||
base_url: str = ""
|
||||
|
||||
|
||||
class ConfigRagSection(ApiModel):
|
||||
model_config = _TOLERANT
|
||||
|
||||
embedding_provider: str = ""
|
||||
embedding_model: str = ""
|
||||
embedding_api_key: str = ""
|
||||
# OpenAI-compatible endpoint URL for ollama/custom embedding providers.
|
||||
# Empty keeps the engine's env value, same convention as the other fields.
|
||||
embedding_base_url: str = ""
|
||||
top_k: int | None = None
|
||||
max_searches: int | None = None
|
||||
|
||||
|
||||
class ConfigLimitsSection(ApiModel):
|
||||
model_config = _TOLERANT
|
||||
|
||||
max_pages: int | None = None
|
||||
max_characters: int | None = None
|
||||
model_max_concurrency: int | None = None
|
||||
|
||||
|
||||
class ConfigPushRequest(ApiModel):
|
||||
"""Admin-configured AI settings pushed at processor startup."""
|
||||
|
||||
model_config = _TOLERANT
|
||||
|
||||
models: ConfigModelsSection = Field(default_factory=ConfigModelsSection)
|
||||
rag: ConfigRagSection = Field(default_factory=ConfigRagSection)
|
||||
limits: ConfigLimitsSection = Field(default_factory=ConfigLimitsSection)
|
||||
|
||||
|
||||
class ConfigApplyResponse(ApiModel):
|
||||
"""Summary of the effective config after a push. Never echoes credentials."""
|
||||
|
||||
status: str
|
||||
provider: str
|
||||
smart_model: str
|
||||
fast_model: str
|
||||
smart_max_tokens: int
|
||||
fast_max_tokens: int
|
||||
rag_embedding_model: str
|
||||
rag_top_k: int
|
||||
rag_max_searches: int
|
||||
max_pages: int
|
||||
max_characters: int
|
||||
model_max_concurrency: int
|
||||
notes: list[str] = Field(default_factory=list)
|
||||
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic_ai import Embedder
|
||||
from pydantic_ai.embeddings.openai import OpenAIEmbeddingModel
|
||||
from pydantic_ai.providers.openai import OpenAIProvider
|
||||
|
||||
from stirling.documents.chunker import chunk_text
|
||||
from stirling.documents.store import Document
|
||||
@@ -12,6 +14,37 @@ from stirling.documents.store import Document
|
||||
DEFAULT_EMBED_BATCH_SIZE = 256
|
||||
|
||||
|
||||
def _build_embedder(
|
||||
model_name: str,
|
||||
*,
|
||||
provider: str | None = None,
|
||||
api_key: str | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> Embedder:
|
||||
"""Construct an :class:`Embedder` for ``model_name``.
|
||||
|
||||
With no explicit ``provider``/``api_key``/``base_url`` this keeps the original
|
||||
behaviour: ``model_name`` is the ``provider:model`` string form (e.g.
|
||||
"voyageai:voyage-4") and credentials come from the provider's native env var.
|
||||
|
||||
With an explicit provider (config-push path) ``model_name`` is the bare model
|
||||
without a prefix. ``voyageai``/``openai`` compose the same string form; the
|
||||
OpenAI-compatible ``ollama``/``custom`` build an OpenAI embedding model against
|
||||
``base_url`` (Ollama ignores the key but the SDK still needs a non-empty one).
|
||||
"""
|
||||
if not provider and not api_key and not base_url:
|
||||
return Embedder(model_name)
|
||||
|
||||
provider_name = (provider or "").lower()
|
||||
key = api_key or None
|
||||
if provider_name in ("voyageai", "openai"):
|
||||
return Embedder(f"{provider_name}:{model_name}")
|
||||
if provider_name in ("ollama", "custom"):
|
||||
openai_provider = OpenAIProvider(base_url=base_url or None, api_key=key or "ollama")
|
||||
return Embedder(OpenAIEmbeddingModel(model_name, provider=openai_provider))
|
||||
raise ValueError(f"Unsupported embedding provider {provider!r}.")
|
||||
|
||||
|
||||
class EmbeddingService:
|
||||
"""Wraps Pydantic AI's Embedder to provide document chunking and embedding."""
|
||||
|
||||
@@ -21,8 +54,12 @@ class EmbeddingService:
|
||||
chunk_size: int = 512,
|
||||
chunk_overlap: int = 64,
|
||||
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
|
||||
*,
|
||||
provider: str | None = None,
|
||||
api_key: str | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> None:
|
||||
self._embedder = Embedder(model_name)
|
||||
self._embedder = _build_embedder(model_name, provider=provider, api_key=api_key, base_url=base_url)
|
||||
self._chunk_size = chunk_size
|
||||
self._chunk_overlap = chunk_overlap
|
||||
self._embed_batch_size = embed_batch_size
|
||||
|
||||
@@ -43,6 +43,25 @@ class DocumentService:
|
||||
self._store = store
|
||||
self._default_top_k = default_top_k
|
||||
|
||||
@property
|
||||
def default_top_k(self) -> int:
|
||||
return self._default_top_k
|
||||
|
||||
@default_top_k.setter
|
||||
def default_top_k(self, value: int) -> None:
|
||||
# Lets a config-push retune retrieval breadth without rebuilding the store.
|
||||
self._default_top_k = value
|
||||
|
||||
@property
|
||||
def embedder(self) -> EmbeddingService:
|
||||
return self._embedder
|
||||
|
||||
@embedder.setter
|
||||
def embedder(self, value: EmbeddingService) -> None:
|
||||
# Lets a config-push swap the embedding model while keeping the live store
|
||||
# (and its connection pool). Existing vectors need re-indexing afterwards.
|
||||
self._embedder = value
|
||||
|
||||
async def ingest(
|
||||
self,
|
||||
collection: FileId,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
@@ -12,8 +14,10 @@ from pydantic_ai import RunContext
|
||||
from pydantic_ai.messages import ModelMessage, ModelResponse
|
||||
from pydantic_ai.models import Model, ModelRequestParameters, StreamedResponse, infer_model
|
||||
from pydantic_ai.models.anthropic import AnthropicModel
|
||||
from pydantic_ai.models.openai import OpenAIChatModel
|
||||
from pydantic_ai.models.wrapper import WrapperModel
|
||||
from pydantic_ai.providers.anthropic import AnthropicProvider
|
||||
from pydantic_ai.providers.openai import OpenAIProvider
|
||||
from pydantic_ai.settings import ModelSettings
|
||||
|
||||
from stirling.config import ENGINE_ROOT, AppSettings, DocumentsBackend
|
||||
@@ -49,6 +53,79 @@ def _build_anthropic_http_client() -> httpx.AsyncClient:
|
||||
)
|
||||
|
||||
|
||||
# Placeholder used when no Anthropic key is configured; lets the engine boot so a
|
||||
# deployment that only uses another provider (e.g. Ollama via the admin UI / config
|
||||
# push) isn't blocked. Anthropic calls then fail with a clear 401 instead.
|
||||
_UNCONFIGURED_ANTHROPIC_KEY = "unconfigured"
|
||||
_warned_missing_anthropic_key = False
|
||||
|
||||
|
||||
def _anthropic_provider(explicit_key: str | None = None) -> AnthropicProvider:
|
||||
"""Build the Anthropic provider, tolerating a missing key at startup.
|
||||
|
||||
pydantic-ai's ``AnthropicProvider`` raises at construction when no key is
|
||||
available, which would crash the whole engine at boot even for deployments
|
||||
that never call Anthropic (Ollama/OpenAI-configured, or awaiting a config
|
||||
push that supplies credentials). We fall back to a placeholder key and warn
|
||||
once so startup succeeds; the placeholder only surfaces as a clear
|
||||
provider-side auth error if an Anthropic call is actually made.
|
||||
"""
|
||||
http_client = _build_anthropic_http_client()
|
||||
key = explicit_key or os.environ.get("ANTHROPIC_API_KEY")
|
||||
if key:
|
||||
return AnthropicProvider(api_key=key, http_client=http_client)
|
||||
global _warned_missing_anthropic_key
|
||||
if not _warned_missing_anthropic_key:
|
||||
_warned_missing_anthropic_key = True
|
||||
logger.warning(
|
||||
"ANTHROPIC_API_KEY is not set - the engine will start, but Anthropic model "
|
||||
"calls will fail until a key is provided or a different provider is configured "
|
||||
"(admin AI settings / config push)."
|
||||
)
|
||||
return AnthropicProvider(api_key=_UNCONFIGURED_ANTHROPIC_KEY, http_client=http_client)
|
||||
|
||||
|
||||
class _NullContentCoercingTransport(httpx.AsyncHTTPTransport):
|
||||
"""Coerce assistant ``content: null`` to ``""`` in outgoing OpenAI chat requests.
|
||||
|
||||
OpenAI's schema uses ``content: null`` for assistant messages that carry only
|
||||
tool calls, but Ollama's OpenAI-compatible endpoint rejects it ("invalid message
|
||||
content type: <nil>"), which intermittently breaks multi-turn tool conversations
|
||||
(RAG search + tool-delivered output). Rewriting null -> "" makes them acceptable
|
||||
without changing semantics. Scoped to the ollama/custom clients only.
|
||||
"""
|
||||
|
||||
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
||||
if request.headers.get("content-type", "").startswith("application/json") and request.content:
|
||||
try:
|
||||
body = json.loads(request.content)
|
||||
except ValueError:
|
||||
return await super().handle_async_request(request)
|
||||
messages = body.get("messages")
|
||||
if isinstance(messages, list):
|
||||
changed = False
|
||||
for message in messages:
|
||||
if isinstance(message, dict) and message.get("content", "") is None:
|
||||
message["content"] = ""
|
||||
changed = True
|
||||
if changed:
|
||||
new_body = json.dumps(body).encode("utf-8")
|
||||
headers = [(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"]
|
||||
request = httpx.Request(
|
||||
method=request.method,
|
||||
url=request.url,
|
||||
headers=headers,
|
||||
content=new_body,
|
||||
extensions=request.extensions,
|
||||
)
|
||||
return await super().handle_async_request(request)
|
||||
|
||||
|
||||
def _openai_compat_http_client() -> httpx.AsyncClient:
|
||||
"""httpx client for Ollama/custom OpenAI-compatible endpoints (null-content fix)."""
|
||||
return httpx.AsyncClient(transport=_NullContentCoercingTransport())
|
||||
|
||||
|
||||
class ConcurrencyLimitedModel(WrapperModel):
|
||||
"""Caps in-flight model API calls with a semaphore shared across the process."""
|
||||
|
||||
@@ -131,45 +208,97 @@ def _build_document_store(settings: AppSettings) -> DocumentStore:
|
||||
assert_never(settings.documents_backend)
|
||||
|
||||
|
||||
def _build_documents(settings: AppSettings) -> DocumentService:
|
||||
"""Build the document service used by per-request RAG capabilities."""
|
||||
logger.info("Documents: embedding_model=%s", settings.rag_embedding_model)
|
||||
embedder = EmbeddingService(
|
||||
model_name=settings.rag_embedding_model,
|
||||
chunk_size=settings.rag_chunk_size,
|
||||
chunk_overlap=settings.rag_chunk_overlap,
|
||||
)
|
||||
def _build_documents(settings: AppSettings, embedder: EmbeddingService | None = None) -> DocumentService:
|
||||
"""Build the document service used by per-request RAG capabilities.
|
||||
|
||||
``embedder`` lets a cache-restore boot inject an already-built embedder (e.g.
|
||||
an OpenAI-compatible ollama/custom one whose base_url the plain
|
||||
``settings.rag_embedding_model`` string can't encode); None builds from settings.
|
||||
"""
|
||||
if embedder is None:
|
||||
logger.info("Documents: embedding_model=%s", settings.rag_embedding_model)
|
||||
embedder = EmbeddingService(
|
||||
model_name=settings.rag_embedding_model,
|
||||
chunk_size=settings.rag_chunk_size,
|
||||
chunk_overlap=settings.rag_chunk_overlap,
|
||||
)
|
||||
store = _build_document_store(settings)
|
||||
return DocumentService(embedder=embedder, store=store, default_top_k=settings.rag_default_top_k)
|
||||
|
||||
|
||||
def build_runtime(settings: AppSettings) -> AppRuntime:
|
||||
fast_model = _build_model(settings.fast_model_name)
|
||||
smart_model = _build_model(settings.smart_model_name)
|
||||
validate_structured_output_support(fast_model, settings.fast_model_name)
|
||||
validate_structured_output_support(smart_model, settings.smart_model_name)
|
||||
def build_runtime(
|
||||
settings: AppSettings,
|
||||
*,
|
||||
documents: DocumentService | None = None,
|
||||
fast_model: Model | None = None,
|
||||
smart_model: Model | None = None,
|
||||
embedder: EmbeddingService | None = None,
|
||||
) -> AppRuntime:
|
||||
"""Assemble the shared runtime.
|
||||
|
||||
``documents``/``fast_model``/``smart_model`` let a config-push rebuild reuse
|
||||
the live vector-store connection pool and inject already-built (and already
|
||||
validated) models instead of reconstructing them from the model-name strings.
|
||||
``embedder`` injects a pre-built embedder when building a fresh document store
|
||||
(cache-restore boot); it is ignored when ``documents`` is supplied. All None
|
||||
(the lifespan path) preserves the original startup behaviour.
|
||||
"""
|
||||
fast = fast_model if fast_model is not None else _build_model(settings.fast_model_name)
|
||||
smart = smart_model if smart_model is not None else _build_model(settings.smart_model_name)
|
||||
validate_structured_output_support(fast, settings.fast_model_name)
|
||||
validate_structured_output_support(smart, settings.smart_model_name)
|
||||
|
||||
# One semaphore across both tiers: the cap protects the provider account
|
||||
# and process resources, which the tiers share.
|
||||
model_semaphore = asyncio.Semaphore(settings.model_max_concurrency)
|
||||
return AppRuntime(
|
||||
settings=settings,
|
||||
fast_model=ConcurrencyLimitedModel(fast_model, model_semaphore),
|
||||
smart_model=ConcurrencyLimitedModel(smart_model, model_semaphore),
|
||||
documents=_build_documents(settings),
|
||||
fast_model=ConcurrencyLimitedModel(fast, model_semaphore),
|
||||
smart_model=ConcurrencyLimitedModel(smart, model_semaphore),
|
||||
documents=documents if documents is not None else _build_documents(settings, embedder),
|
||||
)
|
||||
|
||||
|
||||
def _build_model(model_name: str) -> Model:
|
||||
"""Construct a model, injecting our keepalive-free httpx client for
|
||||
Anthropic models so workers don't pick up stale pooled connections.
|
||||
def _build_model(
|
||||
model_name: str,
|
||||
*,
|
||||
provider: str | None = None,
|
||||
api_key: str | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> Model:
|
||||
"""Construct a model for ``model_name``.
|
||||
|
||||
Other providers fall back to ``infer_model`` defaults; the stale-pool
|
||||
issue is specific to the Cloudflare-fronted Anthropic API in our
|
||||
observations and the fix doesn't necessarily apply elsewhere.
|
||||
With no explicit ``provider``/``api_key``/``base_url`` this keeps the original
|
||||
env-driven behaviour: Anthropic-prefixed names get our keepalive-free httpx
|
||||
client (so workers don't pick up stale pooled connections) and everything
|
||||
else falls back to ``infer_model``.
|
||||
|
||||
When the caller passes an explicit provider (config-push path), ``model_name``
|
||||
is the bare model without a ``provider:`` prefix and credentials come from the
|
||||
call. An empty ``api_key``/``base_url`` is treated as unset so the provider
|
||||
reads its native environment variable (e.g. ANTHROPIC_API_KEY / OPENAI_API_KEY).
|
||||
"""
|
||||
if model_name.startswith("anthropic:"):
|
||||
bare_name = model_name.removeprefix("anthropic:")
|
||||
provider = AnthropicProvider(http_client=_build_anthropic_http_client())
|
||||
return AnthropicModel(bare_name, provider=provider)
|
||||
return infer_model(model_name)
|
||||
if not provider and not api_key and not base_url:
|
||||
if model_name.startswith("anthropic:"):
|
||||
bare_name = model_name.removeprefix("anthropic:")
|
||||
return AnthropicModel(bare_name, provider=_anthropic_provider())
|
||||
return infer_model(model_name)
|
||||
|
||||
provider_name = (provider or "").lower()
|
||||
key = api_key or None
|
||||
if provider_name == "anthropic":
|
||||
return AnthropicModel(model_name, provider=_anthropic_provider(key))
|
||||
if provider_name == "openai":
|
||||
openai_provider = OpenAIProvider(api_key=key) if key else OpenAIProvider()
|
||||
return OpenAIChatModel(model_name, provider=openai_provider)
|
||||
if provider_name in ("ollama", "custom"):
|
||||
# OpenAI-compatible endpoint. Ollama ignores the key but the SDK still
|
||||
# requires a non-empty one, so default to a harmless placeholder. The custom
|
||||
# http client coerces null assistant content so multi-turn tool calls work.
|
||||
openai_provider = OpenAIProvider(
|
||||
base_url=base_url or None,
|
||||
api_key=key or "ollama",
|
||||
http_client=_openai_compat_http_client(),
|
||||
)
|
||||
return OpenAIChatModel(model_name, provider=openai_provider)
|
||||
raise ValueError(f"Unsupported model provider {provider!r}.")
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"models": {
|
||||
"provider": "ollama",
|
||||
"smartModel": "smart-model-x",
|
||||
"fastModel": "fast-model-x",
|
||||
"smartMaxTokens": 1111,
|
||||
"fastMaxTokens": 2222,
|
||||
"apiKey": "provider-key-abc",
|
||||
"baseUrl": "http://engine.example/v1"
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider": "custom",
|
||||
"embeddingModel": "embed-model-x",
|
||||
"embeddingApiKey": "embed-key-abc",
|
||||
"embeddingBaseUrl": "http://embed.example/v1",
|
||||
"topK": 33,
|
||||
"maxSearches": 7
|
||||
},
|
||||
"limits": {
|
||||
"maxPages": 111,
|
||||
"maxCharacters": 222222,
|
||||
"modelMaxConcurrency": 9
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Tests for the encrypted config cache (stirling.config.config_cache)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from stirling.config import config_cache
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
|
||||
def _sample() -> ConfigPushRequest:
|
||||
return ConfigPushRequest.model_validate(
|
||||
{
|
||||
"models": {
|
||||
"provider": "anthropic",
|
||||
"smartModel": "claude-haiku-4-5",
|
||||
"fastModel": "claude-haiku-4-5",
|
||||
"smartMaxTokens": 8192,
|
||||
"fastMaxTokens": 2048,
|
||||
"apiKey": "secret-key-value",
|
||||
"baseUrl": "",
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider": "voyageai",
|
||||
"embeddingModel": "voyage-4",
|
||||
"embeddingApiKey": "embed-secret",
|
||||
"embeddingBaseUrl": "",
|
||||
"topK": 20,
|
||||
"maxSearches": 5,
|
||||
},
|
||||
"limits": {"maxPages": 200, "maxCharacters": 200000, "modelMaxConcurrency": 32},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_roundtrip_with_shared_secret(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "the-shared-secret")
|
||||
req = _sample()
|
||||
config_cache.save_config(req, data_dir=tmp_path)
|
||||
# HKDF-from-secret path: no keyfile is written.
|
||||
assert not (tmp_path / "ai_config_cache.key").exists()
|
||||
assert config_cache.load_config(data_dir=tmp_path) == req
|
||||
# Secrets are encrypted at rest.
|
||||
assert b"secret-key-value" not in (tmp_path / "ai_config_cache.enc").read_bytes()
|
||||
|
||||
|
||||
def test_roundtrip_with_keyfile_when_no_secret(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "")
|
||||
req = _sample()
|
||||
config_cache.save_config(req, data_dir=tmp_path)
|
||||
# No shared secret: a random keyfile is generated and reused for decrypt.
|
||||
assert (tmp_path / "ai_config_cache.key").exists()
|
||||
assert config_cache.load_config(data_dir=tmp_path) == req
|
||||
|
||||
|
||||
def test_load_missing_returns_none(tmp_path: Path) -> None:
|
||||
assert config_cache.load_config(data_dir=tmp_path) is None
|
||||
|
||||
|
||||
def test_load_corrupt_returns_none(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "a-secret")
|
||||
(tmp_path / "ai_config_cache.enc").write_bytes(b"not-a-valid-fernet-token")
|
||||
assert config_cache.load_config(data_dir=tmp_path) is None
|
||||
|
||||
|
||||
def test_wrong_key_returns_none(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "secret-a")
|
||||
config_cache.save_config(_sample(), data_dir=tmp_path)
|
||||
# A different secret derives a different key -> decrypt fails, returns None.
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "secret-b")
|
||||
assert config_cache.load_config(data_dir=tmp_path) is None
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Wire-contract test for the processor -> engine config push.
|
||||
|
||||
The Java processor (AiEngineConfigSync.buildConfigNode) serialises the admin AI settings as
|
||||
camelCase JSON and POSTs them to /api/v1/config. Because ConfigPushRequest uses extra="ignore"
|
||||
(so version skew never 422s), a field the engine can no longer map is silently dropped to its
|
||||
default instead of erroring. This test pins the exact camelCase contract: every field in the
|
||||
shared fixture must round-trip onto the model, so a rename on either side fails loudly.
|
||||
|
||||
The same fixture (tests/fixtures/processor_config_push.json) is the contract the Java
|
||||
AiEngineConfigSyncTest asserts its serialiser produces - keep the two in sync.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "processor_config_push.json"
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
return json.loads(FIXTURE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_processor_contract_round_trips_every_field() -> None:
|
||||
payload = _load()
|
||||
req = ConfigPushRequest.model_validate(payload)
|
||||
|
||||
m = payload["models"]
|
||||
assert req.models.provider == m["provider"]
|
||||
assert req.models.smart_model == m["smartModel"]
|
||||
assert req.models.fast_model == m["fastModel"]
|
||||
assert req.models.smart_max_tokens == m["smartMaxTokens"]
|
||||
assert req.models.fast_max_tokens == m["fastMaxTokens"]
|
||||
assert req.models.api_key == m["apiKey"]
|
||||
assert req.models.base_url == m["baseUrl"]
|
||||
|
||||
r = payload["rag"]
|
||||
assert req.rag.embedding_provider == r["embeddingProvider"]
|
||||
assert req.rag.embedding_model == r["embeddingModel"]
|
||||
assert req.rag.embedding_api_key == r["embeddingApiKey"]
|
||||
assert req.rag.embedding_base_url == r["embeddingBaseUrl"]
|
||||
assert req.rag.top_k == r["topK"]
|
||||
assert req.rag.max_searches == r["maxSearches"]
|
||||
|
||||
limits = payload["limits"]
|
||||
assert req.limits.max_pages == limits["maxPages"]
|
||||
assert req.limits.max_characters == limits["maxCharacters"]
|
||||
assert req.limits.model_max_concurrency == limits["modelMaxConcurrency"]
|
||||
|
||||
|
||||
def test_processor_contract_has_no_unmapped_keys() -> None:
|
||||
"""Guard the fixture itself: every wire key must map to a model field (none silently
|
||||
absorbed by extra="ignore"). If the processor adds a field, extend the contract here."""
|
||||
payload = _load()
|
||||
expected = {
|
||||
"models": {
|
||||
"provider",
|
||||
"smartModel",
|
||||
"fastModel",
|
||||
"smartMaxTokens",
|
||||
"fastMaxTokens",
|
||||
"apiKey",
|
||||
"baseUrl",
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider",
|
||||
"embeddingModel",
|
||||
"embeddingApiKey",
|
||||
"embeddingBaseUrl",
|
||||
"topK",
|
||||
"maxSearches",
|
||||
},
|
||||
"limits": {"maxPages", "maxCharacters", "modelMaxConcurrency"},
|
||||
}
|
||||
assert set(payload) == set(expected)
|
||||
for section, keys in expected.items():
|
||||
assert set(payload[section]) == keys
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Tests for the config-push endpoint (POST /api/v1/config).
|
||||
|
||||
These drive the real lifespan (via ``with TestClient(app)``) so ``app.state`` is
|
||||
populated, then exercise the gate + model-swap behaviour against the in-memory
|
||||
"test" runtime built by :func:`build_app_settings`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from conftest import build_app_settings
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from stirling.api import app
|
||||
from stirling.config import AppSettings, config_cache, load_settings
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_config_cache(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
"""Point the encrypted config cache at a per-test tmp dir so persistence never
|
||||
touches the real engine/data dir or leaks between tests."""
|
||||
monkeypatch.setattr(config_cache, "_default_data_dir", lambda: tmp_path)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _client(
|
||||
settings_factory: Callable[[], AppSettings],
|
||||
*,
|
||||
client_addr: tuple[str, int] = ("127.0.0.1", 12345),
|
||||
) -> Iterator[TestClient]:
|
||||
"""Enter a TestClient whose lifespan builds app.state from ``settings_factory``.
|
||||
|
||||
Defaults to a loopback client address so the config endpoint's local-caller gate
|
||||
(which blocks remote unauthenticated pushes) allows the request through.
|
||||
"""
|
||||
previous = app.dependency_overrides.get(load_settings)
|
||||
app.dependency_overrides[load_settings] = settings_factory
|
||||
try:
|
||||
with TestClient(app, client=client_addr) as client:
|
||||
yield client
|
||||
finally:
|
||||
if previous is None:
|
||||
app.dependency_overrides.pop(load_settings, None)
|
||||
else:
|
||||
app.dependency_overrides[load_settings] = previous
|
||||
|
||||
|
||||
def _anthropic_push() -> dict[str, object]:
|
||||
return {
|
||||
"models": {
|
||||
"provider": "anthropic",
|
||||
"smartModel": "claude-haiku-4-5",
|
||||
"fastModel": "claude-haiku-4-5",
|
||||
"smartMaxTokens": 4096,
|
||||
"fastMaxTokens": 1024,
|
||||
"apiKey": "test-key-not-a-real-secret",
|
||||
"baseUrl": "",
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider": "",
|
||||
"embeddingModel": "",
|
||||
"embeddingApiKey": "",
|
||||
"embeddingBaseUrl": "",
|
||||
"topK": 7,
|
||||
"maxSearches": 3,
|
||||
},
|
||||
"limits": {"maxPages": 50, "maxCharacters": 12345, "modelMaxConcurrency": 8},
|
||||
}
|
||||
|
||||
|
||||
def test_config_push_forbidden_when_disabled() -> None:
|
||||
def factory() -> AppSettings:
|
||||
return build_app_settings().model_copy(update={"allow_config_push": False})
|
||||
|
||||
with _client(factory) as client:
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_config_push_from_non_local_caller_without_secret_returns_403() -> None:
|
||||
"""Secure-by-default: with no shared secret, a remote caller cannot push a config."""
|
||||
with _client(build_app_settings, client_addr=("203.0.113.9", 4444)) as client:
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 403
|
||||
assert "STIRLING_ENGINE_SHARED_SECRET" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_config_push_applies_model_and_limits() -> None:
|
||||
with _client(build_app_settings) as client:
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
# Wire summary is camelCase and never echoes the api key.
|
||||
assert body["smartModel"] == "claude-haiku-4-5"
|
||||
assert body["fastModel"] == "claude-haiku-4-5"
|
||||
assert body["smartMaxTokens"] == 4096
|
||||
assert body["ragTopK"] == 7
|
||||
assert body["maxPages"] == 50
|
||||
assert body["modelMaxConcurrency"] == 8
|
||||
assert "test-key-not-a-real-secret" not in response.text
|
||||
# State was swapped: the running settings now reflect the push.
|
||||
assert app.state.settings.smart_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.max_pages == 50
|
||||
assert app.state.runtime.documents.default_top_k == 7
|
||||
|
||||
|
||||
def test_config_push_unsupported_provider_returns_400_without_swap() -> None:
|
||||
with _client(build_app_settings) as client:
|
||||
before = app.state.runtime
|
||||
payload = _anthropic_push()
|
||||
payload["models"]["provider"] = "nonsense-provider" # type: ignore[index]
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 400
|
||||
# Running runtime is untouched when the push is rejected.
|
||||
assert app.state.runtime is before
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
|
||||
|
||||
def test_config_push_unsupported_model_returns_400() -> None:
|
||||
"""A model that fails structured-output validation is rejected with 400."""
|
||||
with _client(build_app_settings) as client:
|
||||
before = app.state.runtime
|
||||
with patch(
|
||||
"stirling.api.routes.config.validate_structured_output_support",
|
||||
side_effect=ValueError("Unsupported model foo. This model does not support structured outputs."),
|
||||
):
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 400
|
||||
assert "does not support structured outputs" in response.json()["detail"]
|
||||
assert app.state.runtime is before
|
||||
|
||||
|
||||
def test_config_push_ollama_embedding_rebuilds_embedder() -> None:
|
||||
"""A pushed ollama/custom embedding provider builds an OpenAI-compatible
|
||||
embedder and swaps it onto the reused DocumentService without tearing down
|
||||
the store; the response carries a re-index note."""
|
||||
with _client(build_app_settings) as client:
|
||||
store_before = app.state.runtime.documents
|
||||
embedder_before = app.state.runtime.documents.embedder
|
||||
payload = _anthropic_push()
|
||||
payload["rag"] = {
|
||||
"embeddingProvider": "ollama",
|
||||
"embeddingModel": "nomic-embed-text",
|
||||
"embeddingApiKey": "",
|
||||
"embeddingBaseUrl": "http://localhost:11434/v1",
|
||||
"topK": 9,
|
||||
"maxSearches": 4,
|
||||
}
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["ragEmbeddingModel"] == "ollama:nomic-embed-text"
|
||||
assert any("re-index" in note for note in body["notes"])
|
||||
docs = app.state.runtime.documents
|
||||
# Same store object reused (connection pool intact), embedder swapped.
|
||||
assert docs is store_before
|
||||
assert docs.embedder is not embedder_before
|
||||
assert docs.default_top_k == 9
|
||||
|
||||
|
||||
def test_config_push_unsupported_embedding_provider_returns_400() -> None:
|
||||
with _client(build_app_settings) as client:
|
||||
embedder_before = app.state.runtime.documents.embedder
|
||||
payload = _anthropic_push()
|
||||
payload["rag"] = {
|
||||
"embeddingProvider": "totally-bogus",
|
||||
"embeddingModel": "x",
|
||||
"embeddingApiKey": "",
|
||||
"embeddingBaseUrl": "",
|
||||
"topK": None,
|
||||
"maxSearches": None,
|
||||
}
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 400
|
||||
# Embedder untouched when the push is rejected.
|
||||
assert app.state.runtime.documents.embedder is embedder_before
|
||||
|
||||
|
||||
def test_config_push_empty_models_keep_env_value() -> None:
|
||||
"""An empty models block keeps the engine's current (env) models but still
|
||||
applies pushed limits."""
|
||||
with _client(build_app_settings) as client:
|
||||
payload = _anthropic_push()
|
||||
payload["models"] = {
|
||||
"provider": "",
|
||||
"smartModel": "",
|
||||
"fastModel": "",
|
||||
"smartMaxTokens": None,
|
||||
"fastMaxTokens": None,
|
||||
"apiKey": "",
|
||||
"baseUrl": "",
|
||||
}
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 200
|
||||
# Env "test" model preserved for both tiers; limits still applied.
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
assert app.state.settings.fast_model_name == "test"
|
||||
assert app.state.settings.max_pages == 50
|
||||
|
||||
|
||||
def test_config_push_ignores_unknown_fields() -> None:
|
||||
"""A newer processor pushing fields this engine doesn't know must not 422;
|
||||
unknown fields are ignored and the rest of the push still applies."""
|
||||
with _client(build_app_settings) as client:
|
||||
payload = _anthropic_push()
|
||||
payload["futureTopLevelField"] = {"anything": 1}
|
||||
payload["models"]["experimentalFlag"] = True # type: ignore[index]
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 200
|
||||
assert app.state.settings.smart_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.max_pages == 50
|
||||
|
||||
|
||||
def test_boot_restores_cached_config() -> None:
|
||||
"""A persisted config is decrypted and applied on boot, overriding env."""
|
||||
config_cache.save_config(ConfigPushRequest.model_validate(_anthropic_push()))
|
||||
with _client(build_app_settings):
|
||||
# Env model is "test"; the cache pushed claude-haiku-4-5 + limits.
|
||||
assert app.state.settings.smart_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.fast_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.max_pages == 50
|
||||
assert app.state.settings.smart_model_max_tokens == 4096
|
||||
assert app.state.runtime.documents.default_top_k == 7
|
||||
|
||||
|
||||
def test_boot_ignores_cache_when_push_disabled() -> None:
|
||||
"""With allow_config_push false, env wins and the cache is ignored."""
|
||||
config_cache.save_config(ConfigPushRequest.model_validate(_anthropic_push()))
|
||||
|
||||
def factory() -> AppSettings:
|
||||
return build_app_settings().model_copy(update={"allow_config_push": False})
|
||||
|
||||
with _client(factory):
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
assert app.state.settings.max_pages == 200
|
||||
|
||||
|
||||
def test_boot_proceeds_on_corrupt_cache(tmp_path: Path) -> None:
|
||||
"""A corrupt cache file is ignored and boot falls back to env, never crashing."""
|
||||
(tmp_path / "ai_config_cache.enc").write_bytes(b"not-a-valid-fernet-token")
|
||||
with _client(build_app_settings):
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
assert app.state.settings.max_pages == 200
|
||||
Generated
+2
@@ -603,6 +603,7 @@ name = "engine"
|
||||
version = "0.1.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "cryptography" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
@@ -630,6 +631,7 @@ dev = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "cryptography", specifier = ">=44.0.0" },
|
||||
{ name = "fastapi", specifier = ">=0.116.0" },
|
||||
{ name = "jinja2", specifier = ">=3.1.0" },
|
||||
{ name = "opentelemetry-sdk", specifier = ">=1.39.0" },
|
||||
|
||||
@@ -692,6 +692,160 @@ manualLinks = "Manual downloads: click the links and place the files into the te
|
||||
noLanguages = "No tessdata languages found in the configured directory."
|
||||
permissionNotice = "The tessdata path is not writable. Downloads will be opened in the browser; please save the .traineddata files manually into the tessdata folder."
|
||||
|
||||
# AI engine admin settings (AI nav group)
|
||||
[admin.settings.ai.documents]
|
||||
description = "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved."
|
||||
title = "Documents & RAG"
|
||||
|
||||
[admin.settings.ai.documents.embeddingApiKey]
|
||||
description = "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments."
|
||||
generic = "Embedding API key"
|
||||
openai = "OpenAI API key"
|
||||
voyageai = "VoyageAI API key"
|
||||
|
||||
[admin.settings.ai.documents.embeddingBaseUrl]
|
||||
description = "Base URL of the OpenAI-compatible / Ollama embeddings endpoint, e.g. http://ollama:11434/v1. Must point at a trusted internal endpoint (SSRF-sensitive)."
|
||||
label = "Embedding base URL"
|
||||
|
||||
[admin.settings.ai.documents.embeddingModel]
|
||||
description = "Embedding model name. Free text; suggestions are hints only."
|
||||
label = "Embedding model"
|
||||
|
||||
[admin.settings.ai.documents.embeddingProvider]
|
||||
description = "Provider used to turn document text into vector embeddings."
|
||||
label = "Embedding provider"
|
||||
|
||||
[admin.settings.ai.documents.maxSearches]
|
||||
description = "Maximum number of retrieval searches the agent may run per request."
|
||||
label = "Max searches"
|
||||
|
||||
[admin.settings.ai.documents.reindexNote]
|
||||
body = "Changing the embedding model invalidates previously-embedded documents. A full engine restart and re-index of existing documents is required for search to work correctly."
|
||||
title = "Re-index required"
|
||||
|
||||
[admin.settings.ai.documents.topK]
|
||||
description = "Number of most-relevant chunks retrieved per search."
|
||||
label = "Top K"
|
||||
|
||||
[admin.settings.ai.general]
|
||||
description = "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart."
|
||||
title = "AI Engine"
|
||||
|
||||
[admin.settings.ai.general.capabilities]
|
||||
description = "Turn individual AI features on or off. Disabled features are hidden in the app."
|
||||
title = "Capabilities"
|
||||
|
||||
[admin.settings.ai.general.enabled]
|
||||
description = "Master switch. When off, no AI tools, agents, or engine calls are available."
|
||||
label = "Enable AI"
|
||||
|
||||
[admin.settings.ai.general.features.chat]
|
||||
description = "Conversational assistant for working with PDFs."
|
||||
label = "Chat assistant"
|
||||
|
||||
[admin.settings.ai.general.features.classify]
|
||||
description = "Automatically categorise documents by type or content."
|
||||
label = "Document classification"
|
||||
|
||||
[admin.settings.ai.general.features.createPdf]
|
||||
description = "Generate a new PDF (e.g. from HTML) via an AI agent."
|
||||
label = "Create PDF from prompt"
|
||||
|
||||
[admin.settings.ai.general.features.documentQuestions]
|
||||
description = "Ask questions and get answers grounded in an uploaded document."
|
||||
label = "Document questions"
|
||||
|
||||
[admin.settings.ai.general.features.mathAuditor]
|
||||
description = "Review documents for mathematical and numerical errors."
|
||||
label = "Math auditor"
|
||||
|
||||
[admin.settings.ai.general.features.pdfComment]
|
||||
description = "Add AI-authored review comments and annotations to a PDF."
|
||||
label = "PDF comment agent"
|
||||
|
||||
[admin.settings.ai.general.longRunningTimeoutSeconds]
|
||||
description = "Timeout for heavier agent operations such as document generation."
|
||||
label = "Long-running timeout (seconds)"
|
||||
|
||||
[admin.settings.ai.general.note]
|
||||
body = "The AI engine runs as a separate service. Its shared secret"
|
||||
body2 = "is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved."
|
||||
title = "About the AI engine"
|
||||
|
||||
[admin.settings.ai.general.streamTimeoutSeconds]
|
||||
description = "Timeout for streamed (token-by-token) chat responses."
|
||||
label = "Stream timeout (seconds)"
|
||||
|
||||
[admin.settings.ai.general.test]
|
||||
button = "Test connection"
|
||||
failBody = "The AI engine did not respond. Check the URL, that the engine container is running, and that AI is enabled (a restart is needed after enabling)."
|
||||
failTitle = "AI engine unreachable"
|
||||
okBody = "The AI engine responded to a health check."
|
||||
okTitle = "AI engine reachable"
|
||||
|
||||
[admin.settings.ai.general.timeoutSeconds]
|
||||
description = "Timeout for standard AI requests to the engine."
|
||||
label = "Request timeout (seconds)"
|
||||
|
||||
[admin.settings.ai.general.url]
|
||||
description = "Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001."
|
||||
label = "AI engine URL"
|
||||
|
||||
[admin.settings.ai.limits]
|
||||
description = "Guardrails for how much work AI requests may do and how many run concurrently. Applied to the AI engine when saved."
|
||||
title = "Limits & Performance"
|
||||
|
||||
[admin.settings.ai.limits.maxCharacters]
|
||||
description = "Guardrail: reject AI requests whose extracted text exceeds this length."
|
||||
label = "Max characters per request"
|
||||
|
||||
[admin.settings.ai.limits.maxPages]
|
||||
description = "Guardrail: reject AI requests over this many PDF pages."
|
||||
label = "Max pages per request"
|
||||
|
||||
[admin.settings.ai.limits.modelMaxConcurrency]
|
||||
description = "Maximum simultaneous in-flight model calls across the whole engine."
|
||||
label = "Model max concurrency"
|
||||
|
||||
[admin.settings.ai.models]
|
||||
description = "Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved."
|
||||
title = "Models & Providers"
|
||||
|
||||
[admin.settings.ai.models.apiKey]
|
||||
anthropic = "Anthropic API key"
|
||||
description = "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments."
|
||||
generic = "API key"
|
||||
openai = "OpenAI API key"
|
||||
|
||||
[admin.settings.ai.models.baseUrl]
|
||||
description = "Base URL of the OpenAI-compatible / Ollama endpoint, e.g. http://ollama:11434/v1."
|
||||
label = "Provider base URL"
|
||||
warning = "The base URL must point at a trusted internal endpoint. The engine will make server-side requests to it, so an untrusted value is SSRF-sensitive."
|
||||
|
||||
[admin.settings.ai.models.fastMaxTokens]
|
||||
description = "Maximum output tokens for the fast model."
|
||||
label = "Fast model max tokens"
|
||||
|
||||
[admin.settings.ai.models.fastModel]
|
||||
description = "Cheaper, faster model for lightweight tasks. Free text; suggestions are hints only."
|
||||
label = "Fast model"
|
||||
|
||||
[admin.settings.ai.models.provider]
|
||||
description = "Which LLM provider the engine talks to."
|
||||
label = "Provider"
|
||||
|
||||
[admin.settings.ai.models.smartMaxTokens]
|
||||
description = "Maximum output tokens for the smart model."
|
||||
label = "Smart model max tokens"
|
||||
|
||||
[admin.settings.ai.models.smartModel]
|
||||
description = "High-capability model for complex reasoning. Free text; suggestions are hints only."
|
||||
label = "Smart model"
|
||||
|
||||
[admin.settings.ai.saved]
|
||||
body = "Changes are pushed to the AI engine automatically."
|
||||
title = "AI settings saved"
|
||||
|
||||
[admin.settings.badge]
|
||||
clickToUpgrade = "Click to view plan details"
|
||||
|
||||
@@ -6240,6 +6394,10 @@ muted = "muted"
|
||||
nameLabel = "Name"
|
||||
namePlaceholder = "e.g. Compliance escalation"
|
||||
|
||||
[portal.agentBuilder.status]
|
||||
draft = "Draft"
|
||||
published = "Published"
|
||||
|
||||
[portal.agentBuilder.tabs]
|
||||
evals = "Evals"
|
||||
scenarios = "Scenarios"
|
||||
@@ -6463,7 +6621,7 @@ install = "Install"
|
||||
usage = "Usage"
|
||||
|
||||
[portal.catalogue.detail.locked]
|
||||
description = "{{name}} is included from the {{tier}} plan. Upgrade to embed it."
|
||||
description = "{{name}} is included from the {{plan}}. Upgrade to embed it."
|
||||
title = "Not available on your plan"
|
||||
|
||||
[portal.catalogue.detail.preview]
|
||||
@@ -6530,6 +6688,35 @@ title = "No components available"
|
||||
description = "GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."
|
||||
title = "Some components need a paid plan"
|
||||
|
||||
[portal.connections]
|
||||
createTitle = "New S3 connection"
|
||||
delete = "Delete"
|
||||
edit = "Edit"
|
||||
editTitle = "Edit S3 connection"
|
||||
subtitle = "Reusable S3 credentials that sources and pipeline outputs connect to."
|
||||
|
||||
[portal.connections.actions]
|
||||
new = "New connection"
|
||||
|
||||
[portal.connections.empty]
|
||||
description = "Add an S3 connection to reuse the same bucket and credentials across sources and pipeline outputs."
|
||||
title = "No connections yet"
|
||||
|
||||
[portal.connections.picker]
|
||||
cancel = "Cancel"
|
||||
createNew = "New connection..."
|
||||
placeholder = "Select a connection"
|
||||
save = "Save connection"
|
||||
|
||||
[portal.connections.s3.fields]
|
||||
name = "Connection name"
|
||||
namePlaceholder = "e.g. Claims bucket"
|
||||
|
||||
[portal.connections.table]
|
||||
bucket = "Bucket"
|
||||
name = "Name"
|
||||
region = "Region"
|
||||
|
||||
[portal.docs.authentication]
|
||||
codeCaption = "every request"
|
||||
eyebrow = "GETTING STARTED"
|
||||
@@ -7341,10 +7528,6 @@ operations_one = "Operation ({{count}})"
|
||||
operations_other = "Operations ({{count}})"
|
||||
output = "Output"
|
||||
removeStep = "Remove operation"
|
||||
s3Configure = "Configure"
|
||||
s3Done = "Done"
|
||||
s3ModalTitle = "Amazon S3 output"
|
||||
s3NotConfigured = "Not configured"
|
||||
s3PrefixHelp = "Outputs are uploaded under this key prefix."
|
||||
save = "Save changes"
|
||||
scheduleEvery = "Run every"
|
||||
@@ -7415,6 +7598,7 @@ manual = "Manual"
|
||||
schedule = "Scheduled"
|
||||
|
||||
[portal.policies]
|
||||
defaultName = "{{category}} Policy"
|
||||
subtitle = "Standing automations that enforce a tool pipeline on every document. Each policy fires on upload or export, runs its tool chain, and saves the enforced version alongside the original."
|
||||
title = "Policies"
|
||||
|
||||
@@ -7986,34 +8170,29 @@ primaryNav = "Primary navigation"
|
||||
switchApp = "Switch app"
|
||||
|
||||
[portal.sources]
|
||||
subtitle = "Reusable input connections that feed documents into Stirling. Configure a connection once, then reference it from any number of policies. Click a row for its config and which policies use it."
|
||||
subtitle = "Reusable input connections that feed documents into Stirling. Configure a source once, then reference it from any number of pipelines."
|
||||
title = "Sources"
|
||||
|
||||
[portal.sources.actions]
|
||||
agentBuilder = "Agent Builder"
|
||||
connectSource = "Connect source"
|
||||
|
||||
[portal.sources.builder]
|
||||
back = "Back to sources"
|
||||
cancel = "Cancel"
|
||||
create = "Create source"
|
||||
createTitle = "Connect a source"
|
||||
delete = "Delete"
|
||||
editTitle = "Edit source"
|
||||
enabled = "Enabled"
|
||||
save = "Save changes"
|
||||
|
||||
[portal.sources.delete]
|
||||
body = "Delete \"{{name}}\"? This can't be undone. Policies that reference it would need to be updated."
|
||||
cancel = "Cancel"
|
||||
confirm = "Delete"
|
||||
title = "Delete source?"
|
||||
|
||||
[portal.sources.detail]
|
||||
closeAriaLabel = "Close detail"
|
||||
delete = "Delete source"
|
||||
docs24h = "Last 24h"
|
||||
docs30d = "Last 30 days"
|
||||
docsTotal = "Total seen"
|
||||
docsTrend = "Documents over the last 30 days"
|
||||
documents = "Documents"
|
||||
edit = "Edit"
|
||||
notReferenced = "Not referenced by any policy, so it's safe to delete."
|
||||
pause = "Pause"
|
||||
resume = "Resume"
|
||||
subtitle = "{{type}} · {{status}}"
|
||||
usedBy = "Used by"
|
||||
|
||||
[portal.sources.empty]
|
||||
description = "Connect a folder (and, soon, cloud storage) so your policies have somewhere to pull documents from."
|
||||
title = "No sources connected yet"
|
||||
@@ -8029,10 +8208,15 @@ disabled = "Disabled"
|
||||
unused = "Unused"
|
||||
|
||||
[portal.sources.table]
|
||||
documents = "Documents"
|
||||
source = "Source"
|
||||
status = "Status"
|
||||
usedBy = "Policies"
|
||||
|
||||
[portal.sources.tabs]
|
||||
connections = "Connections"
|
||||
sources = "Sources"
|
||||
|
||||
[portal.sources.types.editor]
|
||||
description = "Documents your team has processed in the editor, across policy and AI runs."
|
||||
label = "Editor"
|
||||
@@ -8080,6 +8264,10 @@ label = "Access key ID"
|
||||
label = "Bucket"
|
||||
placeholder = "my-company-inbox"
|
||||
|
||||
[portal.sources.types.s3.fields.connection]
|
||||
helperText = "The stored connection holding the bucket and credentials. Reused by every source and pipeline output that references it."
|
||||
label = "Connection"
|
||||
|
||||
[portal.sources.types.s3.fields.endpoint]
|
||||
helperText = "Leave blank for Amazon S3. Set to use an S3-compatible service such as MinIO."
|
||||
label = "Custom endpoint"
|
||||
@@ -8109,21 +8297,14 @@ label = "Secret access key"
|
||||
label = "Source"
|
||||
|
||||
[portal.sources.wizard]
|
||||
back = "Back"
|
||||
cancel = "Cancel"
|
||||
continue = "Continue"
|
||||
editTitle = "Edit source"
|
||||
name = "Name"
|
||||
namePlaceholder = "e.g. Claims intake"
|
||||
save = "Save changes"
|
||||
subtitle = "Step {{current}} of {{total}} · {{label}}"
|
||||
title = "Connect a source"
|
||||
type = "Type"
|
||||
|
||||
[portal.sources.wizard.steps]
|
||||
chooseType = "Choose type"
|
||||
configure = "Configure"
|
||||
review = "Review & connect"
|
||||
[portal.tier]
|
||||
enterprise = "Enterprise plan"
|
||||
free = "Editor plan"
|
||||
pro = "Processor plan"
|
||||
|
||||
[portal.usage]
|
||||
managePayment = "Manage Payment"
|
||||
@@ -8925,6 +9106,13 @@ title = "Signature Order"
|
||||
[settings]
|
||||
close = "Close"
|
||||
|
||||
[settings.ai]
|
||||
documents = "Documents & RAG"
|
||||
general = "General"
|
||||
limits = "Limits & Performance"
|
||||
models = "Models & Providers"
|
||||
title = "AI"
|
||||
|
||||
[settings.configuration]
|
||||
advanced = "Advanced"
|
||||
database = "Database"
|
||||
@@ -10139,6 +10327,19 @@ resetPw = "Reset password"
|
||||
suspend = "Suspend"
|
||||
unlock = "Unlock account"
|
||||
|
||||
[users.activity]
|
||||
daysAgo = "{{count}}d ago"
|
||||
hoursAgo = "{{count}}h ago"
|
||||
justNow = "Just now"
|
||||
minutesAgo = "{{count}}m ago"
|
||||
monthsAgo_one = "{{count}} month ago"
|
||||
monthsAgo_other = "{{count}} months ago"
|
||||
never = "Never"
|
||||
weeksAgo_one = "{{count}} week ago"
|
||||
weeksAgo_other = "{{count}} weeks ago"
|
||||
yearsAgo_one = "{{count}} year ago"
|
||||
yearsAgo_other = "{{count}} years ago"
|
||||
|
||||
[users.cap]
|
||||
addProcessor = "+ Processor"
|
||||
approver = "Approves policy"
|
||||
@@ -10209,7 +10410,9 @@ by = "Invited by {{who}}"
|
||||
cancel = "Cancel"
|
||||
count = "{{count}} pending"
|
||||
desc = "Invited people who haven't joined yet. They hold a seat until they accept."
|
||||
expires = "Expires"
|
||||
expiresInDays_one = "Expires in {{count}} day"
|
||||
expiresInDays_other = "Expires in {{count}} days"
|
||||
expiresToday = "Expires today"
|
||||
title = "Pending invitations"
|
||||
|
||||
[users.loadError]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "Stirling PDF",
|
||||
"mainBinaryName": "Stirling-PDF",
|
||||
"version": "2.14.1",
|
||||
"version": "2.14.2",
|
||||
"identifier": "stirling.pdf.dev",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -32,6 +32,10 @@ export const VALID_NAV_KEYS = [
|
||||
"adminEndpoints",
|
||||
"adminStorageSharing",
|
||||
"adminMcp",
|
||||
"adminAiGeneral",
|
||||
"adminAiModels",
|
||||
"adminAiDocuments",
|
||||
"adminAiLimits",
|
||||
"help",
|
||||
"legal",
|
||||
"backendThirdPartyLicenses",
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
import {
|
||||
deserializeToolStep,
|
||||
getExecutableTools,
|
||||
serializeStepFromEndpoint,
|
||||
serializeToolStep,
|
||||
stepRequiresUpload,
|
||||
type WorkingToolStep,
|
||||
@@ -199,41 +198,6 @@ describe("serialize/deserialize round-trip", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeStepFromEndpoint", () => {
|
||||
test("maps a wizard step's UI params to the backend contract, filling defaults", () => {
|
||||
// The shape the policy setup wizard holds: an endpoint plus UI-shaped params
|
||||
// (redact's `wordsToRedact`), with several fields left to their defaults.
|
||||
const api = serializeStepFromEndpoint(
|
||||
"/api/v1/security/auto-redact",
|
||||
{ mode: "automatic", useRegex: true, wordsToRedact: ["ssn", "card"] },
|
||||
dynamicRegistry,
|
||||
);
|
||||
|
||||
expect(api.operation).toBe("/api/v1/security/auto-redact");
|
||||
// wordsToRedact -> listOfText (the field the backend actually reads), and the
|
||||
// frontend-only `mode` is dropped.
|
||||
expect(api.parameters).toMatchObject({ listOfText: "ssn\ncard" });
|
||||
expect(api.parameters).not.toHaveProperty("wordsToRedact");
|
||||
expect(api.parameters).not.toHaveProperty("mode");
|
||||
// Fields the wizard never set still get their defaults so the body is complete.
|
||||
expect(api.parameters).toHaveProperty("wholeWordSearch");
|
||||
expect(api.parameters).toHaveProperty("customPadding");
|
||||
});
|
||||
|
||||
test("passes an unmapped endpoint's params through unchanged", () => {
|
||||
expect(
|
||||
serializeStepFromEndpoint(
|
||||
"/api/v1/unknown/thing",
|
||||
{ keep: true },
|
||||
dynamicRegistry,
|
||||
),
|
||||
).toEqual({
|
||||
operation: "/api/v1/unknown/thing",
|
||||
parameters: { keep: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("stepRequiresUpload", () => {
|
||||
const step = (params: Record<string, unknown>): WorkingToolStep => ({
|
||||
toolId: "compress" as ToolId,
|
||||
|
||||
@@ -197,31 +197,6 @@ export function serializeToolStep(
|
||||
return { operation, parameters };
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a step held as an endpoint path plus frontend-shaped params - the form the policy setup
|
||||
* wizard keeps, where params match the tool's UI shape (e.g. redact's `wordsToRedact`) rather than
|
||||
* the backend contract - into the backend step contract, mapping params through the tool's
|
||||
* `toApiParams` (merged over its defaults, so fields the wizard never set still get their defaults).
|
||||
* The endpoint maps to a tool by path, so this works for dynamic-endpoint tools whose config
|
||||
* endpoint is a function. Endpoints that map to no known tool pass through unchanged.
|
||||
*/
|
||||
export function serializeStepFromEndpoint(
|
||||
operation: string,
|
||||
params: ErasedToolParams,
|
||||
registry: Partial<ToolRegistry>,
|
||||
): ToolApiStep {
|
||||
const match = findToolByEndpoint({ operation, parameters: params }, registry);
|
||||
const config = match?.[1].operationConfig;
|
||||
if (!config) return { operation, parameters: params };
|
||||
const merged = { ...(config.defaultParameters ?? {}), ...params };
|
||||
return {
|
||||
operation: resolveEndpoint(config, merged) ?? operation,
|
||||
parameters: config.toApiParams
|
||||
? (config.toApiParams(merged) as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the registry tool for a stored step's endpoint: exact match for static endpoints, else
|
||||
* membership in a dynamic tool's declared `endpoints` set (replaying its function can't recover a
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describeToolOperation } from "@app/hooks/tools/shared/toolOperationDescriptor";
|
||||
|
||||
interface Params {
|
||||
a: number;
|
||||
}
|
||||
|
||||
// A minimal config that type-checks against the flatten endpoint's model.
|
||||
const CONFIG = {
|
||||
endpoint: "/api/v1/misc/flatten" as const,
|
||||
defaultParameters: { a: 1 } satisfies Params,
|
||||
toApiParams: (p: Params) => ({ renderDpi: p.a }),
|
||||
fromApiParams: (api: { renderDpi?: number }) => ({ a: api.renderDpi ?? 0 }),
|
||||
};
|
||||
|
||||
describe("describeToolOperation", () => {
|
||||
test("wraps the config's mappers and endpoint into a descriptor", () => {
|
||||
const d = describeToolOperation("/api/v1/misc/flatten", CONFIG);
|
||||
expect(d.endpoint).toBe("/api/v1/misc/flatten");
|
||||
expect(d.toApi({ a: 200 })).toEqual({ renderDpi: 200 });
|
||||
});
|
||||
|
||||
test("fromApi merges the mapped values over the defaults", () => {
|
||||
const d = describeToolOperation("/api/v1/misc/flatten", CONFIG);
|
||||
expect(d.fromApi({ renderDpi: 72 })).toEqual({ a: 72 });
|
||||
});
|
||||
|
||||
test("throws when the config lacks a mapper", () => {
|
||||
expect(() =>
|
||||
describeToolOperation("/api/v1/misc/flatten", {
|
||||
endpoint: "/api/v1/misc/flatten" as const,
|
||||
defaultParameters: { a: 1 },
|
||||
toApiParams: (p: Params) => ({ renderDpi: p.a }),
|
||||
}),
|
||||
).toThrow(/mappers/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Typed wrapper over a tool's `toApiParams`/`fromApiParams` mappers, binding one endpoint to safe
|
||||
* frontend<->backend parameter conversion.
|
||||
*/
|
||||
|
||||
import type { ToolApiParams, ToolEndpoint } from "@app/types/toolApiTypes";
|
||||
|
||||
export interface ToolOperationDescriptor<E extends ToolEndpoint, TParams> {
|
||||
readonly endpoint: E;
|
||||
readonly defaultParameters: TParams;
|
||||
toApi(params: TParams): ToolApiParams[E];
|
||||
/** Backend model -> full frontend params (defaults merged under the mapped values). */
|
||||
fromApi(api: ToolApiParams[E]): TParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural subset of a tool's config. `CE` is the config's declared endpoint type, inferred from
|
||||
* the `endpoint` field: the literal for static tools, or the whole `ToolEndpoint` union for
|
||||
* dynamic-endpoint tools (whose endpoint is a function typed against the union).
|
||||
*/
|
||||
export interface BidirectionalToolConfig<TParams, CE extends ToolEndpoint> {
|
||||
endpoint: CE | null | ((params: TParams) => CE | null);
|
||||
defaultParameters?: TParams;
|
||||
toApiParams?(params: TParams): ToolApiParams[CE];
|
||||
fromApiParams?(api: ToolApiParams[CE]): Partial<TParams>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pin a config to `endpoint` (passed explicitly, since dynamic-endpoint tools declare `endpoint` as
|
||||
* a function). `E extends CE` rejects pairing a static tool's config with the wrong endpoint, while
|
||||
* allowing a dynamic tool whose `CE` is the full union. Throws when mappers or defaults are missing.
|
||||
*/
|
||||
export function describeToolOperation<
|
||||
E extends CE,
|
||||
CE extends ToolEndpoint,
|
||||
TParams,
|
||||
>(
|
||||
endpoint: E,
|
||||
config: BidirectionalToolConfig<TParams, CE>,
|
||||
): ToolOperationDescriptor<E, TParams> {
|
||||
const { toApiParams, fromApiParams, defaultParameters } = config;
|
||||
if (!toApiParams || !fromApiParams || defaultParameters === undefined) {
|
||||
throw new Error(
|
||||
`describeToolOperation: "${endpoint}" is missing mappers or defaults`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
endpoint,
|
||||
defaultParameters,
|
||||
// A dynamic tool's mapper is typed against the union; narrow to this endpoint (sound - the
|
||||
// runtime mapper produces this endpoint's model).
|
||||
toApi: (params) => toApiParams(params) as ToolApiParams[E],
|
||||
fromApi: (api) =>
|
||||
({
|
||||
...defaultParameters,
|
||||
...fromApiParams(api as ToolApiParams[CE]),
|
||||
}) as TParams,
|
||||
};
|
||||
}
|
||||
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
|
||||
|
||||
const BASE_NO_LOGIN_CONFIG: AppConfig = {
|
||||
enableAnalytics: true,
|
||||
appVersion: "2.14.1",
|
||||
appVersion: "2.14.2",
|
||||
serverCertificateEnabled: false,
|
||||
enableAlphaFunctionality: false,
|
||||
serverPort: 8080,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user