Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7500150fbd | ||
|
|
776749277c | ||
|
|
41b1b89fcb | ||
|
|
4d4e994562 | ||
|
|
2b118556f3 | ||
|
|
fbaff56d1c | ||
|
|
a1b15e0570 | ||
|
|
76549288a9 | ||
|
|
b5d0c4a5ed | ||
|
|
8bfcf6eb7e | ||
|
|
b019f9b570 | ||
|
|
d7df87b684 | ||
|
|
6e4e3e138c | ||
|
|
13ca7bd52e | ||
|
|
456a96e15c | ||
|
|
7c8a46255b | ||
|
|
f1332ebe4f | ||
|
|
d4a3df79e5 | ||
|
|
376c9aeb31 | ||
|
|
19377cc688 | ||
|
|
b22ffb3b3b | ||
|
|
6319936720 | ||
|
|
aca0be7b71 | ||
|
|
1c6e9e8158 | ||
|
|
e0e20559b6 | ||
|
|
af694d506d | ||
|
|
d5806b56dd | ||
|
|
49dbf76670 | ||
|
|
0a7cd1185d | ||
|
|
e67bb77a59 | ||
|
|
ae1f905975 | ||
|
|
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.
|
||||
|
||||
-515
@@ -1,515 +0,0 @@
|
||||
package stirling.software.SPDF.controller.api;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.annotations.api.GeneralApi;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
|
||||
/**
|
||||
* Charcode-encode helper for the v2 PDF text editor.
|
||||
*
|
||||
* <p>The frontend editor uses PDFium-WASM, which exposes {@code FPDFText_SetCharcodes} for writing
|
||||
* new text using raw font charcodes (skipping PDFium's broken reverse Unicode→CID lookup for
|
||||
* embedded subset fonts). What PDFium does NOT expose is the byte-encoding side of an existing font
|
||||
* - given a PDFont and a Unicode string, what are the bytes the font's encoding produces? PDFBox
|
||||
* does have that ({@link PDFont#encode}).
|
||||
*
|
||||
* <p>This endpoint accepts the source PDF + a "locator" describing where to find the font in
|
||||
* question (page index + a sample char known to render in the target font, optionally narrowed by
|
||||
* the font's /BaseFont name) + the Unicode text the frontend wants to encode. It returns the
|
||||
* charcode sequence the frontend can pass to {@code FPDFText_SetCharcodes}.
|
||||
*
|
||||
* <p>If the locator can't find a matching text fragment, or if the font can't encode some chars,
|
||||
* the response reports which chars are missing so the frontend can fall back to Helvetica per char.
|
||||
*/
|
||||
@Slf4j
|
||||
@GeneralApi
|
||||
@RequiredArgsConstructor
|
||||
public class PdfTextEditorV2CharcodeController {
|
||||
|
||||
/** Reject JSON bodies whose base64 implies a decoded PDF larger than this. */
|
||||
private static final int MAX_PDF_BYTES = 100 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Upper bound on {@code request.text} code units. Editor requests are word-sized; an unbounded
|
||||
* text drove a per-code-point encode/exception loop (CPU burn) on crafted requests.
|
||||
*/
|
||||
private static final int MAX_TEXT_CHARS = 4096;
|
||||
|
||||
/** Nested form-XObject resource dictionaries visited per lookup (cycle/DoS guard). */
|
||||
private static final int MAX_RESOURCE_DICTS = 32;
|
||||
|
||||
/** Bound on the reverse-map cache so a busy multi-document server can't grow it forever. */
|
||||
private static final int REVERSE_MAP_CACHE_MAX = 32;
|
||||
|
||||
/** Access-ordered LRU bounded at {@link #REVERSE_MAP_CACHE_MAX} entries. */
|
||||
private static final class BoundedReverseMapCache
|
||||
extends java.util.LinkedHashMap<String, java.util.Map<String, Long>> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
BoundedReverseMapCache() {
|
||||
super(16, 0.75f, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean removeEldestEntry(
|
||||
java.util.Map.Entry<String, java.util.Map<String, Long>> eldest) {
|
||||
return size() > REVERSE_MAP_CACHE_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse Unicode→charcode maps, cached by {@code pdfContentHash + "|" + fontName} so repeated
|
||||
* edits on the SAME document reuse the 0..0xFFFF {@code toUnicode} probe instead of re-running
|
||||
* it (up to 65 536 lookups per font) on every keystroke's request. Access-ordered LRU bounded
|
||||
* by {@link #REVERSE_MAP_CACHE_MAX}.
|
||||
*
|
||||
* <p>The previous {@code WeakHashMap<PDFont, ...>} never hit across requests: every request
|
||||
* loads a fresh {@link PDDocument} hence a fresh {@link PDFont} instance, so the key was never
|
||||
* equal from one request to the next - it was effectively dead code. Keying on the PDF bytes'
|
||||
* hash gives a stable cross-request key.
|
||||
*/
|
||||
private static final java.util.Map<String, java.util.Map<String, Long>> REVERSE_MAP_CACHE =
|
||||
java.util.Collections.synchronizedMap(new BoundedReverseMapCache());
|
||||
|
||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||
|
||||
// NOTE: PDFBox's PDSimpleFont emits one "No Unicode mapping for .notdef" WARN per probed
|
||||
// charcode when buildReverseUnicodeMap iterates 0..0xFFFF, which once flooded info.log to
|
||||
// ~1.4 GB overnight. That logger is silenced DECLARATIVELY in logback.xml (a config entry ops
|
||||
// can see and revert) rather than by mutating the global logger from a static block here -
|
||||
// mutating it at class-load time hid the same warnings from every other tool in the JVM with
|
||||
// no trace in configuration.
|
||||
|
||||
@Data
|
||||
public static class EncodeCharcodesRequest {
|
||||
|
||||
/** Base64-encoded original PDF. The frontend already has the bytes loaded. */
|
||||
private String pdfBase64;
|
||||
|
||||
/** 0-based page index containing the font sample. */
|
||||
private int pageIndex;
|
||||
|
||||
/**
|
||||
* A char known to exist on the page in the target font. Combined with {@code fontName}
|
||||
* (when supplied) it locates the source PDFont via its ToUnicode CMap.
|
||||
*/
|
||||
private String locatorChar;
|
||||
|
||||
/**
|
||||
* Optional /BaseFont name of the target font (as PDFium's FPDFFont_GetBaseFontName reports
|
||||
* it). When a page has TWO fonts that both render {@code locatorChar}, this disambiguates
|
||||
* which one to encode against - otherwise the first font found wins and a cross-font edit
|
||||
* gets the wrong font's charcode. Null = keep the legacy first-match behaviour.
|
||||
*/
|
||||
private String fontName;
|
||||
|
||||
/** Unicode text the frontend wants to encode. */
|
||||
private String text;
|
||||
}
|
||||
|
||||
@Data
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public static class EncodeCharcodesResponse {
|
||||
/**
|
||||
* Per-char charcode array (one entry per code point in {@code request.text}). When the
|
||||
* font's encoding produces multi-byte sequences, each char gets the full unsigned int value
|
||||
* of its bytes packed big-endian (so a 2-byte CID like 0x004D becomes 77).
|
||||
*/
|
||||
private List<Long> charcodes;
|
||||
|
||||
/** Chars from the request that the font couldn't encode. */
|
||||
private List<String> missing;
|
||||
|
||||
/** Diagnostic note - included so the frontend HUD can show what happened. */
|
||||
private String note;
|
||||
|
||||
/** Set when the request failed entirely (bad pdf bytes, no matching font, etc.). */
|
||||
private String error;
|
||||
}
|
||||
|
||||
@Operation(
|
||||
summary = "Encode Unicode → font charcodes for the v2 PDF text editor",
|
||||
description =
|
||||
"""
|
||||
Frontend-only helper: takes the source PDF, a locator pointing at an existing
|
||||
char rendered in the target font, and a Unicode string. Returns the byte
|
||||
sequence the target font produces for that Unicode, packed as one unsigned
|
||||
int per char. The frontend then calls FPDFText_SetCharcodes with the
|
||||
returned ints to inject new text that reuses the embedded font's actual
|
||||
glyphs. Chars the font can't encode are listed in `missing` so the caller
|
||||
can fall back per-char.
|
||||
""")
|
||||
@PostMapping(
|
||||
value = "/pdf-text-editor-v2/encode-charcodes",
|
||||
consumes = "application/json",
|
||||
produces = "application/json")
|
||||
public ResponseEntity<EncodeCharcodesResponse> encodeCharcodes(
|
||||
@RequestBody EncodeCharcodesRequest request) {
|
||||
EncodeCharcodesResponse resp = new EncodeCharcodesResponse();
|
||||
if (request == null
|
||||
|| request.getPdfBase64() == null
|
||||
|| request.getText() == null
|
||||
|| request.getLocatorChar() == null) {
|
||||
resp.setError("missing required fields");
|
||||
return ResponseEntity.badRequest().body(resp);
|
||||
}
|
||||
// length/4*3 bounds the decoded size without decoding, so we reject early before
|
||||
// allocating.
|
||||
String b64 = request.getPdfBase64();
|
||||
if ((long) b64.length() / 4 * 3 > MAX_PDF_BYTES) {
|
||||
resp.setError("pdf too large");
|
||||
return ResponseEntity.status(413).body(resp);
|
||||
}
|
||||
if (request.getText().length() > MAX_TEXT_CHARS || request.getLocatorChar().length() > 4) {
|
||||
resp.setError("text too long");
|
||||
return ResponseEntity.badRequest().body(resp);
|
||||
}
|
||||
byte[] pdfBytes;
|
||||
try {
|
||||
pdfBytes = Base64.getDecoder().decode(b64);
|
||||
} catch (IllegalArgumentException e) {
|
||||
resp.setError("pdfBase64 is not valid base64");
|
||||
return ResponseEntity.badRequest().body(resp);
|
||||
}
|
||||
try (PDDocument doc = pdfDocumentFactory.load(pdfBytes, true)) {
|
||||
if (request.getPageIndex() < 0 || request.getPageIndex() >= doc.getNumberOfPages()) {
|
||||
resp.setError("pageIndex out of range");
|
||||
return ResponseEntity.badRequest().body(resp);
|
||||
}
|
||||
PDPage page = doc.getPage(request.getPageIndex());
|
||||
// Skip walking the page's content stream (it crashes on Type3 fonts with
|
||||
// UnsupportedOperationException("Not implemented: Type3") before we can do anything
|
||||
// useful). Instead enumerate the page's font resources and pick the first one whose
|
||||
// ToUnicode CMap maps SOME charcode to the locator char.
|
||||
// For Chrome/Skia-printed PDFs that emit one Type3 font per glyph, this lands on
|
||||
// the exact font that renders the locator char.
|
||||
PDFont font =
|
||||
findFontByToUnicode(page, request.getLocatorChar(), request.getFontName(), doc);
|
||||
if (font == null) {
|
||||
resp.setError(
|
||||
"no font on page "
|
||||
+ request.getPageIndex()
|
||||
+ " renders locatorChar="
|
||||
+ request.getLocatorChar()
|
||||
+ (request.getFontName() != null
|
||||
? " (fontName=" + request.getFontName() + ")"
|
||||
: ""));
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
// Build a reverse Unicode→charcode map by walking the font's ToUnicode CMap.
|
||||
// This is the ONLY path that works for Type3 fonts (PDFBox's font.encode() throws
|
||||
// "Not implemented: Type3" on them), and it also acts as a more reliable fallback
|
||||
// for subset fonts whose encode() rejects chars not in the original document.
|
||||
//
|
||||
// For Sample.pdf specifically, every embedded font is Type3 (Chrome/Skia output),
|
||||
// but they all carry a ToUnicode CMap mapping CIDs back to Unicode. We iterate
|
||||
// charcodes 0..0xFFFF, call font.toUnicode(cc) for each, and record the inverse
|
||||
// mapping for the chars the user wants to write.
|
||||
java.util.Map<String, Long> reverseMap =
|
||||
buildReverseUnicodeMap(
|
||||
pdfBytes, font, request.getPageIndex(), request.getLocatorChar());
|
||||
List<Long> charcodes = new ArrayList<>();
|
||||
List<String> missing = new ArrayList<>();
|
||||
String text = request.getText();
|
||||
int i = 0;
|
||||
while (i < text.length()) {
|
||||
int cp = text.codePointAt(i);
|
||||
String oneChar = new String(Character.toChars(cp));
|
||||
i += Character.charCount(cp);
|
||||
// Whitespace is NEVER charcode-reused. Subset Type1/LaTeX fonts
|
||||
// usually have no real space glyph, yet font.encode(0x20) still
|
||||
// returns code 0x20 without throwing - and SetCharcodes(0x20)
|
||||
// then paints whatever glyph sits at that subset code (e.g. „
|
||||
// quotedblbase in LMRoman). Report whitespace as missing so the
|
||||
// frontend emits it as a positional gap instead.
|
||||
if (Character.isWhitespace(cp)) {
|
||||
missing.add(oneChar);
|
||||
continue;
|
||||
}
|
||||
// 1st try: font.encode() - works for Type0/TrueType/Type1
|
||||
Long packed = null;
|
||||
try {
|
||||
byte[] encoded = font.encode(oneChar);
|
||||
long p = 0L;
|
||||
for (byte b : encoded) p = (p << 8) | (b & 0xff);
|
||||
packed = p;
|
||||
} catch (IOException
|
||||
| IllegalArgumentException
|
||||
| UnsupportedOperationException encodeEx) {
|
||||
// 2nd try: ToUnicode reverse lookup - works for Type3 + anything with a CMap
|
||||
packed = reverseMap.get(oneChar);
|
||||
}
|
||||
if (packed != null) charcodes.add(packed);
|
||||
else missing.add(oneChar);
|
||||
}
|
||||
resp.setCharcodes(charcodes);
|
||||
if (!missing.isEmpty()) resp.setMissing(missing);
|
||||
resp.setNote(
|
||||
"font="
|
||||
+ font.getName()
|
||||
+ " encoded "
|
||||
+ charcodes.size()
|
||||
+ " of "
|
||||
+ (charcodes.size() + missing.size())
|
||||
+ " chars");
|
||||
return ResponseEntity.ok(resp);
|
||||
} catch (IOException e) {
|
||||
log.warn("encodeCharcodes: failed to load PDF", e);
|
||||
resp.setError("failed to load PDF");
|
||||
return ResponseEntity.badRequest().body(resp);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("encodeCharcodes: unexpected error", e);
|
||||
resp.setError("unexpected error");
|
||||
return ResponseEntity.status(500).body(resp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk every font resource on the page (and on any nested Form XObjects we can reach) and
|
||||
* return the FIRST font whose ToUnicode CMap includes the requested char. This avoids running
|
||||
* PDFStreamEngine.processPage, which throws UnsupportedOperationException on Type3 font glyph
|
||||
* rendering. The PDFont lookup itself is purely metadata-driven and works on all subtypes.
|
||||
*/
|
||||
/** How strictly {@code scanResources} compares a candidate font's name to the requested one. */
|
||||
private enum NameMatch {
|
||||
/** Full /BaseFont equality, subset tag included. */
|
||||
EXACT,
|
||||
/** Equality after stripping the "ABCDEF+" subset tag from both names. */
|
||||
STRIPPED,
|
||||
/** No name constraint: first font that renders the char wins. */
|
||||
ANY
|
||||
}
|
||||
|
||||
private static PDFont findFontByToUnicode(
|
||||
PDPage page, String wantChar, String fontName, PDDocument doc) {
|
||||
try {
|
||||
PDResources resources = page.getResources();
|
||||
// When a target font name is supplied, prefer an EXACT /BaseFont match (tag included)
|
||||
// BEFORE a tag-stripped one. Two distinct subsets of the same base font ("ABCDEF+Arial"
|
||||
// and "GHIJKL+Arial", common after a merge) share different charcode spaces but compare
|
||||
// equal once the tag is stripped, so an exact match must win first or we could encode
|
||||
// against the wrong subset. Only when no exact match exists do we fall back to the
|
||||
// tag-stripped comparison (a re-saved subset whose tag changed).
|
||||
if (fontName != null && !fontName.isEmpty()) {
|
||||
PDFont exact = scanResourceTree(resources, wantChar, fontName, NameMatch.EXACT);
|
||||
if (exact != null) return exact;
|
||||
PDFont stripped =
|
||||
scanResourceTree(resources, wantChar, fontName, NameMatch.STRIPPED);
|
||||
if (stripped != null) return stripped;
|
||||
// The frontend NAMED the font it is editing. Falling back to "any font that
|
||||
// renders the char" would hand back a DIFFERENT font's charcodes, which the
|
||||
// frontend then writes into the named font's text object - wrong glyph, and the
|
||||
// backend strategy skips all frontend validation. Report the char missing
|
||||
// instead so the caller takes its own fallback path.
|
||||
return null;
|
||||
}
|
||||
return scanResourceTree(resources, wantChar, null, NameMatch.ANY);
|
||||
} catch (RuntimeException ignore) {
|
||||
// Be defensive: any single bad font shouldn't sink the whole request.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Breadth-first {@link #scanResources} over the page's resources AND every nested form
|
||||
* XObject's resources (bounded by {@link #MAX_RESOURCE_DICTS}, cycle-safe). The v2 reader
|
||||
* surfaces form-XObject text as editable, so its fonts must be findable too - previously only
|
||||
* page-level resources were scanned and XObject text degraded to a wrong page font or
|
||||
* Helvetica.
|
||||
*/
|
||||
private static PDFont scanResourceTree(
|
||||
PDResources resources, String wantChar, String wantName, NameMatch mode) {
|
||||
java.util.ArrayDeque<PDResources> queue = new java.util.ArrayDeque<>();
|
||||
java.util.Set<org.apache.pdfbox.cos.COSDictionary> seen =
|
||||
java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
|
||||
if (resources != null) queue.add(resources);
|
||||
PDFont nameOnly = null;
|
||||
int visited = 0;
|
||||
while (!queue.isEmpty() && visited < MAX_RESOURCE_DICTS) {
|
||||
PDResources res = queue.poll();
|
||||
if (!seen.add(res.getCOSObject())) continue;
|
||||
visited++;
|
||||
ScanResult r = scanResources(res, wantChar, wantName, mode);
|
||||
if (r.probed() != null) return r.probed();
|
||||
if (nameOnly == null) nameOnly = r.nameOnly();
|
||||
try {
|
||||
for (org.apache.pdfbox.cos.COSName xn : res.getXObjectNames()) {
|
||||
try {
|
||||
org.apache.pdfbox.pdmodel.graphics.PDXObject xo = res.getXObject(xn);
|
||||
if (xo
|
||||
instanceof
|
||||
org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject form) {
|
||||
PDResources fr = form.getResources();
|
||||
if (fr != null) queue.add(fr);
|
||||
}
|
||||
} catch (IOException | RuntimeException ignore) {
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException ignore) {
|
||||
}
|
||||
}
|
||||
// A name-matching font whose ToUnicode probe missed (or that has no ToUnicode at all):
|
||||
// font.encode() may still succeed, so return it rather than degrading a correctly-named
|
||||
// font. Never used in ANY mode (no name constraint -> an unprobed font is arbitrary).
|
||||
return nameOnly;
|
||||
}
|
||||
|
||||
/** One probed match (ToUnicode hit) plus, for named modes, a name-only candidate. */
|
||||
private record ScanResult(PDFont probed, PDFont nameOnly) {}
|
||||
|
||||
/**
|
||||
* Return a font on the page that renders {@code wantChar}, subject to {@code mode}: {@code
|
||||
* EXACT} requires the /BaseFont to equal {@code wantName} verbatim, {@code STRIPPED} compares
|
||||
* with subset tags removed, {@code ANY} ignores the name entirely (first font with the char
|
||||
* wins).
|
||||
*/
|
||||
private static ScanResult scanResources(
|
||||
PDResources resources, String wantChar, String wantName, NameMatch mode) {
|
||||
if (resources == null) return new ScanResult(null, null);
|
||||
String wantStripped = stripSubsetTag(wantName);
|
||||
// Bound a crafted page declaring many fonts none of which match (CPU-DoS guard).
|
||||
int scanned = 0;
|
||||
final int MAX_FONTS = 64;
|
||||
PDFont nameOnly = null;
|
||||
for (org.apache.pdfbox.cos.COSName name : resources.getFontNames()) {
|
||||
if (++scanned > MAX_FONTS) break;
|
||||
PDFont font;
|
||||
try {
|
||||
font = resources.getFont(name);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
continue;
|
||||
}
|
||||
if (font == null) continue;
|
||||
if (mode == NameMatch.EXACT) {
|
||||
if (wantName == null || !wantName.equals(font.getName())) continue;
|
||||
} else if (mode == NameMatch.STRIPPED) {
|
||||
if (wantStripped == null || !wantStripped.equals(stripSubsetTag(font.getName()))) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Cheap inverse-CMap probe: iterate codes until we hit one whose toUnicode is wantChar.
|
||||
// For Type3 with at most ~16 glyphs, this is microseconds. For full Type0 subsets
|
||||
// it's a few-thousand-iteration scan.
|
||||
int upper = font.isStandard14() ? 256 : 0x10000;
|
||||
boolean probeHit = false;
|
||||
for (int cc = 0; cc < upper; cc++) {
|
||||
String u;
|
||||
try {
|
||||
u = font.toUnicode(cc);
|
||||
} catch (Exception ignore) {
|
||||
continue;
|
||||
}
|
||||
if (u != null && u.equals(wantChar)) {
|
||||
probeHit = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (probeHit) return new ScanResult(font, nameOnly);
|
||||
// Name matched but the probe missed (e.g. no ToUnicode CMap at all - common for
|
||||
// Type0/Identity-H). Remember it: font.encode() may still handle the chars.
|
||||
if (mode != NameMatch.ANY && nameOnly == null) nameOnly = font;
|
||||
}
|
||||
return new ScanResult(null, nameOnly);
|
||||
}
|
||||
|
||||
/** Drop the 6-letter "ABCDEF+" subset prefix PDF puts on subset /BaseFont names. */
|
||||
private static String stripSubsetTag(String fontName) {
|
||||
if (fontName == null) return null;
|
||||
if (fontName.length() > 7
|
||||
&& fontName.charAt(6) == '+'
|
||||
&& fontName.chars().limit(6).allMatch(c -> c >= 'A' && c <= 'Z')) {
|
||||
return fontName.substring(7);
|
||||
}
|
||||
return fontName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Unicode→charcode map for a font by iterating every charcode in 0..0xFFFF and asking
|
||||
* the font's ToUnicode CMap what Unicode it maps to. Charcodes that aren't in the CMap throw
|
||||
* inside toUnicode (PDFBox returns null or throws depending on font subtype), and those are
|
||||
* skipped silently.
|
||||
*
|
||||
* <p>This is the encoding inverse PDFBox doesn't expose directly. For Type3 fonts (where
|
||||
* font.encode() throws "Not implemented"), this is the ONLY way to write text in the same font
|
||||
* - we look up the user's char in the reverse map and pass that charcode to
|
||||
* FPDFText_SetCharcodes on the frontend.
|
||||
*
|
||||
* <p>The 0..0xFFFF range is sufficient for Type0/CIDFontType2 fonts (CIDs are 16-bit). For
|
||||
* single-byte fonts the loop short-circuits after 256. We don't go higher because no PDF font
|
||||
* has a CID outside that range in practice; the per-font result is memoised in {@link
|
||||
* #REVERSE_MAP_CACHE} so the 65 536-entry probe runs once per document+font, not per request.
|
||||
*/
|
||||
private static java.util.Map<String, Long> buildReverseUnicodeMap(
|
||||
byte[] pdfBytes, PDFont font, int pageIndex, String locatorChar) {
|
||||
// Cache by (PDF content hash | font name) so repeated edits on the SAME document reuse the
|
||||
// 0..0xFFFF probe instead of rebuilding it on every keystroke's request. Two fonts sharing
|
||||
// a name within one PDF (rare) would collide, but that is no worse than the previous
|
||||
// no-cross-request-cache behaviour, and the hash isolates different documents.
|
||||
//
|
||||
// NAME-LESS fonts (Skia/Chrome Type3 output has no /BaseFont, so getName() is null) must
|
||||
// NOT share one "hash|null" entry - every name-less font in the doc would be served the
|
||||
// FIRST one's map (wrong glyphs, trusted by the frontend). Key those by the lookup inputs
|
||||
// (page + locator char) instead: for identical bytes the font located from those inputs is
|
||||
// deterministic, so the cached map always belongs to the font that will consume it.
|
||||
String fname = font.getName();
|
||||
String key =
|
||||
fname != null
|
||||
? sha256Hex(pdfBytes) + "|n|" + fname
|
||||
: sha256Hex(pdfBytes) + "|p" + pageIndex + "|c|" + locatorChar;
|
||||
return REVERSE_MAP_CACHE.computeIfAbsent(key, k -> computeReverseUnicodeMap(font));
|
||||
}
|
||||
|
||||
/** Lowercase hex SHA-256 of the PDF bytes; used as the reverse-map cache key. */
|
||||
private static String sha256Hex(byte[] bytes) {
|
||||
try {
|
||||
byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes);
|
||||
StringBuilder sb = new StringBuilder(digest.length * 2);
|
||||
for (byte b : digest) {
|
||||
sb.append(Character.forDigit((b >> 4) & 0xf, 16));
|
||||
sb.append(Character.forDigit(b & 0xf, 16));
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (java.security.NoSuchAlgorithmException e) {
|
||||
// SHA-256 is always present in a JRE; fall back to a length+hash key just in case so
|
||||
// the cache still functions (correctness holds - collisions only cost a rebuild).
|
||||
return bytes.length + ":" + java.util.Arrays.hashCode(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static java.util.Map<String, Long> computeReverseUnicodeMap(PDFont font) {
|
||||
java.util.Map<String, Long> out = new java.util.HashMap<>();
|
||||
int upper = font.isStandard14() ? 256 : 0x10000;
|
||||
for (int cc = 0; cc < upper; cc++) {
|
||||
String u;
|
||||
try {
|
||||
u = font.toUnicode(cc);
|
||||
} catch (Exception ignore) {
|
||||
continue;
|
||||
}
|
||||
if (u == null || u.isEmpty()) continue;
|
||||
// First charcode wins for a given Unicode (the canonical mapping).
|
||||
out.putIfAbsent(u, (long) cc);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -15,62 +15,24 @@
|
||||
<encoder>
|
||||
<pattern>%d %p %c{1} [%thread] %m%n</pattern>
|
||||
</encoder>
|
||||
<!-- SizeAndTimeBased: rotate daily OR every 100 MB, keep 1 day of history,
|
||||
hard cap the appender's total disk footprint at 200 MB so a runaway
|
||||
logger can't ever fill the disk (see GENERAL appender note). -->
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/auth-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
<maxFileSize>100MB</maxFileSize>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/auth-%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<maxHistory>1</maxHistory>
|
||||
<totalSizeCap>200MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<!-- Rolling File Appender for General Logs
|
||||
|
||||
Why SizeAndTimeBased + totalSizeCap: a previous build of the v2 PDF
|
||||
text editor's reverse-CMap probe loop triggered PDSimpleFont to emit
|
||||
one "No Unicode mapping for .notdef" WARN per probed charcode per
|
||||
font per request. With TimeBasedRollingPolicy alone there was no
|
||||
size ceiling; info.log grew to 1.4 GB in a single day before the JVM
|
||||
choked. The class-level silencer fixes the specific offender, but
|
||||
this size cap is the defence-in-depth: any future logger that
|
||||
floods unexpectedly will roll + auto-delete instead of starving
|
||||
disk + Jetty threads. -->
|
||||
<!-- Rolling File Appender for General Logs -->
|
||||
<appender name="GENERAL" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/info.log</file>
|
||||
<encoder>
|
||||
<pattern>%d %p %c{1} [%thread] %m%n</pattern>
|
||||
</encoder>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
|
||||
<maxFileSize>100MB</maxFileSize>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/info-%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<maxHistory>1</maxHistory>
|
||||
<totalSizeCap>500MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
</appender>
|
||||
|
||||
<!-- Suppress PDFBox PDSimpleFont's per-charcode .notdef WARN.
|
||||
|
||||
Required by the v2 PDF text editor's `buildReverseUnicodeMap`
|
||||
which DELIBERATELY iterates every charcode in 0..0xFFFF to
|
||||
discover the encoding-to-Unicode map of an embedded subset
|
||||
font. For any subset font ~99% of those probes hit .notdef,
|
||||
and the default WARN level for those misses turned info.log
|
||||
into a 1.4 GB monster overnight.
|
||||
|
||||
This declarative logback entry is the SOLE mechanism: it is
|
||||
visible to ops and revertable via configuration. An earlier
|
||||
build also mutated this logger's level from a static block in
|
||||
PdfTextEditorV2CharcodeController, which silenced the same
|
||||
warnings JVM-wide with no trace in any config file - that
|
||||
static block has been removed in favour of this entry. -->
|
||||
<logger name="org.apache.pdfbox.pdmodel.font.PDSimpleFont"
|
||||
level="ERROR" additivity="false">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="GENERAL"/>
|
||||
</logger>
|
||||
|
||||
<!-- Root Logger -->
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
|
||||
-509
@@ -1,509 +0,0 @@
|
||||
package stirling.software.SPDF.controller.api;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
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.font.PDFont;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType0Font;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType1Font;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType3Font;
|
||||
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Probe: what can PDFBox actually do for font ENCODING on real-world PDFs. This is a diagnostic
|
||||
* test (not a regression) - run with --tests PdfBoxFontEncodingProbeTest -i to see stdout.
|
||||
*
|
||||
* <p>Answers these questions:
|
||||
*
|
||||
* <ol>
|
||||
* <li>Type0/CIDFontType2 subset: can we add a new glyph not in the original subset? (no, encode
|
||||
* throws IllegalArgumentException).
|
||||
* <li>Type1: same question.
|
||||
* <li>TrueType: same question.
|
||||
* <li>Can we load a fresh TTF via PDType0Font.load(doc, file) and write text with it? (yes,
|
||||
* primary path).
|
||||
* <li>Round-trip via getFontStream / re-embed - can it rehabilitate Type3? (no - Type3 has no
|
||||
* FontFile* program at all).
|
||||
* <li>What fonts ship with PDFBox / fontbox? (only LiberationSans-Regular.ttf + AFM for the 14
|
||||
* standard fonts; CFF/Type1 binaries are NOT bundled - Standard14Fonts.getMappedFontName
|
||||
* redirects unmappable ones to LiberationSans).
|
||||
* </ol>
|
||||
*/
|
||||
public class PdfBoxFontEncodingProbeTest {
|
||||
|
||||
private static final Path PROJECT_ROOT =
|
||||
Paths.get(System.getProperty("user.dir")).getParent().getParent();
|
||||
|
||||
private static final Path SAMPLE =
|
||||
PROJECT_ROOT.resolve("frontend/editor/public/samples/Sample.pdf");
|
||||
|
||||
private static final Path[] EXTRA_FIXTURES = {
|
||||
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/stirling-marketing.pdf"),
|
||||
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/multi-page-sample.pdf"),
|
||||
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/big-sample.pdf"),
|
||||
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/paragraph-sample.pdf"),
|
||||
PROJECT_ROOT.resolve("frontend/editor/src/core/tests/test-fixtures/user-sample.pdf"),
|
||||
};
|
||||
|
||||
/**
|
||||
* Rasterize the Q4b output (Sample.pdf with injected Liberation text) to confirm the new text
|
||||
* actually renders on top of the existing Type3 content.
|
||||
*/
|
||||
@Test
|
||||
public void probeRenderInjectedSample() throws IOException {
|
||||
Path liberation =
|
||||
PROJECT_ROOT.resolve(
|
||||
"app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");
|
||||
byte[] pdfBytes = Files.readAllBytes(SAMPLE);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
|
||||
PDPage page = doc.getPage(0);
|
||||
PDType0Font ttf;
|
||||
try (InputStream in = Files.newInputStream(liberation)) {
|
||||
ttf = PDType0Font.load(doc, in, true);
|
||||
}
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
doc, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||
cs.beginText();
|
||||
cs.setFont(ttf, 24);
|
||||
cs.newLineAtOffset(50, 120);
|
||||
cs.showText("INJECTED via PDType0Font.load - $@#&Z");
|
||||
cs.endText();
|
||||
}
|
||||
doc.save(out);
|
||||
}
|
||||
// Rasterize page 0 to a PNG so we can eyeball it.
|
||||
try (PDDocument check = Loader.loadPDF(out.toByteArray())) {
|
||||
PDFRenderer renderer = new PDFRenderer(check);
|
||||
java.awt.image.BufferedImage img = renderer.renderImageWithDPI(0, 100);
|
||||
Path png = PROJECT_ROOT.resolve("test-screenshots/pdfbox-probe-q4b-rendered.png");
|
||||
Files.createDirectories(png.getParent());
|
||||
ImageIO.write(img, "PNG", png.toFile());
|
||||
System.out.println(
|
||||
"Rendered injected sample to "
|
||||
+ png
|
||||
+ " - "
|
||||
+ img.getWidth()
|
||||
+ "x"
|
||||
+ img.getHeight());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a PDF in memory that uses a Type0/CIDFontType2 subset font (the kind Word / InDesign /
|
||||
* LibreOffice produce), then probe whether encode() can add a glyph that wasn't in the original
|
||||
* subset.
|
||||
*/
|
||||
@Test
|
||||
public void probeType0CIDFontType2Subset() throws IOException {
|
||||
System.out.println(
|
||||
"\n##################################################################\n"
|
||||
+ "Q1 probe: Type0/CIDFontType2 SUBSET can/cannot add new glyphs\n"
|
||||
+ "##################################################################\n");
|
||||
Path liberation =
|
||||
PROJECT_ROOT.resolve(
|
||||
"app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");
|
||||
|
||||
// Build a PDF that contains only "abc" subsetted from LiberationSans.
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage();
|
||||
doc.addPage(page);
|
||||
PDType0Font subset;
|
||||
try (InputStream in = Files.newInputStream(liberation)) {
|
||||
subset = PDType0Font.load(doc, in, true /* embedSubset */);
|
||||
}
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(subset, 12);
|
||||
cs.newLineAtOffset(100, 700);
|
||||
cs.showText("abc");
|
||||
cs.endText();
|
||||
}
|
||||
doc.save(baos);
|
||||
}
|
||||
|
||||
// Reload the produced PDF and try to add a NEW glyph through the embedded subset font.
|
||||
byte[] subsetPdf = baos.toByteArray();
|
||||
try (PDDocument doc = Loader.loadPDF(subsetPdf)) {
|
||||
PDResources res = doc.getPage(0).getResources();
|
||||
for (COSName fn : res.getFontNames()) {
|
||||
PDFont f = res.getFont(fn);
|
||||
System.out.println(
|
||||
" Subset font in saved PDF: "
|
||||
+ f.getName()
|
||||
+ " ("
|
||||
+ f.getClass().getSimpleName()
|
||||
+ ", subType="
|
||||
+ f.getSubType()
|
||||
+ ")");
|
||||
for (String ch : new String[] {"a", "b", "c", "Z", "z", "0", "$", "@", "X", " "}) {
|
||||
try {
|
||||
byte[] enc = f.encode(ch);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte b : enc) hex.append(String.format("%02X ", b & 0xff));
|
||||
System.out.println(
|
||||
" encode('" + ch + "') -> [" + hex.toString().trim() + "] OK");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
System.out.println(" encode('" + ch + "') UNSUPPORTED");
|
||||
} catch (IllegalArgumentException iae) {
|
||||
System.out.println(
|
||||
" encode('" + ch + "') MISSING - " + iae.getMessage());
|
||||
} catch (IOException ioe) {
|
||||
System.out.println(" encode('" + ch + "') IO ERR - " + ioe.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void probeExtraFixtures() throws IOException {
|
||||
System.out.println(
|
||||
"\n##################################################################\n"
|
||||
+ "Extra fixture font-class probe\n"
|
||||
+ "##################################################################\n");
|
||||
for (Path fixture : EXTRA_FIXTURES) {
|
||||
if (!Files.exists(fixture)) {
|
||||
System.out.println("(missing) " + fixture);
|
||||
continue;
|
||||
}
|
||||
System.out.println("\n=== " + fixture.getFileName() + " ===");
|
||||
byte[] bytes = Files.readAllBytes(fixture);
|
||||
try (PDDocument doc = Loader.loadPDF(bytes)) {
|
||||
Set<COSName> seen = new HashSet<>();
|
||||
for (int p = 0; p < doc.getNumberOfPages(); p++) {
|
||||
PDPage page = doc.getPage(p);
|
||||
PDResources res = page.getResources();
|
||||
if (res == null) continue;
|
||||
for (COSName name : res.getFontNames()) {
|
||||
if (!seen.add(name)) continue;
|
||||
try {
|
||||
PDFont f = res.getFont(name);
|
||||
if (f == null) continue;
|
||||
String fontFile = "none";
|
||||
PDFontDescriptor d = f.getFontDescriptor();
|
||||
if (d != null) {
|
||||
if (d.getFontFile() != null) fontFile = "FontFile";
|
||||
else if (d.getFontFile2() != null) fontFile = "FontFile2";
|
||||
else if (d.getFontFile3() != null) fontFile = "FontFile3";
|
||||
}
|
||||
String z = "?";
|
||||
try {
|
||||
f.encode("Z");
|
||||
z = "OK";
|
||||
} catch (UnsupportedOperationException ex) {
|
||||
z = "UNSUPPORTED";
|
||||
} catch (IllegalArgumentException ex) {
|
||||
z = "MISSING";
|
||||
} catch (IOException ex) {
|
||||
z = "IO_ERR";
|
||||
}
|
||||
System.out.println(
|
||||
" page "
|
||||
+ p
|
||||
+ " "
|
||||
+ name.getName()
|
||||
+ " -> "
|
||||
+ f.getName()
|
||||
+ " "
|
||||
+ f.getClass().getSimpleName()
|
||||
+ " ("
|
||||
+ f.getSubType()
|
||||
+ ", "
|
||||
+ fontFile
|
||||
+ ", embed="
|
||||
+ f.isEmbedded()
|
||||
+ ") encode('Z')="
|
||||
+ z);
|
||||
} catch (IOException e) {
|
||||
System.out.println(
|
||||
" page "
|
||||
+ p
|
||||
+ " "
|
||||
+ name.getName()
|
||||
+ " load failed: "
|
||||
+ e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void probeAllQuestions() throws IOException {
|
||||
System.out.println(
|
||||
"\n##################################################################\n"
|
||||
+ "PDFBox font-encoding probe (Sample.pdf + bundled fallback fonts)\n"
|
||||
+ "##################################################################\n");
|
||||
|
||||
// Discover every font in Sample.pdf so we have a real-world test set.
|
||||
byte[] pdfBytes = Files.readAllBytes(SAMPLE);
|
||||
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
|
||||
List<PDFont> allFonts = new ArrayList<>();
|
||||
Set<COSName> seen = new HashSet<>();
|
||||
for (int p = 0; p < doc.getNumberOfPages(); p++) {
|
||||
PDPage page = doc.getPage(p);
|
||||
PDResources res = page.getResources();
|
||||
if (res == null) continue;
|
||||
for (COSName name : res.getFontNames()) {
|
||||
if (!seen.add(name)) continue;
|
||||
try {
|
||||
PDFont f = res.getFont(name);
|
||||
if (f != null) allFonts.add(f);
|
||||
} catch (Exception e) {
|
||||
System.out.println(
|
||||
" (skipped " + name.getName() + " - " + e.getMessage() + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println(
|
||||
"Discovered " + allFonts.size() + " unique fonts across Sample.pdf:");
|
||||
for (PDFont f : allFonts) {
|
||||
System.out.println(
|
||||
" - "
|
||||
+ f.getName()
|
||||
+ " ("
|
||||
+ f.getClass().getSimpleName()
|
||||
+ ", subType="
|
||||
+ f.getSubType()
|
||||
+ ", embedded="
|
||||
+ f.isEmbedded()
|
||||
+ ")");
|
||||
}
|
||||
|
||||
// ------------------ Q1/Q2/Q3 ------------------
|
||||
// Try encoding a char that is NEVER in Sample.pdf via each font.
|
||||
// 'Z' is unlikely to be in the subset for most marketing pages.
|
||||
// Try several candidates to surface what each font can/can't add.
|
||||
String[] candidates = {"Z", "$", "@", "#", "Q", "&", "A", "0", "M"};
|
||||
for (PDFont f : allFonts) {
|
||||
System.out.println("\n=== Encode-probe for font: " + f.getName() + " ===");
|
||||
for (String ch : candidates) {
|
||||
try {
|
||||
byte[] enc = f.encode(ch);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte b : enc) hex.append(String.format("%02X ", b & 0xff));
|
||||
System.out.println(
|
||||
" encode('" + ch + "') -> [" + hex.toString().trim() + "] OK");
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
System.out.println(
|
||||
" encode('" + ch + "') UNSUPPORTED: " + uoe.getMessage());
|
||||
} catch (IllegalArgumentException iae) {
|
||||
System.out.println(" encode('" + ch + "') MISSING: " + iae.getMessage());
|
||||
} catch (IOException ioe) {
|
||||
System.out.println(" encode('" + ch + "') IO ERR: " + ioe.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ Q5 ------------------
|
||||
// For each font, see what's in the FontFile* stream - this is what we'd
|
||||
// have to round-trip through to "rehabilitate" a Type3 font.
|
||||
System.out.println("\n=== FontFile stream availability (Q5) ===");
|
||||
for (PDFont f : allFonts) {
|
||||
String kind = "none";
|
||||
int size = 0;
|
||||
PDFontDescriptor d = f.getFontDescriptor();
|
||||
if (d != null) {
|
||||
if (d.getFontFile() != null) {
|
||||
kind = "FontFile (Type1)";
|
||||
size = streamBytes(d.getFontFile().getCOSObject().createInputStream());
|
||||
} else if (d.getFontFile2() != null) {
|
||||
kind = "FontFile2 (TTF)";
|
||||
size = streamBytes(d.getFontFile2().getCOSObject().createInputStream());
|
||||
} else if (d.getFontFile3() != null) {
|
||||
kind = "FontFile3 (CFF/OpenType)";
|
||||
size = streamBytes(d.getFontFile3().getCOSObject().createInputStream());
|
||||
}
|
||||
}
|
||||
System.out.println(
|
||||
" "
|
||||
+ f.getName()
|
||||
+ " ("
|
||||
+ f.getClass().getSimpleName()
|
||||
+ "): "
|
||||
+ kind
|
||||
+ " ("
|
||||
+ size
|
||||
+ " bytes)");
|
||||
if (f instanceof PDType3Font) {
|
||||
System.out.println(
|
||||
" -> Type3 has CharProc streams, NOT a FontFile binary."
|
||||
+ " getFontStream() returns null. Round-trip rehab is impossible:");
|
||||
System.out.println(
|
||||
" each glyph is a mini content stream, not a glyph outline in a"
|
||||
+ " standard font format. We'd need to rasterize each CharProc to"
|
||||
+ " glyph outlines + build a fresh TTF/CFF from scratch.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ Q4: PDType0Font.load(doc, file) round-trip ------------------
|
||||
System.out.println("\n=== Q4: load fresh TTF and write text to a fresh PDF ===");
|
||||
Path liberation =
|
||||
PROJECT_ROOT.resolve(
|
||||
"app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");
|
||||
if (!Files.exists(liberation)) {
|
||||
System.out.println(" Liberation TTF not found at " + liberation);
|
||||
} else {
|
||||
try (PDDocument out = new PDDocument()) {
|
||||
PDPage page = new PDPage();
|
||||
out.addPage(page);
|
||||
PDType0Font ttf;
|
||||
try (InputStream in = Files.newInputStream(liberation)) {
|
||||
ttf = PDType0Font.load(out, in, true /* embedSubset */);
|
||||
}
|
||||
System.out.println(
|
||||
" Loaded TTF -> "
|
||||
+ ttf.getName()
|
||||
+ " ("
|
||||
+ ttf.getClass().getSimpleName()
|
||||
+ ")");
|
||||
String testText = "Hello world! 0123 Z $ @";
|
||||
byte[] encoded = ttf.encode(testText);
|
||||
System.out.println(
|
||||
" Encoded "
|
||||
+ testText.length()
|
||||
+ " chars -> "
|
||||
+ encoded.length
|
||||
+ " bytes (Identity-H = 2 bytes/glyph)");
|
||||
try (PDPageContentStream cs = new PDPageContentStream(out, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(ttf, 12);
|
||||
cs.newLineAtOffset(100, 700);
|
||||
cs.showText(testText);
|
||||
cs.endText();
|
||||
}
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
out.save(baos);
|
||||
Path tmp = Files.createTempFile("pdfbox-probe-q4-", ".pdf");
|
||||
Files.write(tmp, baos.toByteArray());
|
||||
System.out.println(
|
||||
" Wrote fresh-TTF PDF to "
|
||||
+ tmp
|
||||
+ " ("
|
||||
+ baos.size()
|
||||
+ " bytes) - opens cleanly.");
|
||||
|
||||
// Re-load to confirm the new font is embedded properly.
|
||||
try (PDDocument check = Loader.loadPDF(baos.toByteArray())) {
|
||||
PDResources res = check.getPage(0).getResources();
|
||||
for (COSName fn : res.getFontNames()) {
|
||||
PDFont f = res.getFont(fn);
|
||||
System.out.println(
|
||||
" embedded font: "
|
||||
+ f.getName()
|
||||
+ " ("
|
||||
+ f.getClass().getSimpleName()
|
||||
+ ", embedded="
|
||||
+ f.isEmbedded()
|
||||
+ ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ Q4b: load TTF into an EXISTING PDF (Sample.pdf) and append text ------
|
||||
System.out.println(
|
||||
"\n=== Q4b: load TTF into EXISTING Sample.pdf and write text on page 0 ===");
|
||||
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
|
||||
PDPage page = doc.getPage(0);
|
||||
PDType0Font ttf;
|
||||
try (InputStream in = Files.newInputStream(liberation)) {
|
||||
ttf = PDType0Font.load(doc, in, true);
|
||||
}
|
||||
// append-mode content stream so we don't disturb existing graphics
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
doc,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.APPEND,
|
||||
true /* compress */,
|
||||
true /* resetContext */)) {
|
||||
cs.beginText();
|
||||
cs.setFont(ttf, 12);
|
||||
cs.newLineAtOffset(50, 50);
|
||||
cs.showText("Injected via PDType0Font.load - $@#&");
|
||||
cs.endText();
|
||||
}
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
doc.save(baos);
|
||||
Path tmp = Files.createTempFile("pdfbox-probe-q4b-", ".pdf");
|
||||
Files.write(tmp, baos.toByteArray());
|
||||
System.out.println(
|
||||
" Wrote injected-text PDF to " + tmp + " (" + baos.size() + " bytes).");
|
||||
|
||||
// Verify by re-reading: how many fonts now on page 0?
|
||||
try (PDDocument check = Loader.loadPDF(baos.toByteArray())) {
|
||||
PDResources res = check.getPage(0).getResources();
|
||||
int count = 0;
|
||||
for (COSName fn : res.getFontNames()) {
|
||||
PDFont f = res.getFont(fn);
|
||||
count++;
|
||||
System.out.println(
|
||||
" page-0 font: "
|
||||
+ fn.getName()
|
||||
+ " -> "
|
||||
+ f.getName()
|
||||
+ " ("
|
||||
+ f.getClass().getSimpleName()
|
||||
+ ")");
|
||||
}
|
||||
System.out.println(" Total fonts on page 0: " + count);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ Q6: what fonts ship in PDFBox / fontbox ------------------
|
||||
System.out.println("\n=== Q6: bundled fonts (Standard14 redirect probe) ===");
|
||||
for (Standard14Fonts.FontName fn : Standard14Fonts.FontName.values()) {
|
||||
PDType1Font f = new PDType1Font(fn);
|
||||
String mapped = "" + Standard14Fonts.getMappedFontName(fn.getName());
|
||||
System.out.println(
|
||||
" Standard14 "
|
||||
+ fn.getName()
|
||||
+ " -> mapped='"
|
||||
+ mapped
|
||||
+ "' name="
|
||||
+ f.getName());
|
||||
}
|
||||
System.out.println(
|
||||
" (PDFBox bundles ONLY LiberationSans-Regular.ttf as a binary; the AFMs cover"
|
||||
+ " metrics for the 14 standard fonts but rendering Helvetica/Times/Courier"
|
||||
+ " glyphs falls back to LiberationSans glyphs at runtime when no system font"
|
||||
+ " is found.)");
|
||||
}
|
||||
|
||||
private static int streamBytes(InputStream is) {
|
||||
try (InputStream it = is) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
byte[] buf = new byte[4096];
|
||||
int n;
|
||||
while ((n = it.read(buf)) >= 0) baos.write(buf, 0, n);
|
||||
return baos.size();
|
||||
} catch (IOException e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
-316
@@ -1,316 +0,0 @@
|
||||
package stirling.software.SPDF.controller.api;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.Base64;
|
||||
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageContentStream;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType1Font;
|
||||
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import stirling.software.SPDF.controller.api.PdfTextEditorV2CharcodeController.EncodeCharcodesRequest;
|
||||
import stirling.software.SPDF.controller.api.PdfTextEditorV2CharcodeController.EncodeCharcodesResponse;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.service.PdfMetadataService;
|
||||
|
||||
/**
|
||||
* Regression coverage for the v2 text editor "spaces render as „" bug.
|
||||
*
|
||||
* <p>mushroom-life.pdf is a LaTeX document whose embedded LMRoman subset font has NO real space
|
||||
* glyph, yet {@code font.encode(" ")} still returns charcode 0x20 without throwing. Reusing that
|
||||
* code via {@code FPDFText_SetCharcodes} paints whatever glyph sits at subset code 0x20 - the
|
||||
* quotedblbase „. The controller must therefore report whitespace as {@code missing} so the
|
||||
* frontend emits it as a positional gap instead of a reused glyph.
|
||||
*/
|
||||
class PdfTextEditorV2CharcodeControllerTest {
|
||||
|
||||
private static PdfTextEditorV2CharcodeController controller() {
|
||||
return new PdfTextEditorV2CharcodeController(
|
||||
new CustomPDFDocumentFactory(mock(PdfMetadataService.class)));
|
||||
}
|
||||
|
||||
private static String mushroomBase64() throws Exception {
|
||||
try (InputStream in =
|
||||
PdfTextEditorV2CharcodeControllerTest.class.getResourceAsStream(
|
||||
"/pdftexteditor/mushroom-life.pdf")) {
|
||||
assertThat(in).as("mushroom-life.pdf test resource").isNotNull();
|
||||
return Base64.getEncoder().encodeToString(in.readAllBytes());
|
||||
}
|
||||
}
|
||||
|
||||
private static EncodeCharcodesRequest request(String text) throws Exception {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
req.setPdfBase64(mushroomBase64());
|
||||
req.setPageIndex(0);
|
||||
// findFontByToUnicode locates the font via the ToUnicode CMap - "M" exists on page 0.
|
||||
req.setLocatorChar("M");
|
||||
req.setText(text);
|
||||
return req;
|
||||
}
|
||||
|
||||
@Test
|
||||
void spaceIsReportedMissingNeverEncoded() throws Exception {
|
||||
PdfTextEditorV2CharcodeController controller = controller();
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request(" "));
|
||||
|
||||
EncodeCharcodesResponse body = resp.getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getError()).isNull();
|
||||
// The space must be reported missing, NOT handed back as a charcode
|
||||
// (0x20) the frontend would reuse into the „ glyph.
|
||||
assertThat(body.getMissing()).containsExactly(" ");
|
||||
assertThat(body.getCharcodes()).isNullOrEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void realCharsEncodeWhileWhitespaceStaysAGap() throws Exception {
|
||||
PdfTextEditorV2CharcodeController controller = controller();
|
||||
// "M M" - both M's must encode to real charcodes; only the space is a gap.
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request("M M"));
|
||||
|
||||
EncodeCharcodesResponse body = resp.getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getError()).isNull();
|
||||
assertThat(body.getCharcodes()).as("both M glyphs encode").hasSize(2);
|
||||
assertThat(body.getMissing()).containsExactly(" ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tabAndNewlineAreAlsoTreatedAsGaps() throws Exception {
|
||||
PdfTextEditorV2CharcodeController controller = controller();
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request("\t\n"));
|
||||
|
||||
EncodeCharcodesResponse body = resp.getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getMissing()).containsExactly("\t", "\n");
|
||||
assertThat(body.getCharcodes()).isNullOrEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* A page with two fonts that BOTH render 'A'. {@code fontName} must select which one to encode
|
||||
* against - the cross-font fix. Without it the first font in resources order won wins and a
|
||||
* cross-font edit got the wrong font's charcode.
|
||||
*/
|
||||
private static String twoFontBase64() throws Exception {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage();
|
||||
doc.addPage(page);
|
||||
PDType1Font helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
|
||||
PDType1Font times = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN);
|
||||
try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
|
||||
cs.beginText();
|
||||
cs.setFont(helvetica, 12);
|
||||
cs.newLineAtOffset(72, 720);
|
||||
cs.showText("A");
|
||||
cs.endText();
|
||||
cs.beginText();
|
||||
cs.setFont(times, 12);
|
||||
cs.newLineAtOffset(72, 700);
|
||||
cs.showText("A");
|
||||
cs.endText();
|
||||
}
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
doc.save(bos);
|
||||
return Base64.getEncoder().encodeToString(bos.toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
private static EncodeCharcodesRequest twoFontRequest(String fontName) throws Exception {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
req.setPdfBase64(twoFontBase64());
|
||||
req.setPageIndex(0);
|
||||
req.setLocatorChar("A");
|
||||
req.setFontName(fontName);
|
||||
req.setText("A");
|
||||
return req;
|
||||
}
|
||||
|
||||
@Test
|
||||
void fontNameDisambiguatesBetweenTwoFontsRenderingTheSameChar() throws Exception {
|
||||
PdfTextEditorV2CharcodeController controller = controller();
|
||||
|
||||
// Targeting Times-Roman must encode against Times-Roman, not whichever
|
||||
// font happens to appear first in the page's font resources.
|
||||
EncodeCharcodesResponse times =
|
||||
controller.encodeCharcodes(twoFontRequest("Times-Roman")).getBody();
|
||||
assertThat(times).isNotNull();
|
||||
assertThat(times.getError()).isNull();
|
||||
assertThat(times.getNote()).contains("Times-Roman");
|
||||
assertThat(times.getCharcodes()).hasSize(1);
|
||||
|
||||
// Targeting Helvetica must encode against Helvetica.
|
||||
EncodeCharcodesResponse helv =
|
||||
controller.encodeCharcodes(twoFontRequest("Helvetica")).getBody();
|
||||
assertThat(helv).isNotNull();
|
||||
assertThat(helv.getError()).isNull();
|
||||
assertThat(helv.getNote()).contains("Helvetica");
|
||||
assertThat(helv.getCharcodes()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownFontNameReportsNoFontInsteadOfWrongFont() throws Exception {
|
||||
PdfTextEditorV2CharcodeController controller = controller();
|
||||
// A name that matches no font on the page must NOT silently encode
|
||||
// against a different font: the frontend writes the returned charcodes
|
||||
// into the NAMED font's text object, so a first-match fallback would
|
||||
// bake wrong glyphs. It must report failure so the caller falls back.
|
||||
EncodeCharcodesResponse body =
|
||||
controller.encodeCharcodes(twoFontRequest("DoesNotExist")).getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getError()).contains("no font");
|
||||
assertThat(body.getCharcodes()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingRequiredFieldsReturns400() {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
req.setPdfBase64("AAAA");
|
||||
req.setLocatorChar("M");
|
||||
// text is null
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(400);
|
||||
assertThat(resp.getBody()).isNotNull();
|
||||
assertThat(resp.getBody().getError()).isEqualTo("missing required fields");
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidBase64Returns400() {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
req.setPdfBase64("!!!notbase64!!!");
|
||||
req.setLocatorChar("M");
|
||||
req.setText("M");
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(400);
|
||||
assertThat(resp.getBody()).isNotNull();
|
||||
assertThat(resp.getBody().getError()).isEqualTo("pdfBase64 is not valid base64");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageIndexOutOfRangeReturns400() throws Exception {
|
||||
EncodeCharcodesRequest req = request("M");
|
||||
req.setPageIndex(999);
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(400);
|
||||
assertThat(resp.getBody()).isNotNull();
|
||||
assertThat(resp.getBody().getError()).isEqualTo("pageIndex out of range");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonPdfBytesReturnsGenericError() {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
req.setPdfBase64(Base64.getEncoder().encodeToString("not a pdf".getBytes()));
|
||||
req.setLocatorChar("M");
|
||||
req.setText("M");
|
||||
// Must not throw, and must not leak the raw PDFBox parser message.
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
|
||||
assertThat(resp.getStatusCode().is4xxClientError()).isTrue();
|
||||
assertThat(resp.getBody()).isNotNull();
|
||||
assertThat(resp.getBody().getError()).isEqualTo("failed to load PDF");
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentLocatorCharReturns200WithError() throws Exception {
|
||||
// U+FFFF never appears in the document, so no font matches.
|
||||
ResponseEntity<EncodeCharcodesResponse> resp =
|
||||
controller().encodeCharcodes(requestWithLocator(""));
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(200);
|
||||
EncodeCharcodesResponse body = resp.getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getError()).isNotNull();
|
||||
assertThat(body.getCharcodes()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void oversizePdfRejected() {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
// A base64 string long enough that length/4*3 exceeds the 100MB cap, without
|
||||
// ever allocating the decoded bytes (the guard runs before decode).
|
||||
char[] huge = new char[140 * 1024 * 1024];
|
||||
java.util.Arrays.fill(huge, 'A');
|
||||
req.setPdfBase64(new String(huge));
|
||||
req.setLocatorChar("M");
|
||||
req.setText("M");
|
||||
ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(413);
|
||||
assertThat(resp.getBody()).isNotNull();
|
||||
assertThat(resp.getBody().getError()).isEqualTo("pdf too large");
|
||||
}
|
||||
|
||||
private static EncodeCharcodesRequest requestWithLocator(String locator) throws Exception {
|
||||
EncodeCharcodesRequest req = request("M");
|
||||
req.setLocatorChar(locator);
|
||||
return req;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a page whose resources declare {@code filler} fonts that do NOT render 'A' (Symbol /
|
||||
* ZapfDingbats have non-Latin encodings) plus, optionally, a trailing Helvetica that does. The
|
||||
* Standard14 probe upper bound is 256 so each scan is cheap.
|
||||
*/
|
||||
private static String manyFontsBase64(int filler, boolean trailingTarget) throws Exception {
|
||||
try (PDDocument doc = new PDDocument()) {
|
||||
PDPage page = new PDPage();
|
||||
doc.addPage(page);
|
||||
org.apache.pdfbox.pdmodel.PDResources resources =
|
||||
new org.apache.pdfbox.pdmodel.PDResources();
|
||||
for (int n = 0; n < filler; n++) {
|
||||
Standard14Fonts.FontName fn =
|
||||
(n % 2 == 0)
|
||||
? Standard14Fonts.FontName.SYMBOL
|
||||
: Standard14Fonts.FontName.ZAPF_DINGBATS;
|
||||
resources.put(
|
||||
org.apache.pdfbox.cos.COSName.getPDFName("Ff" + n), new PDType1Font(fn));
|
||||
}
|
||||
if (trailingTarget) {
|
||||
resources.put(
|
||||
org.apache.pdfbox.cos.COSName.getPDFName("Target"),
|
||||
new PDType1Font(Standard14Fonts.FontName.HELVETICA));
|
||||
}
|
||||
page.setResources(resources);
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
doc.save(bos);
|
||||
return Base64.getEncoder().encodeToString(bos.toByteArray());
|
||||
}
|
||||
}
|
||||
|
||||
private static EncodeCharcodesRequest manyFontsRequest(String base64) {
|
||||
EncodeCharcodesRequest req = new EncodeCharcodesRequest();
|
||||
req.setPdfBase64(base64);
|
||||
req.setPageIndex(0);
|
||||
req.setLocatorChar("A");
|
||||
req.setText("A");
|
||||
return req;
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetFontFoundAmongManyFonts() throws Exception {
|
||||
// 60 non-matching fonts then the Helvetica target, all within the 64-font cap.
|
||||
ResponseEntity<EncodeCharcodesResponse> resp =
|
||||
controller().encodeCharcodes(manyFontsRequest(manyFontsBase64(60, true)));
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(200);
|
||||
EncodeCharcodesResponse body = resp.getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getError()).isNull();
|
||||
assertThat(body.getCharcodes()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetBeyondFontCapReturnsGracefulNoFont() throws Exception {
|
||||
// 64 non-matching fonts then the target at position 65 - the scan cap stops
|
||||
// before reaching it, so we get a graceful no-font error rather than a full scan.
|
||||
ResponseEntity<EncodeCharcodesResponse> resp =
|
||||
controller().encodeCharcodes(manyFontsRequest(manyFontsBase64(64, true)));
|
||||
assertThat(resp.getStatusCode().value()).isEqualTo(200);
|
||||
EncodeCharcodesResponse body = resp.getBody();
|
||||
assertThat(body).isNotNull();
|
||||
assertThat(body.getError()).isNotNull();
|
||||
assertThat(body.getCharcodes()).isNull();
|
||||
}
|
||||
}
|
||||
-337
@@ -1,337 +0,0 @@
|
||||
package stirling.software.SPDF.controller.api;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.contentstream.PDFStreamEngine;
|
||||
import org.apache.pdfbox.contentstream.operator.state.Concatenate;
|
||||
import org.apache.pdfbox.contentstream.operator.state.Restore;
|
||||
import org.apache.pdfbox.contentstream.operator.state.Save;
|
||||
import org.apache.pdfbox.contentstream.operator.state.SetGraphicsStateParameters;
|
||||
import org.apache.pdfbox.contentstream.operator.state.SetMatrix;
|
||||
import org.apache.pdfbox.contentstream.operator.text.BeginText;
|
||||
import org.apache.pdfbox.contentstream.operator.text.EndText;
|
||||
import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize;
|
||||
import org.apache.pdfbox.contentstream.operator.text.SetTextHorizontalScaling;
|
||||
import org.apache.pdfbox.contentstream.operator.text.SetTextLeading;
|
||||
import org.apache.pdfbox.contentstream.operator.text.SetTextRenderingMode;
|
||||
import org.apache.pdfbox.contentstream.operator.text.SetTextRise;
|
||||
import org.apache.pdfbox.contentstream.operator.text.SetWordSpacing;
|
||||
import org.apache.pdfbox.contentstream.operator.text.ShowText;
|
||||
import org.apache.pdfbox.cos.COSBase;
|
||||
import org.apache.pdfbox.cos.COSDictionary;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.cos.COSStream;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDResources;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFont;
|
||||
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType3CharProc;
|
||||
import org.apache.pdfbox.pdmodel.font.PDType3Font;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Diagnostic test: enumerate every font referenced by Sample.pdf and dump its subtype, encoding,
|
||||
* ToUnicode, and embedded font program info. For Type3 fonts also dump CharProcs glyph names and
|
||||
* the content stream of one glyph (the 'M' if present).
|
||||
*
|
||||
* <p>Not a real regression test - run with --tests SamplePdfFontDumpTest -i to see the stdout
|
||||
* output.
|
||||
*/
|
||||
public class SamplePdfFontDumpTest {
|
||||
|
||||
private static final Path SAMPLE =
|
||||
Paths.get(System.getProperty("user.dir"))
|
||||
.getParent()
|
||||
.getParent()
|
||||
.resolve("frontend/editor/public/samples/Sample.pdf");
|
||||
|
||||
@Test
|
||||
public void dumpFonts() throws IOException {
|
||||
byte[] pdfBytes = Files.readAllBytes(SAMPLE);
|
||||
try (PDDocument doc = Loader.loadPDF(pdfBytes)) {
|
||||
int numPages = doc.getNumberOfPages();
|
||||
System.out.println("Sample.pdf has " + numPages + " pages.");
|
||||
Set<COSDictionary> seenFontDicts = new HashSet<>();
|
||||
for (int p = 0; p < numPages; p++) {
|
||||
PDPage page = doc.getPage(p);
|
||||
System.out.println("\n=== Page " + p + " ===");
|
||||
PDResources resources = page.getResources();
|
||||
if (resources == null) {
|
||||
System.out.println(" (no resources)");
|
||||
continue;
|
||||
}
|
||||
for (COSName fontName : resources.getFontNames()) {
|
||||
PDFont font;
|
||||
try {
|
||||
font = resources.getFont(fontName);
|
||||
} catch (IOException e) {
|
||||
System.out.println(
|
||||
" Font "
|
||||
+ fontName.getName()
|
||||
+ ": failed to load - "
|
||||
+ e.getMessage());
|
||||
continue;
|
||||
}
|
||||
if (font == null) continue;
|
||||
COSDictionary dict = font.getCOSObject();
|
||||
if (!seenFontDicts.add(dict)) {
|
||||
System.out.println(
|
||||
" Font " + fontName.getName() + " -> already seen above");
|
||||
continue;
|
||||
}
|
||||
dumpFont(fontName.getName(), font);
|
||||
}
|
||||
}
|
||||
// Scan: for every text-show operation, record per-font (charcode, unicode) pairs.
|
||||
System.out.println("\n=== All (font, charcode, unicode) seen on page ===");
|
||||
for (int p = 0; p < numPages; p++) {
|
||||
PDPage page = doc.getPage(p);
|
||||
AllCharsScanner scanner = new AllCharsScanner();
|
||||
scanner.processPage(page);
|
||||
System.out.println("\nPage " + p + ":");
|
||||
for (var entry : scanner.perFont.entrySet()) {
|
||||
PDFont font = entry.getKey();
|
||||
var seen = entry.getValue();
|
||||
System.out.println(" Font " + font.getName() + " " + font.getSubType() + ":");
|
||||
var sortedSeen = new java.util.TreeMap<Integer, String>(seen);
|
||||
for (var s : sortedSeen.entrySet()) {
|
||||
System.out.println(
|
||||
" charcode 0x"
|
||||
+ Integer.toHexString(s.getKey())
|
||||
+ " ("
|
||||
+ s.getKey()
|
||||
+ ") -> '"
|
||||
+ s.getValue()
|
||||
+ "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Confirm font.encode() works for Type3 fonts.
|
||||
System.out.println("\n=== Can we encode existing chars in F27/F28? ===");
|
||||
PDPage page0 = doc.getPage(0);
|
||||
PDResources r0 = page0.getResources();
|
||||
for (String fname : new String[] {"F27", "F28"}) {
|
||||
PDFont f = r0.getFont(COSName.getPDFName(fname));
|
||||
if (f == null) {
|
||||
System.out.println(" " + fname + ": NOT FOUND on page 0");
|
||||
continue;
|
||||
}
|
||||
System.out.println(" " + fname + ": " + f.getClass().getSimpleName());
|
||||
for (String ch : new String[] {"M", "0", "1", "+", "Z", "a"}) {
|
||||
try {
|
||||
byte[] enc = f.encode(ch);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : enc) sb.append(String.format("%02X ", b & 0xff));
|
||||
System.out.println(
|
||||
" encode('" + ch + "') -> [" + sb.toString().trim() + "]");
|
||||
} catch (Exception e) {
|
||||
System.out.println(
|
||||
" encode('"
|
||||
+ ch
|
||||
+ "') FAILED: "
|
||||
+ e.getClass().getSimpleName()
|
||||
+ " "
|
||||
+ e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dump page 0 content stream so we can see how "10M+" is composed.
|
||||
System.out.println("\n=== Page 0 RAW content stream (first 4kb) ===");
|
||||
try (InputStream is = doc.getPage(0).getContents()) {
|
||||
byte[] bytes = is.readAllBytes();
|
||||
System.out.println("Total content stream size: " + bytes.length + " bytes");
|
||||
String asStr = new String(bytes, StandardCharsets.ISO_8859_1);
|
||||
int idx = asStr.indexOf("F27");
|
||||
if (idx >= 0) {
|
||||
int start = Math.max(0, idx - 100);
|
||||
int end = Math.min(asStr.length(), idx + 2500);
|
||||
System.out.println("--- F27 context ---");
|
||||
System.out.println(asStr.substring(start, end));
|
||||
System.out.println("---");
|
||||
}
|
||||
int idx2 = asStr.indexOf("F28");
|
||||
if (idx2 >= 0) {
|
||||
int start = Math.max(0, idx2 - 200);
|
||||
int end = Math.min(asStr.length(), idx2 + 600);
|
||||
System.out.println("--- F28 context ---");
|
||||
System.out.println(asStr.substring(start, end));
|
||||
System.out.println("---");
|
||||
}
|
||||
}
|
||||
|
||||
// Dump a CharProc for each font's first non-zero glyph, with focus on any 'M' or "0".
|
||||
System.out.println("\n=== Sample CharProc dumps for Type3 fonts ===");
|
||||
Set<COSDictionary> printed = new HashSet<>();
|
||||
for (int p = 0; p < numPages; p++) {
|
||||
PDPage page = doc.getPage(p);
|
||||
PDResources resources = page.getResources();
|
||||
if (resources == null) continue;
|
||||
for (COSName fn : resources.getFontNames()) {
|
||||
PDFont font = resources.getFont(fn);
|
||||
if (!(font instanceof PDType3Font)) continue;
|
||||
if (!printed.add(font.getCOSObject())) continue;
|
||||
PDType3Font t3 = (PDType3Font) font;
|
||||
// Iterate charcodes 0..255 looking for any that map to 'M' or '0' or '+'.
|
||||
for (int cc = 0; cc < 256; cc++) {
|
||||
String u = null;
|
||||
try {
|
||||
u = t3.toUnicode(cc);
|
||||
} catch (Exception e) {
|
||||
/* */
|
||||
}
|
||||
if (u == null) continue;
|
||||
if (u.equals("M") || u.equals("0") || u.equals("+") || u.equals("1")) {
|
||||
System.out.println(
|
||||
"Page "
|
||||
+ p
|
||||
+ " font '"
|
||||
+ fn.getName()
|
||||
+ "' charcode "
|
||||
+ cc
|
||||
+ " maps to '"
|
||||
+ u
|
||||
+ "':");
|
||||
dumpType3Glyph(t3, cc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void dumpFont(String resourceName, PDFont font) {
|
||||
COSDictionary dict = font.getCOSObject();
|
||||
String subtype = dict.getNameAsString(COSName.SUBTYPE);
|
||||
String baseFont = dict.getNameAsString(COSName.BASE_FONT);
|
||||
boolean hasEncoding = dict.containsKey(COSName.ENCODING);
|
||||
boolean hasToUnicode = dict.containsKey(COSName.TO_UNICODE);
|
||||
PDFontDescriptor descriptor = font.getFontDescriptor();
|
||||
boolean hasEmbedded = false;
|
||||
String embeddedKind = "none";
|
||||
if (descriptor != null) {
|
||||
COSDictionary dDict = descriptor.getCOSObject();
|
||||
if (dDict.containsKey(COSName.FONT_FILE)) {
|
||||
hasEmbedded = true;
|
||||
embeddedKind = "FontFile (Type1)";
|
||||
} else if (dDict.containsKey(COSName.FONT_FILE2)) {
|
||||
hasEmbedded = true;
|
||||
embeddedKind = "FontFile2 (TrueType)";
|
||||
} else if (dDict.containsKey(COSName.FONT_FILE3)) {
|
||||
hasEmbedded = true;
|
||||
COSBase ff3 = dDict.getDictionaryObject(COSName.FONT_FILE3);
|
||||
if (ff3 instanceof COSStream) {
|
||||
String ff3Subtype = ((COSStream) ff3).getNameAsString(COSName.SUBTYPE);
|
||||
embeddedKind = "FontFile3 (" + ff3Subtype + ")";
|
||||
} else {
|
||||
embeddedKind = "FontFile3";
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println(
|
||||
" Font resource '"
|
||||
+ resourceName
|
||||
+ "': base='"
|
||||
+ baseFont
|
||||
+ "' subtype="
|
||||
+ subtype
|
||||
+ " hasEncoding="
|
||||
+ hasEncoding
|
||||
+ " hasToUnicode="
|
||||
+ hasToUnicode
|
||||
+ " embedded="
|
||||
+ hasEmbedded
|
||||
+ " ("
|
||||
+ embeddedKind
|
||||
+ ")");
|
||||
|
||||
if (font instanceof PDType3Font) {
|
||||
PDType3Font t3 = (PDType3Font) font;
|
||||
COSDictionary charProcs = t3.getCharProcs();
|
||||
int count = charProcs == null ? 0 : charProcs.size();
|
||||
System.out.println(" Type3 CharProcs count = " + count);
|
||||
if (charProcs != null) {
|
||||
TreeSet<String> names = new TreeSet<>();
|
||||
for (COSName k : charProcs.keySet()) names.add(k.getName());
|
||||
System.out.println(" glyph names: " + names);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void dumpType3Glyph(PDType3Font font, int charcode) throws IOException {
|
||||
String name = font.getEncoding() != null ? font.getEncoding().getName(charcode) : null;
|
||||
System.out.println(" Type3 charcode " + charcode + " -> glyph name '" + name + "'");
|
||||
PDType3CharProc proc = font.getCharProc(charcode);
|
||||
if (proc == null) {
|
||||
System.out.println(" (no CharProc for that charcode)");
|
||||
return;
|
||||
}
|
||||
COSStream stream = proc.getCOSObject();
|
||||
byte[] raw;
|
||||
try (InputStream is = stream.createInputStream()) {
|
||||
raw = is.readAllBytes();
|
||||
}
|
||||
System.out.println(" CharProc content stream (" + raw.length + " bytes):");
|
||||
System.out.println("---");
|
||||
System.out.println(new String(raw, StandardCharsets.ISO_8859_1));
|
||||
System.out.println("---");
|
||||
}
|
||||
|
||||
/** Records every (font, charcode -> unicode) tuple seen on a page. */
|
||||
static final class AllCharsScanner extends PDFStreamEngine {
|
||||
final java.util.LinkedHashMap<PDFont, java.util.Map<Integer, String>> perFont =
|
||||
new java.util.LinkedHashMap<>();
|
||||
|
||||
AllCharsScanner() {
|
||||
addOperator(new BeginText(this));
|
||||
addOperator(new EndText(this));
|
||||
addOperator(new SetFontAndSize(this));
|
||||
addOperator(new SetTextHorizontalScaling(this));
|
||||
addOperator(new SetTextLeading(this));
|
||||
addOperator(new SetTextRenderingMode(this));
|
||||
addOperator(new SetTextRise(this));
|
||||
addOperator(new SetWordSpacing(this));
|
||||
addOperator(new SetMatrix(this));
|
||||
addOperator(new Save(this));
|
||||
addOperator(new Restore(this));
|
||||
addOperator(new Concatenate(this));
|
||||
addOperator(new SetGraphicsStateParameters(this));
|
||||
addOperator(new ShowText(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void showText(byte[] string) throws IOException {
|
||||
PDFont font = getGraphicsState().getTextState().getFont();
|
||||
if (font == null) return;
|
||||
var seen = perFont.computeIfAbsent(font, k -> new java.util.LinkedHashMap<>());
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(string);
|
||||
while (in.available() > 0) {
|
||||
int code;
|
||||
try {
|
||||
code = font.readCode(in);
|
||||
} catch (IOException e) {
|
||||
break;
|
||||
}
|
||||
String u;
|
||||
try {
|
||||
u = font.toUnicode(code);
|
||||
} catch (RuntimeException e) {
|
||||
u = null;
|
||||
}
|
||||
seen.putIfAbsent(code, u);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
+13
-2
@@ -54,10 +54,21 @@ public class CustomAuditEventRepository implements AuditEventRepository {
|
||||
return;
|
||||
}
|
||||
String rid = MDC.get("requestId");
|
||||
String apiKeyLabel =
|
||||
MDC.get(
|
||||
stirling.software.proprietary.security.service
|
||||
.ApiKeyAuthenticationService.AUDIT_LABEL_MDC_KEY);
|
||||
|
||||
if (rid != null) {
|
||||
if (rid != null || apiKeyLabel != null) {
|
||||
clean = new java.util.HashMap<>(clean);
|
||||
clean.put("requestId", rid);
|
||||
if (rid != null) {
|
||||
clean.put("requestId", rid);
|
||||
}
|
||||
// Named key that made the request; surfaces as the doc source in the processor
|
||||
// feed.
|
||||
if (apiKeyLabel != null) {
|
||||
clean.put("__apiKeyLabel", apiKeyLabel);
|
||||
}
|
||||
}
|
||||
|
||||
String source = MDC.get("auditSource");
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package stirling.software.proprietary.controller.api;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.annotations.api.ProprietaryUiDataApi;
|
||||
import stirling.software.proprietary.model.api.apikey.CreateApiKeyRequest;
|
||||
import stirling.software.proprietary.model.api.apikey.CreatedApiKeyDto;
|
||||
import stirling.software.proprietary.model.api.apikey.PortalApiKeysResponse;
|
||||
import stirling.software.proprietary.security.service.ApiKeyManagementService;
|
||||
|
||||
/**
|
||||
* Real backing for the portal Infrastructure → API Keys tab: list/create/revoke named, personal API
|
||||
* keys. Replaces the former portal-only mock endpoint. Not gated behind an Enterprise license - API
|
||||
* keys are a core auth feature available on every self-hosted instance.
|
||||
*/
|
||||
@ProprietaryUiDataApi
|
||||
@RequiredArgsConstructor
|
||||
public class PortalApiKeysController {
|
||||
|
||||
private final ApiKeyManagementService apiKeyManagementService;
|
||||
|
||||
// tier accepted for endpoint symmetry with the other infra tabs; ignored here.
|
||||
@GetMapping("/infrastructure/api-keys")
|
||||
@Operation(summary = "List API keys", description = "The caller's personal API keys.")
|
||||
public ResponseEntity<PortalApiKeysResponse> list(
|
||||
@RequestParam(value = "tier", required = false) String tier) {
|
||||
return ResponseEntity.ok(apiKeyManagementService.listVisibleKeys());
|
||||
}
|
||||
|
||||
@PostMapping("/infrastructure/api-keys")
|
||||
@Operation(
|
||||
summary = "Create an API key",
|
||||
description = "Mints a personal key and returns its one-time secret.")
|
||||
public ResponseEntity<CreatedApiKeyDto> create(@RequestBody CreateApiKeyRequest request) {
|
||||
return ResponseEntity.ok(apiKeyManagementService.createKey(request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/infrastructure/api-keys/{id}")
|
||||
@Operation(summary = "Revoke an API key", description = "Disables a key the caller owns.")
|
||||
public ResponseEntity<Void> revoke(@PathVariable("id") Long id) {
|
||||
apiKeyManagementService.revokeKey(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+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);
|
||||
}
|
||||
+2
-2
@@ -24,8 +24,8 @@ import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
/**
|
||||
* API-key auth for the MCP endpoint: validates a Stirling per-user API key and binds the request to
|
||||
* that user with the MCP scopes.
|
||||
* API-key auth for the MCP endpoint: validates a Stirling API key and binds the request to that
|
||||
* user with the MCP scopes.
|
||||
*/
|
||||
@Slf4j
|
||||
public class McpApiKeyAuthFilter extends OncePerRequestFilter {
|
||||
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package stirling.software.proprietary.model.api.apikey;
|
||||
|
||||
/** Create-key request body from the portal: just a display name for the new personal key. */
|
||||
public record CreateApiKeyRequest(String name) {}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package stirling.software.proprietary.model.api.apikey;
|
||||
|
||||
import lombok.Builder;
|
||||
|
||||
/** Returned once when a key is created: the row plus the plaintext secret, never persisted. */
|
||||
@Builder
|
||||
public record CreatedApiKeyDto(PortalApiKeyDto key, String secret) {}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package stirling.software.proprietary.model.api.apikey;
|
||||
|
||||
import lombok.Builder;
|
||||
|
||||
/**
|
||||
* One API key as shown in the portal Infrastructure → API Keys tab. Never carries the secret; that
|
||||
* is returned once from {@link CreatedApiKeyDto} at creation time.
|
||||
*/
|
||||
@Builder
|
||||
public record PortalApiKeyDto(
|
||||
String id,
|
||||
String name,
|
||||
String prefix,
|
||||
String created,
|
||||
String lastUsed,
|
||||
/** "active" | "revoked". */
|
||||
String status,
|
||||
long usageToday,
|
||||
long usageMonth,
|
||||
/** Lifetime request count for the key. */
|
||||
long usageTotal) {}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package stirling.software.proprietary.model.api.apikey;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Builder;
|
||||
|
||||
/** Payload for the API Keys tab: the personal keys the caller owns. */
|
||||
@Builder
|
||||
public record PortalApiKeysResponse(List<PortalApiKeyDto> keys) {}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -57,6 +57,7 @@ import stirling.software.proprietary.security.oauth2.TauriAuthorizationRequestRe
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationFailureHandler;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationSuccessHandler;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2ResponseAuthenticationConverter;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.CustomOAuth2UserService;
|
||||
import stirling.software.proprietary.security.service.CustomUserDetailsService;
|
||||
import stirling.software.proprietary.security.service.JwtServiceInterface;
|
||||
@@ -484,12 +485,14 @@ public class SecurityConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtAuthenticationFilter jwtAuthenticationFilter() {
|
||||
public JwtAuthenticationFilter jwtAuthenticationFilter(
|
||||
ApiKeyAuthenticationService apiKeyAuthenticationService) {
|
||||
return new JwtAuthenticationFilter(
|
||||
jwtService,
|
||||
userService,
|
||||
userDetailsService,
|
||||
jwtAuthenticationEntryPoint,
|
||||
securityProperties);
|
||||
securityProperties,
|
||||
apiKeyAuthenticationService);
|
||||
}
|
||||
}
|
||||
|
||||
+20
-4
@@ -11,6 +11,7 @@ import java.sql.SQLException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
@@ -33,8 +34,9 @@ import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
|
||||
import stirling.software.proprietary.security.model.AuthenticationType;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.model.exception.AuthenticationFailureException;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService.ApiKeyAuthentication;
|
||||
import stirling.software.proprietary.security.service.CustomUserDetailsService;
|
||||
import stirling.software.proprietary.security.service.JwtServiceInterface;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
@@ -48,11 +50,15 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final CustomUserDetailsService userDetailsService;
|
||||
private final AuthenticationEntryPoint authenticationEntryPoint;
|
||||
private final ApplicationProperties.Security securityProperties;
|
||||
private final ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
// Start clean so a pooled thread can't inherit a prior request's key label. This filter
|
||||
// runs before UserAuthenticationFilter, so in JWT mode it owns the API-key label lifecycle.
|
||||
MDC.remove(ApiKeyAuthenticationService.AUDIT_LABEL_MDC_KEY);
|
||||
if (!jwtService.isJwtEnabled()) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
@@ -131,9 +137,14 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
if (apiKey != null && !apiKey.isBlank()) {
|
||||
try {
|
||||
Optional<User> user = userService.getUserByApiKey(apiKey);
|
||||
// Resolve through the shared service so the multi-key table (then the legacy
|
||||
// per-user key) is consulted and per-key usage is recorded; the key runs as its
|
||||
// owner. It also yields a per-key label for the processor's document
|
||||
// attribution.
|
||||
Optional<ApiKeyAuthentication> resolved =
|
||||
apiKeyAuthenticationService.authenticate(apiKey);
|
||||
|
||||
if (user.isEmpty()) {
|
||||
if (resolved.isEmpty()) {
|
||||
handleAuthenticationFailure(
|
||||
request,
|
||||
response,
|
||||
@@ -143,8 +154,13 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
authentication =
|
||||
new ApiKeyAuthenticationToken(
|
||||
user.get(), apiKey, user.get().getAuthorities());
|
||||
resolved.get().user(), apiKey, resolved.get().authorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
if (resolved.get().auditLabel() != null) {
|
||||
MDC.put(
|
||||
ApiKeyAuthenticationService.AUDIT_LABEL_MDC_KEY,
|
||||
resolved.get().auditLabel());
|
||||
}
|
||||
return true;
|
||||
} catch (AuthenticationException e) {
|
||||
handleAuthenticationFailure(
|
||||
|
||||
+27
-5
@@ -6,6 +6,7 @@ import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
@@ -33,6 +34,8 @@ import stirling.software.common.util.RequestUriUtils;
|
||||
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService.ApiKeyAuthentication;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
|
||||
@@ -41,18 +44,24 @@ import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
@Profile("!saas")
|
||||
public class UserAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
/** MDC key carrying the resolved key's label into audit events for the processor feed. */
|
||||
public static final String API_KEY_LABEL_MDC = ApiKeyAuthenticationService.AUDIT_LABEL_MDC_KEY;
|
||||
|
||||
private final ApplicationProperties.Security securityProp;
|
||||
private final UserService userService;
|
||||
private final ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
private final SessionPersistentRegistry sessionPersistentRegistry;
|
||||
private final boolean loginEnabledValue;
|
||||
|
||||
public UserAuthenticationFilter(
|
||||
@Lazy ApplicationProperties.Security securityProp,
|
||||
@Lazy UserService userService,
|
||||
ApiKeyAuthenticationService apiKeyAuthenticationService,
|
||||
SessionPersistentRegistry sessionPersistentRegistry,
|
||||
@Qualifier("loginEnabled") boolean loginEnabledValue) {
|
||||
this.securityProp = securityProp;
|
||||
this.userService = userService;
|
||||
this.apiKeyAuthenticationService = apiKeyAuthenticationService;
|
||||
this.sessionPersistentRegistry = sessionPersistentRegistry;
|
||||
this.loginEnabledValue = loginEnabledValue;
|
||||
}
|
||||
@@ -62,6 +71,14 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// Start each request clean so a pooled thread can't inherit a prior request's key label -
|
||||
// but keep a label an upstream filter (JwtAuthenticationFilter) already set for a request
|
||||
// it API-key-authenticated, otherwise per-key attribution is lost on the JWT path.
|
||||
if (!(SecurityContextHolder.getContext().getAuthentication()
|
||||
instanceof ApiKeyAuthenticationToken)) {
|
||||
MDC.remove(API_KEY_LABEL_MDC);
|
||||
}
|
||||
|
||||
if (!loginEnabledValue) {
|
||||
// If login is not enabled, just pass all requests without authentication
|
||||
filterChain.doFilter(request, response);
|
||||
@@ -89,18 +106,23 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
|
||||
String apiKey = request.getHeader("X-API-KEY");
|
||||
if (apiKey != null && !apiKey.trim().isEmpty()) {
|
||||
try {
|
||||
// Use API key to authenticate. This requires you to have an authentication
|
||||
// provider for API keys.
|
||||
Optional<User> user = userService.getUserByApiKey(apiKey);
|
||||
if (user.isEmpty()) {
|
||||
// Resolves the multi-key table then the legacy key, records usage, and yields a
|
||||
// per-key label for the processor's document-source attribution.
|
||||
Optional<ApiKeyAuthentication> resolved =
|
||||
apiKeyAuthenticationService.authenticate(apiKey);
|
||||
if (resolved.isEmpty()) {
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
response.getWriter().write("Invalid API Key.");
|
||||
return;
|
||||
}
|
||||
User user = resolved.get().user();
|
||||
authentication =
|
||||
new ApiKeyAuthenticationToken(
|
||||
user.get(), apiKey, user.get().getAuthorities());
|
||||
user, apiKey, resolved.get().authorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
if (resolved.get().auditLabel() != null) {
|
||||
MDC.put(API_KEY_LABEL_MDC, resolved.get().auditLabel());
|
||||
}
|
||||
} catch (AuthenticationException e) {
|
||||
// If API key authentication fails, deny the request
|
||||
response.setStatus(HttpStatus.UNAUTHORIZED.value());
|
||||
|
||||
+15
-14
@@ -11,7 +11,6 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@@ -58,22 +57,24 @@ public class UserBasedRateLimitingFilter extends OncePerRequestFilter {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
// Bucket by the resolved user (the auth filter runs first and populates the context, even
|
||||
// for X-API-KEY requests), so all of a user's API keys share ONE per-user quota - minting
|
||||
// extra keys can't multiply the daily limit. Fall back to the raw key / IP only when the
|
||||
// request is unauthenticated.
|
||||
String identifier = null;
|
||||
// Check for API key in the request headers
|
||||
String apiKey = request.getHeader("X-API-KEY");
|
||||
if (apiKey != null && !apiKey.trim().isEmpty()) {
|
||||
identifier = // Prefix to distinguish between API keys and usernames
|
||||
"API_KEY_" + apiKey;
|
||||
} else {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null && authentication.isAuthenticated()) {
|
||||
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
|
||||
identifier = userDetails.getUsername();
|
||||
}
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null
|
||||
&& authentication.isAuthenticated()
|
||||
&& !"anonymousUser".equals(authentication.getName())) {
|
||||
identifier = authentication.getName();
|
||||
}
|
||||
// If neither API key nor an authenticated user is present, use IP address
|
||||
if (identifier == null) {
|
||||
identifier = request.getRemoteAddr();
|
||||
String apiKey = request.getHeader("X-API-KEY");
|
||||
if (apiKey != null && !apiKey.trim().isEmpty()) {
|
||||
identifier = "API_KEY_" + apiKey;
|
||||
} else {
|
||||
identifier = request.getRemoteAddr();
|
||||
}
|
||||
}
|
||||
Role userRole =
|
||||
getRoleFromAuthentication(SecurityContextHolder.getContext().getAuthentication());
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package stirling.software.proprietary.security.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.Instant;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* A named, personal API key belonging to a user. The raw secret is shown once at creation and never
|
||||
* stored; only its SHA-256 hash is persisted, so a leaked database row cannot be replayed. Distinct
|
||||
* from the legacy single {@code users.apiKey} column, which stays a per-user key for backward
|
||||
* compatibility and is lazily represented here.
|
||||
*/
|
||||
@Entity
|
||||
@Table(
|
||||
name = "api_keys",
|
||||
indexes = {
|
||||
@Index(name = "idx_api_key_hash", columnList = "key_hash", unique = true),
|
||||
@Index(name = "idx_api_key_owner", columnList = "owner_user_id")
|
||||
})
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ApiKey implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name", nullable = false, length = 100)
|
||||
private String name;
|
||||
|
||||
/** SHA-256 hex of the raw key; the raw value is never persisted. */
|
||||
@Column(name = "key_hash", nullable = false, unique = true, length = 64)
|
||||
private String keyHash;
|
||||
|
||||
/** Non-secret leading fragment of the raw key, shown in listings (e.g. {@code sk_a1b2c3d4}). */
|
||||
@Column(name = "prefix", nullable = false, length = 32)
|
||||
private String prefix;
|
||||
|
||||
/** The user who created and owns the key; the key authenticates as this user. */
|
||||
@Column(name = "owner_user_id", nullable = false)
|
||||
private Long ownerUserId;
|
||||
|
||||
@Column(name = "enabled", nullable = false)
|
||||
private boolean enabled;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "last_used_at")
|
||||
private Instant lastUsedAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
|
||||
/** Active = enabled and not revoked; only active keys authenticate. */
|
||||
public boolean isActive() {
|
||||
return enabled && revokedAt == null;
|
||||
}
|
||||
}
|
||||
+1
@@ -5,6 +5,7 @@ import java.util.Collection;
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
/** Authentication produced from an {@code X-API-KEY} header; runs as the key's owner. */
|
||||
public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
|
||||
|
||||
private final Object principal;
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package stirling.software.proprietary.security.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.IdClass;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* One UTC day's request tally for an API key. Rolling "today"/"this month" usage is summed from
|
||||
* these rows, keeping the table at one row per key per active day rather than one per request.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "api_key_daily_usage")
|
||||
@IdClass(ApiKeyDailyUsageId.class)
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class ApiKeyDailyUsage implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(name = "api_key_id")
|
||||
private Long apiKeyId;
|
||||
|
||||
@Id
|
||||
@Column(name = "epoch_day")
|
||||
private long epochDay;
|
||||
|
||||
@Column(name = "count")
|
||||
private long count;
|
||||
|
||||
public ApiKeyDailyUsage(Long apiKeyId, long epochDay, long count) {
|
||||
this.apiKeyId = apiKeyId;
|
||||
this.epochDay = epochDay;
|
||||
this.count = count;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package stirling.software.proprietary.security.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Composite key for {@link ApiKeyDailyUsage}: one row per key per UTC day. */
|
||||
public class ApiKeyDailyUsageId implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long apiKeyId;
|
||||
private long epochDay;
|
||||
|
||||
public ApiKeyDailyUsageId() {}
|
||||
|
||||
public ApiKeyDailyUsageId(Long apiKeyId, long epochDay) {
|
||||
this.apiKeyId = apiKeyId;
|
||||
this.epochDay = epochDay;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof ApiKeyDailyUsageId other)) {
|
||||
return false;
|
||||
}
|
||||
return epochDay == other.epochDay && Objects.equals(apiKeyId, other.apiKeyId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(apiKeyId, epochDay);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package stirling.software.proprietary.security.repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.security.model.ApiKeyDailyUsage;
|
||||
import stirling.software.proprietary.security.model.ApiKeyDailyUsageId;
|
||||
|
||||
@Repository
|
||||
public interface ApiKeyDailyUsageRepository
|
||||
extends JpaRepository<ApiKeyDailyUsage, ApiKeyDailyUsageId> {
|
||||
|
||||
/** Atomically bump today's tally; returns 0 when no row exists yet (caller then inserts). */
|
||||
@Modifying
|
||||
@Query(
|
||||
"UPDATE ApiKeyDailyUsage u SET u.count = u.count + 1 "
|
||||
+ "WHERE u.apiKeyId = :apiKeyId AND u.epochDay = :epochDay")
|
||||
int incrementIfPresent(@Param("apiKeyId") Long apiKeyId, @Param("epochDay") long epochDay);
|
||||
|
||||
@Query(
|
||||
"SELECT COALESCE(SUM(u.count), 0) FROM ApiKeyDailyUsage u "
|
||||
+ "WHERE u.apiKeyId = :apiKeyId AND u.epochDay >= :fromDayInclusive")
|
||||
long sumSince(
|
||||
@Param("apiKeyId") Long apiKeyId, @Param("fromDayInclusive") long fromDayInclusive);
|
||||
|
||||
@Query(
|
||||
"SELECT u.count FROM ApiKeyDailyUsage u "
|
||||
+ "WHERE u.apiKeyId = :apiKeyId AND u.epochDay = :epochDay")
|
||||
Long countForDay(@Param("apiKeyId") Long apiKeyId, @Param("epochDay") long epochDay);
|
||||
|
||||
/** Batched today-count for many keys in one query (avoids N+1 when listing keys). */
|
||||
@Query(
|
||||
"SELECT u.apiKeyId AS apiKeyId, u.count AS total FROM ApiKeyDailyUsage u "
|
||||
+ "WHERE u.apiKeyId IN :ids AND u.epochDay = :epochDay")
|
||||
List<ApiKeyUsageSum> countForDayByIds(
|
||||
@Param("ids") Collection<Long> ids, @Param("epochDay") long epochDay);
|
||||
|
||||
/** Batched trailing-window sum for many keys in one query. */
|
||||
@Query(
|
||||
"SELECT u.apiKeyId AS apiKeyId, SUM(u.count) AS total FROM ApiKeyDailyUsage u "
|
||||
+ "WHERE u.apiKeyId IN :ids AND u.epochDay >= :fromDayInclusive "
|
||||
+ "GROUP BY u.apiKeyId")
|
||||
List<ApiKeyUsageSum> sumSinceByIds(
|
||||
@Param("ids") Collection<Long> ids, @Param("fromDayInclusive") long fromDayInclusive);
|
||||
|
||||
void deleteByApiKeyId(Long apiKeyId);
|
||||
|
||||
List<ApiKeyDailyUsage> findByApiKeyId(Long apiKeyId);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package stirling.software.proprietary.security.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.security.model.ApiKey;
|
||||
|
||||
@Repository
|
||||
public interface ApiKeyRepository extends JpaRepository<ApiKey, Long> {
|
||||
|
||||
Optional<ApiKey> findByKeyHash(String keyHash);
|
||||
|
||||
boolean existsByKeyHash(String keyHash);
|
||||
|
||||
List<ApiKey> findByOwnerUserIdOrderByCreatedAtDesc(Long ownerUserId);
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package stirling.software.proprietary.security.repository;
|
||||
|
||||
/** Projection: a key id and a usage total, for batching per-key usage into one query. */
|
||||
public interface ApiKeyUsageSum {
|
||||
Long getApiKeyId();
|
||||
|
||||
Long getTotal();
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.security.database.repository.UserRepository;
|
||||
import stirling.software.proprietary.security.model.ApiKey;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyRepository;
|
||||
|
||||
/**
|
||||
* Resolves an incoming {@code X-API-KEY} to its owning user and records per-key usage. Depends only
|
||||
* on repositories (never {@code UserService}) so {@code UserService} can delegate here without a
|
||||
* bean cycle.
|
||||
*
|
||||
* <p>Resolution order: the multi-key {@code api_keys} table first (by hash), then the legacy
|
||||
* per-user {@code users.apiKey} column. Legacy keys therefore keep working unchanged. Every key is
|
||||
* personal and authenticates as its owner with the owner's authorities.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiKeyAuthenticationService {
|
||||
|
||||
/**
|
||||
* MDC key that carries the resolved key's label into audit events so the processor's Documents
|
||||
* feed can attribute a document to the specific key. Set by the auth filters (both flavors),
|
||||
* read by {@code CustomAuditEventRepository}.
|
||||
*/
|
||||
public static final String AUDIT_LABEL_MDC_KEY = "apiKeyLabel";
|
||||
|
||||
private final ApiKeyRepository apiKeyRepository;
|
||||
private final ApiKeyUsageRecorder usageRecorder;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
/** The user a raw key authenticates as, or empty if it matches no active key. */
|
||||
public Optional<User> resolveUser(String rawKey) {
|
||||
return authenticate(rawKey).map(ApiKeyAuthentication::user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a raw key, recording usage as a side effect. Returns the owning user, a display label
|
||||
* for the resolved key ({@code null} for the legacy per-user key), and the owner's authorities.
|
||||
*/
|
||||
public Optional<ApiKeyAuthentication> authenticate(String rawKey) {
|
||||
if (rawKey == null || rawKey.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
ApiKey key = apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(rawKey)).orElse(null);
|
||||
if (key != null) {
|
||||
if (!key.isActive()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
User owner = userRepository.findById(key.getOwnerUserId()).orElse(null);
|
||||
if (owner == null || !owner.isEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
usageRecorder.record(key.getId());
|
||||
return Optional.of(
|
||||
new ApiKeyAuthentication(owner, auditLabel(key), owner.getAuthorities()));
|
||||
}
|
||||
|
||||
// Legacy single per-user key: keep working, always a personal key for its user.
|
||||
return userRepository
|
||||
.findByApiKey(rawKey)
|
||||
.filter(User::isEnabled)
|
||||
.map(user -> new ApiKeyAuthentication(user, null, user.getAuthorities()));
|
||||
}
|
||||
|
||||
/** "Production ingest (sk_a1b2c3d4)" - shown against API-sourced docs in the processor feed. */
|
||||
private static String auditLabel(ApiKey key) {
|
||||
return key.getName() + " (" + key.getPrefix() + ")";
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the {@code api_keys} row that mirrors a given raw key, if any. Called when the legacy
|
||||
* per-user key is rotated so the migrated shadow row can't keep authenticating the old secret.
|
||||
*/
|
||||
@Transactional
|
||||
public void revokeMigratedKey(String rawKey) {
|
||||
if (rawKey == null || rawKey.isBlank()) {
|
||||
return;
|
||||
}
|
||||
apiKeyRepository
|
||||
.findByKeyHash(ApiKeyHasher.hash(rawKey))
|
||||
.filter(ApiKey::isActive)
|
||||
.ifPresent(
|
||||
k -> {
|
||||
k.setEnabled(false);
|
||||
k.setRevokedAt(Instant.now());
|
||||
apiKeyRepository.save(k);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolved key: the user, an optional processor-feed label, and the authorities to run as.
|
||||
*/
|
||||
public record ApiKeyAuthentication(
|
||||
User user, String auditLabel, Collection<? extends GrantedAuthority> authorities) {}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/** Generates opaque API-key secrets and hashes them for storage/lookup. */
|
||||
public final class ApiKeyHasher {
|
||||
|
||||
/** Human-recognisable prefix so a leaked string is identifiable as a Stirling API key. */
|
||||
public static final String KEY_PREFIX = "sk_";
|
||||
|
||||
/** Chars of the raw key kept for non-secret display (includes the {@code sk_} prefix). */
|
||||
private static final int DISPLAY_PREFIX_LENGTH = 11;
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private ApiKeyHasher() {}
|
||||
|
||||
/** A fresh opaque secret: {@code sk_} followed by 40 hex chars of cryptographic randomness. */
|
||||
public static String generateRawKey() {
|
||||
byte[] bytes = new byte[20];
|
||||
RANDOM.nextBytes(bytes);
|
||||
return KEY_PREFIX + HexFormat.of().formatHex(bytes);
|
||||
}
|
||||
|
||||
/** SHA-256 hex of a raw key; the value stored and looked up, never the raw key. */
|
||||
public static String hash(String rawKey) {
|
||||
try {
|
||||
byte[] digest =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(rawKey.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Leading, non-secret fragment shown in listings (e.g. {@code sk_a1b2c3d4}). */
|
||||
public static String displayPrefix(String rawKey) {
|
||||
if (rawKey == null) {
|
||||
return "";
|
||||
}
|
||||
return rawKey.length() <= DISPLAY_PREFIX_LENGTH
|
||||
? rawKey
|
||||
: rawKey.substring(0, DISPLAY_PREFIX_LENGTH);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.security.model.ApiKey;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyRepository;
|
||||
|
||||
/**
|
||||
* Inserts the shadow {@code api_keys} row that mirrors a user's legacy {@code users.apiKey} in its
|
||||
* OWN ({@code REQUIRES_NEW}) transaction. Kept a separate bean so the write is isolated from the
|
||||
* caller's listing transaction: when two concurrent first-loads race to insert the same hash, the
|
||||
* loser's unique-key clash rolls back only this insert instead of poisoning the caller's
|
||||
* transaction (on Postgres a failed statement aborts the whole transaction). The {@code
|
||||
* DataIntegrityViolationException} is left to propagate so the caller can treat it as "already
|
||||
* migrated".
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
class ApiKeyLegacyMigrator {
|
||||
|
||||
private final ApiKeyRepository apiKeyRepository;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void insertMigratedKey(ApiKey key) {
|
||||
apiKeyRepository.saveAndFlush(key);
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.api.apikey.CreateApiKeyRequest;
|
||||
import stirling.software.proprietary.model.api.apikey.CreatedApiKeyDto;
|
||||
import stirling.software.proprietary.model.api.apikey.PortalApiKeyDto;
|
||||
import stirling.software.proprietary.model.api.apikey.PortalApiKeysResponse;
|
||||
import stirling.software.proprietary.security.database.repository.UserRepository;
|
||||
import stirling.software.proprietary.security.model.ApiKey;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyDailyUsageRepository;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyRepository;
|
||||
|
||||
/**
|
||||
* Portal-facing CRUD for named, personal API keys: lists, creates, and revokes the caller's own
|
||||
* keys. Every key belongs to exactly one user and authenticates as that user; there is no sharing.
|
||||
*
|
||||
* <p>Every pre-existing single {@code users.apiKey} is lazily represented as a key owned by that
|
||||
* user, so historic keys list uniformly.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiKeyManagementService {
|
||||
|
||||
private static final DateTimeFormatter CREATED_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
|
||||
private static final DateTimeFormatter LAST_USED_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneOffset.UTC);
|
||||
private static final int MONTH_WINDOW_DAYS = 30;
|
||||
|
||||
/** Bounds a key name so it can't bloat storage or the audit/processor feed. */
|
||||
private static final int MAX_NAME_LENGTH = 100;
|
||||
|
||||
/** Caps active keys per user so key creation can't be used to multiply rate-limit budget. */
|
||||
private static final int MAX_ACTIVE_KEYS_PER_USER = 50;
|
||||
|
||||
private final ApiKeyRepository apiKeyRepository;
|
||||
private final ApiKeyDailyUsageRepository usageRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final UserService userService;
|
||||
private final ApiKeyLegacyMigrator legacyMigrator;
|
||||
|
||||
/** All keys the caller owns. */
|
||||
@Transactional
|
||||
public PortalApiKeysResponse listVisibleKeys() {
|
||||
User caller = requireCaller();
|
||||
migrateLegacyKey(caller);
|
||||
|
||||
List<ApiKey> visible =
|
||||
apiKeyRepository.findByOwnerUserIdOrderByCreatedAtDesc(caller.getId());
|
||||
|
||||
// Batch usage for all keys into three queries rather than two-per-key (avoids N+1).
|
||||
long today = Instant.now().atZone(ZoneOffset.UTC).toLocalDate().toEpochDay();
|
||||
List<Long> ids = visible.stream().map(ApiKey::getId).toList();
|
||||
Map<Long, Long> todayById = new HashMap<>();
|
||||
Map<Long, Long> monthById = new HashMap<>();
|
||||
Map<Long, Long> totalById = new HashMap<>();
|
||||
if (!ids.isEmpty()) {
|
||||
usageRepository
|
||||
.countForDayByIds(ids, today)
|
||||
.forEach(r -> todayById.put(r.getApiKeyId(), r.getTotal()));
|
||||
usageRepository
|
||||
.sumSinceByIds(ids, today - (MONTH_WINDOW_DAYS - 1))
|
||||
.forEach(r -> monthById.put(r.getApiKeyId(), r.getTotal()));
|
||||
usageRepository
|
||||
.sumSinceByIds(ids, Long.MIN_VALUE)
|
||||
.forEach(r -> totalById.put(r.getApiKeyId(), r.getTotal()));
|
||||
}
|
||||
|
||||
List<PortalApiKeyDto> keys =
|
||||
visible.stream()
|
||||
.map(
|
||||
k ->
|
||||
toDto(
|
||||
k,
|
||||
zeroIfNull(todayById.get(k.getId())),
|
||||
zeroIfNull(monthById.get(k.getId())),
|
||||
zeroIfNull(totalById.get(k.getId()))))
|
||||
.toList();
|
||||
return PortalApiKeysResponse.builder().keys(keys).build();
|
||||
}
|
||||
|
||||
private static long zeroIfNull(Long value) {
|
||||
return value == null ? 0L : value;
|
||||
}
|
||||
|
||||
/** Create a personal key and return its one-time secret. */
|
||||
@Transactional
|
||||
public CreatedApiKeyDto createKey(CreateApiKeyRequest request) {
|
||||
User caller = requireCaller();
|
||||
String name = request == null ? null : request.name();
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Key name is required");
|
||||
}
|
||||
if (name.trim().length() > MAX_NAME_LENGTH) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Key name must be " + MAX_NAME_LENGTH + " characters or fewer");
|
||||
}
|
||||
long activeOwned =
|
||||
apiKeyRepository.findByOwnerUserIdOrderByCreatedAtDesc(caller.getId()).stream()
|
||||
.filter(ApiKey::isActive)
|
||||
.count();
|
||||
if (activeOwned >= MAX_ACTIVE_KEYS_PER_USER) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
"You have reached the maximum of "
|
||||
+ MAX_ACTIVE_KEYS_PER_USER
|
||||
+ " active API keys; revoke one before creating another");
|
||||
}
|
||||
|
||||
String rawKey = ApiKeyHasher.generateRawKey();
|
||||
ApiKey saved =
|
||||
apiKeyRepository.save(
|
||||
ApiKey.builder()
|
||||
.name(name.trim())
|
||||
.keyHash(ApiKeyHasher.hash(rawKey))
|
||||
.prefix(ApiKeyHasher.displayPrefix(rawKey))
|
||||
.ownerUserId(caller.getId())
|
||||
.enabled(true)
|
||||
.createdAt(Instant.now())
|
||||
.build());
|
||||
|
||||
return CreatedApiKeyDto.builder().key(toDto(saved, 0L, 0L, 0L)).secret(rawKey).build();
|
||||
}
|
||||
|
||||
/** Soft-revoke a key the caller owns; also clears the legacy column if it is that key. */
|
||||
@Transactional
|
||||
public void revokeKey(Long id) {
|
||||
User caller = requireCaller();
|
||||
ApiKey key =
|
||||
apiKeyRepository
|
||||
.findById(id)
|
||||
.orElseThrow(
|
||||
() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No key"));
|
||||
if (!key.getOwnerUserId().equals(caller.getId())) {
|
||||
// Not-found rather than forbidden so a caller can't probe other users' key ids.
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No key");
|
||||
}
|
||||
key.setEnabled(false);
|
||||
key.setRevokedAt(Instant.now());
|
||||
apiKeyRepository.save(key);
|
||||
clearLegacyColumnIfMatches(key);
|
||||
}
|
||||
|
||||
/** Represent a user's pre-existing single key as a row so it lists uniformly. */
|
||||
private void migrateLegacyKey(User user) {
|
||||
String legacy = user.getApiKey();
|
||||
if (legacy == null || legacy.isBlank()) {
|
||||
return;
|
||||
}
|
||||
String hash = ApiKeyHasher.hash(legacy);
|
||||
if (apiKeyRepository.existsByKeyHash(hash)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Insert in its own transaction so a concurrent-insert clash can't poison this
|
||||
// listing transaction (see ApiKeyLegacyMigrator).
|
||||
legacyMigrator.insertMigratedKey(
|
||||
ApiKey.builder()
|
||||
.name("Default key")
|
||||
.keyHash(hash)
|
||||
.prefix(ApiKeyHasher.displayPrefix(legacy))
|
||||
.ownerUserId(user.getId())
|
||||
.enabled(true)
|
||||
.createdAt(Instant.now())
|
||||
.build());
|
||||
} catch (DataIntegrityViolationException alreadyMigrated) {
|
||||
// A concurrent first-load won the race and inserted the same hash; that's fine.
|
||||
log.debug("Legacy key already migrated concurrently for user {}", user.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If a revoked key is the owner's legacy {@code users.apiKey}, null it so it stops resolving.
|
||||
*/
|
||||
private void clearLegacyColumnIfMatches(ApiKey key) {
|
||||
userRepository
|
||||
.findById(key.getOwnerUserId())
|
||||
.ifPresent(
|
||||
owner -> {
|
||||
String legacy = owner.getApiKey();
|
||||
if (legacy != null
|
||||
&& ApiKeyHasher.hash(legacy).equals(key.getKeyHash())) {
|
||||
owner.setApiKey(null);
|
||||
userRepository.save(owner);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private PortalApiKeyDto toDto(ApiKey key, long usageToday, long usageMonth, long usageTotal) {
|
||||
return PortalApiKeyDto.builder()
|
||||
.id(String.valueOf(key.getId()))
|
||||
.name(key.getName())
|
||||
.prefix(key.getPrefix())
|
||||
.created(
|
||||
key.getCreatedAt() == null ? "" : CREATED_FORMAT.format(key.getCreatedAt()))
|
||||
.lastUsed(
|
||||
key.getLastUsedAt() == null
|
||||
? "Never"
|
||||
: LAST_USED_FORMAT.format(key.getLastUsedAt()))
|
||||
.status(key.isActive() ? "active" : "revoked")
|
||||
.usageToday(usageToday)
|
||||
.usageMonth(usageMonth)
|
||||
.usageTotal(usageTotal)
|
||||
.build();
|
||||
}
|
||||
|
||||
private User requireCaller() {
|
||||
String username = userService.getCurrentUsername();
|
||||
if (username == null || username.isBlank() || "anonymousUser".equalsIgnoreCase(username)) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Not authenticated");
|
||||
}
|
||||
return userService
|
||||
.findByUsernameIgnoreCase(username)
|
||||
.orElseThrow(
|
||||
() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Unknown user"));
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* Records per-key usage off the request thread. Kept a separate bean so the {@code @Async} proxy is
|
||||
* honoured (a self-invocation from the resolver would run inline). Best-effort: never fails a
|
||||
* request. The actual writes go through {@link ApiKeyUsageWriter} so each step commits in its own
|
||||
* transaction and a first-write race can't drop a count.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiKeyUsageRecorder {
|
||||
|
||||
private final ApiKeyUsageWriter writer;
|
||||
|
||||
/** Bump today's tally for the key and stamp last-used. */
|
||||
@Async("auditExecutor")
|
||||
public void record(Long apiKeyId) {
|
||||
if (apiKeyId == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
long epochDay = Instant.now().atZone(ZoneOffset.UTC).toLocalDate().toEpochDay();
|
||||
// First writer of the day inserts the row; everyone else (and the loser of an insert
|
||||
// race) increments. Separate transactions mean a unique-key clash never rolls back an
|
||||
// already-counted request.
|
||||
if (writer.increment(apiKeyId, epochDay) == 0
|
||||
&& !firstUseInserted(apiKeyId, epochDay)) {
|
||||
writer.increment(apiKeyId, epochDay);
|
||||
}
|
||||
writer.stampLastUsed(apiKeyId);
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to record API key usage for id={}", apiKeyId, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether we inserted the day's first row. A lost insert race can surface either as a {@code
|
||||
* false} return or - when the failed flush marked the REQUIRES_NEW transaction rollback-only,
|
||||
* so its commit throws - as an exception; both mean "someone else inserted", so we treat any
|
||||
* failure as not-inserted and let the caller fall back to an increment rather than dropping the
|
||||
* count.
|
||||
*/
|
||||
private boolean firstUseInserted(Long apiKeyId, long epochDay) {
|
||||
try {
|
||||
return writer.tryInsertFirstUse(apiKeyId, epochDay);
|
||||
} catch (RuntimeException raced) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.security.model.ApiKeyDailyUsage;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyDailyUsageRepository;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyRepository;
|
||||
|
||||
/**
|
||||
* Per-step transactional writes for {@link ApiKeyUsageRecorder}. Each method runs in its own
|
||||
* ({@code REQUIRES_NEW}) transaction so a unique-key clash when two requests race to insert the
|
||||
* day's first row rolls back only that failed insert - never an already-counted request or the
|
||||
* last-used stamp.
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
class ApiKeyUsageWriter {
|
||||
|
||||
private final ApiKeyRepository apiKeyRepository;
|
||||
private final ApiKeyDailyUsageRepository usageRepository;
|
||||
|
||||
/** Bump today's tally if the row already exists; returns rows updated (0 if none yet). */
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public int increment(Long apiKeyId, long epochDay) {
|
||||
return usageRepository.incrementIfPresent(apiKeyId, epochDay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert today's row with a count of 1. Flushes so a concurrent first-write's unique-key clash
|
||||
* surfaces here (returning false) instead of at commit; the caller then increments instead.
|
||||
*/
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public boolean tryInsertFirstUse(Long apiKeyId, long epochDay) {
|
||||
try {
|
||||
usageRepository.saveAndFlush(new ApiKeyDailyUsage(apiKeyId, epochDay, 1));
|
||||
return true;
|
||||
} catch (DataIntegrityViolationException raced) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void stampLastUsed(Long apiKeyId) {
|
||||
apiKeyRepository
|
||||
.findById(apiKeyId)
|
||||
.ifPresent(
|
||||
key -> {
|
||||
key.setLastUsedAt(Instant.now());
|
||||
apiKeyRepository.save(key);
|
||||
});
|
||||
}
|
||||
}
|
||||
+16
-10
@@ -95,6 +95,7 @@ public class UserService implements UserServiceInterface {
|
||||
private final ResourceGrantRepository resourceGrantRepository;
|
||||
private final IntegrationConfigRepository integrationConfigRepository;
|
||||
private final TeamMembershipService teamMembershipService;
|
||||
private final ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
|
||||
@Transactional
|
||||
public void processSSOPostLogin(
|
||||
@@ -147,15 +148,16 @@ public class UserService implements UserServiceInterface {
|
||||
}
|
||||
|
||||
public Authentication getAuthentication(String apiKey) {
|
||||
Optional<User> user = getUserByApiKey(apiKey);
|
||||
if (user.isEmpty()) {
|
||||
throw new UsernameNotFoundException("API key is not valid");
|
||||
}
|
||||
// Convert the user into an Authentication object
|
||||
return new UsernamePasswordAuthenticationToken( // principal (typically the user)
|
||||
user, // credentials (we don't expose the password or API key here)
|
||||
null, // user's authorities (roles/permissions)
|
||||
getAuthorities(user.get()));
|
||||
// Resolve through the shared service (multi-key table, then the legacy per-user column).
|
||||
// The key runs as its owner with the owner's authorities.
|
||||
var resolved =
|
||||
apiKeyAuthenticationService
|
||||
.authenticate(apiKey)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("API key is not valid"));
|
||||
return new UsernamePasswordAuthenticationToken(
|
||||
resolved.user(), // principal
|
||||
null, // credentials (we don't expose the password or API key here)
|
||||
resolved.authorities()); // the owner's authorities
|
||||
}
|
||||
|
||||
private Collection<? extends GrantedAuthority> getAuthorities(User user) {
|
||||
@@ -173,6 +175,9 @@ public class UserService implements UserServiceInterface {
|
||||
|
||||
public User addApiKeyToUser(String username) {
|
||||
Optional<User> userOpt = findByUsernameIgnoreCase(username);
|
||||
// Rotating/regenerating the legacy key must also revoke its migrated api_keys shadow row,
|
||||
// otherwise the old secret keeps authenticating (it resolves from api_keys first).
|
||||
userOpt.map(User::getApiKey).ifPresent(apiKeyAuthenticationService::revokeMigratedKey);
|
||||
User user = saveUser(userOpt, generateApiKey());
|
||||
try {
|
||||
databaseService.exportDatabase();
|
||||
@@ -220,7 +225,8 @@ public class UserService implements UserServiceInterface {
|
||||
}
|
||||
|
||||
public Optional<User> getUserByApiKey(String apiKey) {
|
||||
return userRepository.findByApiKey(apiKey);
|
||||
// Resolves the multi-key api_keys table first, then the legacy per-user column.
|
||||
return apiKeyAuthenticationService.resolveUser(apiKey);
|
||||
}
|
||||
|
||||
public Optional<User> loadUserByApiKey(String apiKey) {
|
||||
|
||||
+9
-4
@@ -65,12 +65,13 @@ public class PortalDocumentsService {
|
||||
// "API". The automation marker distinguishes a policy-run step from real API traffic.
|
||||
boolean automation = isAutomation(data);
|
||||
String policyName = asString(data.get("policyName"));
|
||||
String origin = asString(data.get("__origin"));
|
||||
String source =
|
||||
automation
|
||||
? (policyName != null && !policyName.isBlank()
|
||||
? "Policy: " + policyName
|
||||
: "Policy automation")
|
||||
: sourceLabel(asString(data.get("__origin")));
|
||||
: sourceLabel(origin, asString(data.get("__apiKeyLabel")));
|
||||
String product = automation ? "Automation" : productLabel(source);
|
||||
String action = prettyTool(path);
|
||||
boolean failed = isFailure(data);
|
||||
@@ -173,9 +174,12 @@ public class PortalDocumentsService {
|
||||
return code instanceof Number n && n.intValue() >= 400;
|
||||
}
|
||||
|
||||
private static String sourceLabel(String origin) {
|
||||
private static String sourceLabel(String origin, String apiKeyLabel) {
|
||||
if ("API".equals(origin)) {
|
||||
return "API integration";
|
||||
// Attribute to the specific named key when known, else the generic API channel.
|
||||
return apiKeyLabel != null && !apiKeyLabel.isBlank()
|
||||
? "API key · " + apiKeyLabel
|
||||
: "API integration";
|
||||
}
|
||||
if ("SYSTEM".equals(origin)) {
|
||||
return "System";
|
||||
@@ -184,7 +188,8 @@ public class PortalDocumentsService {
|
||||
}
|
||||
|
||||
private static String productLabel(String source) {
|
||||
return "API integration".equals(source) ? "API" : "Editor";
|
||||
// Covers both the generic "API integration" and per-key "API key · <label>" sources.
|
||||
return source != null && source.startsWith("API") ? "API" : "Editor";
|
||||
}
|
||||
|
||||
private static boolean isAutomation(Map<String, Object> data) {
|
||||
|
||||
+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));
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -29,6 +29,7 @@ import stirling.software.proprietary.security.database.repository.PersistentLogi
|
||||
import stirling.software.proprietary.security.filter.IPRateLimitingFilter;
|
||||
import stirling.software.proprietary.security.filter.JwtAuthenticationFilter;
|
||||
import stirling.software.proprietary.security.filter.UserAuthenticationFilter;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.CustomUserDetailsService;
|
||||
import stirling.software.proprietary.security.service.JwtServiceInterface;
|
||||
import stirling.software.proprietary.security.service.LoginAttemptService;
|
||||
@@ -160,7 +161,9 @@ class SecurityConfigurationTest {
|
||||
@Test
|
||||
@DisplayName("jwtAuthenticationFilter is created")
|
||||
void jwtAuthenticationFilter() {
|
||||
JwtAuthenticationFilter filter = newConfig(true).jwtAuthenticationFilter();
|
||||
JwtAuthenticationFilter filter =
|
||||
newConfig(true)
|
||||
.jwtAuthenticationFilter(mock(ApiKeyAuthenticationService.class));
|
||||
assertThat(filter).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
+14
-3
@@ -29,6 +29,8 @@ import org.springframework.security.core.session.SessionInformation;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService.ApiKeyAuthentication;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
|
||||
@@ -37,6 +39,7 @@ import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
class UserAuthenticationFilterTest {
|
||||
|
||||
@Mock private UserService userService;
|
||||
@Mock private ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
@Mock private SessionPersistentRegistry sessionPersistentRegistry;
|
||||
|
||||
private ApplicationProperties.Security securityProp;
|
||||
@@ -60,7 +63,11 @@ class UserAuthenticationFilterTest {
|
||||
|
||||
private UserAuthenticationFilter filter(boolean loginEnabled) {
|
||||
return new UserAuthenticationFilter(
|
||||
securityProp, userService, sessionPersistentRegistry, loginEnabled);
|
||||
securityProp,
|
||||
userService,
|
||||
apiKeyAuthenticationService,
|
||||
sessionPersistentRegistry,
|
||||
loginEnabled);
|
||||
}
|
||||
|
||||
private static User enabledUser(String username) {
|
||||
@@ -99,7 +106,11 @@ class UserAuthenticationFilterTest {
|
||||
User user = enabledUser("api-user");
|
||||
user.addAuthority(
|
||||
new stirling.software.proprietary.security.model.Authority("ROLE_USER", user));
|
||||
when(userService.getUserByApiKey("good-key")).thenReturn(Optional.of(user));
|
||||
when(apiKeyAuthenticationService.authenticate("good-key"))
|
||||
.thenReturn(
|
||||
Optional.of(
|
||||
new ApiKeyAuthentication(
|
||||
user, "Prod (sk_demo0000)", user.getAuthorities())));
|
||||
when(userService.usernameExistsIgnoreCase("api-user")).thenReturn(true);
|
||||
when(userService.isUserDisabled("api-user")).thenReturn(false);
|
||||
when(sessionPersistentRegistry.getAllSessions(any(), anyBoolean()))
|
||||
@@ -117,7 +128,7 @@ class UserAuthenticationFilterTest {
|
||||
void invalidApiKeyRejected() throws Exception {
|
||||
request.setRequestURI("/api/v1/some/protected");
|
||||
request.addHeader("X-API-KEY", "bad-key");
|
||||
when(userService.getUserByApiKey("bad-key")).thenReturn(Optional.empty());
|
||||
when(apiKeyAuthenticationService.authenticate("bad-key")).thenReturn(Optional.empty());
|
||||
|
||||
filter(true).doFilter(request, response, filterChain);
|
||||
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
package stirling.software.proprietary.security.filter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("UserBasedRateLimitingFilter")
|
||||
class UserBasedRateLimitingFilterTest {
|
||||
|
||||
@AfterEach
|
||||
void clear() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private void authenticateAs(String username) {
|
||||
User u = new User();
|
||||
u.setUsername(username);
|
||||
u.setEnabled(true);
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(
|
||||
new ApiKeyAuthenticationToken(
|
||||
u,
|
||||
"irrelevant",
|
||||
List.of(new SimpleGrantedAuthority(Role.USER.getRoleId()))));
|
||||
}
|
||||
|
||||
private long remainingAfterApiPost(UserBasedRateLimitingFilter filter, String apiKey)
|
||||
throws Exception {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/general/x");
|
||||
req.addHeader("X-API-KEY", apiKey);
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
filter.doFilter(req, res, new MockFilterChain());
|
||||
return Long.parseLong(res.getHeader("X-Rate-Limit-Remaining"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("all of a user's keys share ONE bucket - minting keys can't multiply the quota")
|
||||
void keysShareOnePerUserBucket() throws Exception {
|
||||
UserBasedRateLimitingFilter filter = new UserBasedRateLimitingFilter(true);
|
||||
authenticateAs("alice");
|
||||
|
||||
long afterKeyA = remainingAfterApiPost(filter, "key-A");
|
||||
long afterKeyB = remainingAfterApiPost(filter, "key-B"); // different key, same user
|
||||
|
||||
// The second (different) key drew from the SAME per-user bucket, so remaining fell by one.
|
||||
// If it were keyed per-API-key, both would report the same remaining.
|
||||
assertThat(afterKeyB).isEqualTo(afterKeyA - 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("non-POST requests are not rate limited")
|
||||
void nonPostPassesThrough() throws Exception {
|
||||
UserBasedRateLimitingFilter filter = new UserBasedRateLimitingFilter(true);
|
||||
authenticateAs("alice");
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/api/v1/general/x");
|
||||
req.addHeader("X-API-KEY", "key-A");
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
|
||||
filter.doFilter(req, res, chain);
|
||||
|
||||
assertThat(res.getHeader("X-Rate-Limit-Remaining")).isNull();
|
||||
assertThat(chain.getRequest()).isNotNull(); // passed down the chain
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rate limiting disabled: passes through untouched")
|
||||
void disabledPassesThrough() throws Exception {
|
||||
UserBasedRateLimitingFilter filter = new UserBasedRateLimitingFilter(false);
|
||||
authenticateAs("alice");
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/general/x");
|
||||
req.addHeader("X-API-KEY", "key-A");
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(req, res, new MockFilterChain());
|
||||
|
||||
assertThat(res.getHeader("X-Rate-Limit-Remaining")).isNull();
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.security.database.repository.UserRepository;
|
||||
import stirling.software.proprietary.security.model.ApiKey;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyRepository;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("ApiKeyAuthenticationService")
|
||||
class ApiKeyAuthenticationServiceTest {
|
||||
|
||||
@Mock private ApiKeyRepository apiKeyRepository;
|
||||
@Mock private ApiKeyUsageRecorder usageRecorder;
|
||||
@Mock private UserRepository userRepository;
|
||||
@InjectMocks private ApiKeyAuthenticationService service;
|
||||
|
||||
private User user(long id, boolean enabled) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setUsername("user" + id);
|
||||
u.setEnabled(enabled);
|
||||
return u;
|
||||
}
|
||||
|
||||
private ApiKey key(long id, long ownerId, boolean enabled, Instant revoked) {
|
||||
return ApiKey.builder()
|
||||
.id(id)
|
||||
.name("Production ingest")
|
||||
.keyHash(ApiKeyHasher.hash("raw-" + id))
|
||||
.prefix("sk_demo0000")
|
||||
.ownerUserId(ownerId)
|
||||
.enabled(enabled)
|
||||
.revokedAt(revoked)
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("resolves an active multi-key to its owner and records usage")
|
||||
void resolvesActiveKey() {
|
||||
String raw = "raw-1";
|
||||
when(apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(raw)))
|
||||
.thenReturn(Optional.of(key(1, 7, true, null)));
|
||||
when(userRepository.findById(7L)).thenReturn(Optional.of(user(7, true)));
|
||||
|
||||
var result = service.authenticate(raw);
|
||||
|
||||
assertThat(result).isPresent();
|
||||
assertThat(result.get().user().getId()).isEqualTo(7L);
|
||||
assertThat(result.get().auditLabel()).isEqualTo("Production ingest (sk_demo0000)");
|
||||
verify(usageRecorder).record(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects a revoked key without recording usage")
|
||||
void rejectsRevokedKey() {
|
||||
String raw = "raw-2";
|
||||
when(apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(raw)))
|
||||
.thenReturn(Optional.of(key(2, 7, true, Instant.now())));
|
||||
|
||||
assertThat(service.authenticate(raw)).isEmpty();
|
||||
verifyNoInteractions(usageRecorder);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects a key whose owner is disabled")
|
||||
void rejectsDisabledOwner() {
|
||||
String raw = "raw-3";
|
||||
when(apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(raw)))
|
||||
.thenReturn(Optional.of(key(3, 8, true, null)));
|
||||
when(userRepository.findById(8L)).thenReturn(Optional.of(user(8, false)));
|
||||
|
||||
assertThat(service.authenticate(raw)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("falls back to the legacy per-user column, with no per-key label")
|
||||
void legacyFallback() {
|
||||
String raw = "legacy-key";
|
||||
when(apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(raw))).thenReturn(Optional.empty());
|
||||
when(userRepository.findByApiKey(raw)).thenReturn(Optional.of(user(9, true)));
|
||||
|
||||
var result = service.authenticate(raw);
|
||||
|
||||
assertThat(result).isPresent();
|
||||
assertThat(result.get().user().getId()).isEqualTo(9L);
|
||||
assertThat(result.get().auditLabel()).isNull();
|
||||
verifyNoInteractions(usageRecorder);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("blank keys resolve to nothing")
|
||||
void blankKey() {
|
||||
assertThat(service.authenticate(" ")).isEmpty();
|
||||
assertThat(service.resolveUser(null)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a key authenticates with its owner's authorities (owner acts as self)")
|
||||
void keyKeepsOwnerAuthorities() {
|
||||
String raw = "raw-6";
|
||||
User owner = user(8, true);
|
||||
owner.addAuthority(new Authority(Role.ADMIN.getRoleId(), owner));
|
||||
when(apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(raw)))
|
||||
.thenReturn(Optional.of(key(6, 8, true, null)));
|
||||
when(userRepository.findById(8L)).thenReturn(Optional.of(owner));
|
||||
|
||||
var result = service.authenticate(raw);
|
||||
|
||||
List<String> auths =
|
||||
result.get().authorities().stream().map(GrantedAuthority::getAuthority).toList();
|
||||
assertThat(auths).contains(Role.ADMIN.getRoleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("revokeMigratedKey disables the shadow row so a rotated legacy key stops working")
|
||||
void revokeMigratedKeyRevokesRow() {
|
||||
String raw = "raw-9";
|
||||
ApiKey shadow = key(9, 1, true, null);
|
||||
when(apiKeyRepository.findByKeyHash(ApiKeyHasher.hash(raw)))
|
||||
.thenReturn(Optional.of(shadow));
|
||||
|
||||
service.revokeMigratedKey(raw);
|
||||
|
||||
assertThat(shadow.isEnabled()).isFalse();
|
||||
assertThat(shadow.getRevokedAt()).isNotNull();
|
||||
verify(apiKeyRepository).save(shadow);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@DisplayName("ApiKeyHasher")
|
||||
class ApiKeyHasherTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("generated keys are unique, prefixed, and hash deterministically")
|
||||
void generateAndHash() {
|
||||
String a = ApiKeyHasher.generateRawKey();
|
||||
String b = ApiKeyHasher.generateRawKey();
|
||||
|
||||
assertThat(a).startsWith("sk_").isNotEqualTo(b);
|
||||
// Same input hashes the same; SHA-256 hex is 64 chars.
|
||||
assertThat(ApiKeyHasher.hash(a)).isEqualTo(ApiKeyHasher.hash(a)).hasSize(64);
|
||||
assertThat(ApiKeyHasher.hash(a)).isNotEqualTo(ApiKeyHasher.hash(b));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("hash never returns the raw key")
|
||||
void hashHidesRaw() {
|
||||
String raw = ApiKeyHasher.generateRawKey();
|
||||
assertThat(ApiKeyHasher.hash(raw)).isNotEqualTo(raw);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("display prefix is a short non-secret leading fragment")
|
||||
void displayPrefix() {
|
||||
String raw = ApiKeyHasher.generateRawKey();
|
||||
String prefix = ApiKeyHasher.displayPrefix(raw);
|
||||
assertThat(prefix).hasSize(11).startsWith("sk_");
|
||||
assertThat(raw).startsWith(prefix);
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
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.anyLong;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import stirling.software.proprietary.model.api.apikey.CreateApiKeyRequest;
|
||||
import stirling.software.proprietary.model.api.apikey.CreatedApiKeyDto;
|
||||
import stirling.software.proprietary.model.api.apikey.PortalApiKeysResponse;
|
||||
import stirling.software.proprietary.security.database.repository.UserRepository;
|
||||
import stirling.software.proprietary.security.model.ApiKey;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyDailyUsageRepository;
|
||||
import stirling.software.proprietary.security.repository.ApiKeyRepository;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("ApiKeyManagementService")
|
||||
class ApiKeyManagementServiceTest {
|
||||
|
||||
@Mock private ApiKeyRepository apiKeyRepository;
|
||||
@Mock private ApiKeyDailyUsageRepository usageRepository;
|
||||
@Mock private UserRepository userRepository;
|
||||
@Mock private UserService userService;
|
||||
@Mock private ApiKeyLegacyMigrator legacyMigrator;
|
||||
@InjectMocks private ApiKeyManagementService service;
|
||||
|
||||
private User caller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
caller = new User();
|
||||
caller.setId(1L);
|
||||
caller.setUsername("alice");
|
||||
lenient().when(userService.getCurrentUsername()).thenReturn("alice");
|
||||
lenient()
|
||||
.when(userService.findByUsernameIgnoreCase("alice"))
|
||||
.thenReturn(Optional.of(caller));
|
||||
lenient().when(apiKeyRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
lenient().when(usageRepository.countForDayByIds(any(), anyLong())).thenReturn(List.of());
|
||||
lenient().when(usageRepository.sumSinceByIds(any(), anyLong())).thenReturn(List.of());
|
||||
}
|
||||
|
||||
private ApiKey personalKey(long id, long ownerId) {
|
||||
return ApiKey.builder()
|
||||
.id(id)
|
||||
.name("Key " + id)
|
||||
.keyHash("hash" + id)
|
||||
.prefix("sk_demo0000")
|
||||
.ownerUserId(ownerId)
|
||||
.enabled(true)
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
}
|
||||
|
||||
// ---- migration safety ---------------------------------------------------
|
||||
|
||||
@Test
|
||||
@DisplayName("an existing legacy key migrates to an owner-only row")
|
||||
void legacyKeyMigratesAsPersonal() {
|
||||
caller.setApiKey("legacy-raw-key");
|
||||
when(apiKeyRepository.existsByKeyHash(ApiKeyHasher.hash("legacy-raw-key")))
|
||||
.thenReturn(false);
|
||||
when(apiKeyRepository.findByOwnerUserIdOrderByCreatedAtDesc(1L)).thenReturn(List.of());
|
||||
|
||||
service.listVisibleKeys();
|
||||
|
||||
// Migration insert is isolated in its own transaction (ApiKeyLegacyMigrator).
|
||||
ArgumentCaptor<ApiKey> saved = ArgumentCaptor.forClass(ApiKey.class);
|
||||
verify(legacyMigrator).insertMigratedKey(saved.capture());
|
||||
ApiKey migrated = saved.getValue();
|
||||
assertThat(migrated.getOwnerUserId()).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("migration is idempotent - an already-migrated legacy key is not re-saved")
|
||||
void legacyKeyMigrationIdempotent() {
|
||||
caller.setApiKey("legacy-raw-key");
|
||||
when(apiKeyRepository.existsByKeyHash(ApiKeyHasher.hash("legacy-raw-key")))
|
||||
.thenReturn(true);
|
||||
when(apiKeyRepository.findByOwnerUserIdOrderByCreatedAtDesc(1L)).thenReturn(List.of());
|
||||
|
||||
service.listVisibleKeys();
|
||||
|
||||
verify(legacyMigrator, never()).insertMigratedKey(any());
|
||||
}
|
||||
|
||||
// ---- personal isolation -------------------------------------------------
|
||||
|
||||
@Test
|
||||
@DisplayName("listing scopes keys to the caller by owner id")
|
||||
void personalKeysScopedToOwner() {
|
||||
when(apiKeyRepository.findByOwnerUserIdOrderByCreatedAtDesc(1L))
|
||||
.thenReturn(List.of(personalKey(10, 1L)));
|
||||
|
||||
PortalApiKeysResponse res = service.listVisibleKeys();
|
||||
|
||||
assertThat(res.keys()).singleElement().satisfies(k -> assertThat(k.id()).isEqualTo("10"));
|
||||
// Isolation: the query is keyed by the caller's id, never a broad scan.
|
||||
verify(apiKeyRepository).findByOwnerUserIdOrderByCreatedAtDesc(1L);
|
||||
}
|
||||
|
||||
// ---- creation -----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@DisplayName("a user creates a personal key and gets a one-time secret")
|
||||
void createPersonalKey() {
|
||||
CreatedApiKeyDto created = service.createKey(new CreateApiKeyRequest("My key"));
|
||||
|
||||
assertThat(created.secret()).startsWith("sk_");
|
||||
ArgumentCaptor<ApiKey> saved = ArgumentCaptor.forClass(ApiKey.class);
|
||||
verify(apiKeyRepository).save(saved.capture());
|
||||
assertThat(saved.getValue().getOwnerUserId()).isEqualTo(1L);
|
||||
assertThat(saved.getValue().getName()).isEqualTo("My key");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects an over-long key name")
|
||||
void rejectsLongName() {
|
||||
String longName = "a".repeat(101);
|
||||
assertThatThrownBy(() -> service.createKey(new CreateApiKeyRequest(longName)))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.hasMessageContaining("characters or fewer");
|
||||
verify(apiKeyRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects a blank key name")
|
||||
void rejectsBlankName() {
|
||||
assertThatThrownBy(() -> service.createKey(new CreateApiKeyRequest(" ")))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.hasMessageContaining("required");
|
||||
verify(apiKeyRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("rejects creating a key past the per-user active-key cap")
|
||||
void rejectsPastActiveKeyCap() {
|
||||
when(apiKeyRepository.findByOwnerUserIdOrderByCreatedAtDesc(1L))
|
||||
.thenReturn(java.util.Collections.nCopies(50, personalKey(100, 1L)));
|
||||
|
||||
assertThatThrownBy(() -> service.createKey(new CreateApiKeyRequest("One too many")))
|
||||
.isInstanceOf(ResponseStatusException.class);
|
||||
verify(apiKeyRepository, never()).save(any());
|
||||
}
|
||||
|
||||
// ---- revocation ---------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@DisplayName("owner revokes their key and the legacy column is cleared")
|
||||
void revokePersonalClearsLegacy() {
|
||||
caller.setApiKey("legacy-raw-key");
|
||||
ApiKey legacyRow = personalKey(30, 1L);
|
||||
legacyRow.setKeyHash(ApiKeyHasher.hash("legacy-raw-key"));
|
||||
when(apiKeyRepository.findById(30L)).thenReturn(Optional.of(legacyRow));
|
||||
when(userRepository.findById(1L)).thenReturn(Optional.of(caller));
|
||||
|
||||
service.revokeKey(30L);
|
||||
|
||||
assertThat(legacyRow.isEnabled()).isFalse();
|
||||
assertThat(legacyRow.getRevokedAt()).isNotNull();
|
||||
assertThat(caller.getApiKey()).isNull();
|
||||
verify(userRepository).save(caller);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"a non-owner cannot revoke someone else's key (404, not 403, so ids can't be probed)")
|
||||
void revokeForeignKeyForbidden() {
|
||||
when(apiKeyRepository.findById(31L)).thenReturn(Optional.of(personalKey(31, 999L)));
|
||||
|
||||
assertThatThrownBy(() -> service.revokeKey(31L))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(
|
||||
e ->
|
||||
assertThat(((ResponseStatusException) e).getStatusCode().value())
|
||||
.isEqualTo(404));
|
||||
verify(apiKeyRepository, never()).save(any());
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
/**
|
||||
* Unit tests for the increment/insert/increment race protocol. {@code @Async} has no proxy in a
|
||||
* plain Mockito test, so {@code record()} runs inline and is directly testable.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@DisplayName("ApiKeyUsageRecorder")
|
||||
class ApiKeyUsageRecorderTest {
|
||||
|
||||
private static final long KEY = 7L;
|
||||
|
||||
@Mock private ApiKeyUsageWriter writer;
|
||||
@InjectMocks private ApiKeyUsageRecorder recorder;
|
||||
|
||||
@Test
|
||||
@DisplayName("a null key id is a no-op")
|
||||
void nullIdIsNoOp() {
|
||||
recorder.record(null);
|
||||
verifyNoInteractions(writer);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("row already exists: one increment, never inserts")
|
||||
void rowExistsFastPath() {
|
||||
when(writer.increment(eq(KEY), anyLong())).thenReturn(1);
|
||||
|
||||
recorder.record(KEY);
|
||||
|
||||
verify(writer, times(1)).increment(eq(KEY), anyLong());
|
||||
verify(writer, never()).tryInsertFirstUse(anyLong(), anyLong());
|
||||
verify(writer).stampLastUsed(KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("first writer of the day: increment misses, insert wins, no second increment")
|
||||
void firstWriterInserts() {
|
||||
when(writer.increment(eq(KEY), anyLong())).thenReturn(0);
|
||||
when(writer.tryInsertFirstUse(eq(KEY), anyLong())).thenReturn(true);
|
||||
|
||||
recorder.record(KEY);
|
||||
|
||||
verify(writer, times(1)).increment(eq(KEY), anyLong());
|
||||
verify(writer).tryInsertFirstUse(eq(KEY), anyLong());
|
||||
verify(writer).stampLastUsed(KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"lost the insert race: falls back to a second increment so the count is not dropped")
|
||||
void lostInsertRaceReincrements() {
|
||||
when(writer.increment(eq(KEY), anyLong())).thenReturn(0);
|
||||
when(writer.tryInsertFirstUse(eq(KEY), anyLong())).thenReturn(false);
|
||||
|
||||
recorder.record(KEY);
|
||||
|
||||
verify(writer, times(2)).increment(eq(KEY), anyLong());
|
||||
verify(writer).stampLastUsed(KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("insert throws (rollback-only commit): still re-increments, count not dropped")
|
||||
void insertThrowsStillReincrements() {
|
||||
when(writer.increment(eq(KEY), anyLong())).thenReturn(0);
|
||||
when(writer.tryInsertFirstUse(eq(KEY), anyLong()))
|
||||
.thenThrow(new RuntimeException("UnexpectedRollbackException"));
|
||||
|
||||
recorder.record(KEY);
|
||||
|
||||
verify(writer, times(2)).increment(eq(KEY), anyLong());
|
||||
verify(writer).stampLastUsed(KEY);
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -41,6 +41,7 @@ import stirling.software.proprietary.security.model.AuthenticationType;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService.ApiKeyAuthentication;
|
||||
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
import stirling.software.proprietary.storage.repository.FileShareAccessRepository;
|
||||
import stirling.software.proprietary.storage.repository.FileShareRepository;
|
||||
@@ -76,6 +77,7 @@ class UserServiceMoreTest {
|
||||
integrationConfigRepository;
|
||||
|
||||
@Mock private TeamMembershipService teamMembershipService;
|
||||
@Mock private ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
|
||||
@InjectMocks private UserService userService;
|
||||
|
||||
@@ -99,7 +101,8 @@ class UserServiceMoreTest {
|
||||
void getAuthenticationValid() {
|
||||
User u = user("api");
|
||||
u.addAuthority(new Authority("ROLE_USER", u));
|
||||
when(userRepository.findByApiKey("k")).thenReturn(Optional.of(u));
|
||||
when(apiKeyAuthenticationService.authenticate("k"))
|
||||
.thenReturn(Optional.of(new ApiKeyAuthentication(u, null, u.getAuthorities())));
|
||||
|
||||
assertThat(userService.getAuthentication("k")).isNotNull();
|
||||
}
|
||||
@@ -107,7 +110,7 @@ class UserServiceMoreTest {
|
||||
@Test
|
||||
@DisplayName("getAuthentication throws when key is unknown")
|
||||
void getAuthenticationInvalid() {
|
||||
when(userRepository.findByApiKey("bad")).thenReturn(Optional.empty());
|
||||
when(apiKeyAuthenticationService.authenticate("bad")).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> userService.getAuthentication("bad"))
|
||||
.isInstanceOf(UsernameNotFoundException.class);
|
||||
|
||||
+22
@@ -71,6 +71,7 @@ class UserServiceTest {
|
||||
integrationConfigRepository;
|
||||
|
||||
@Mock private TeamMembershipService teamMembershipService;
|
||||
@Mock private ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
|
||||
@Spy @InjectMocks private UserService userService;
|
||||
|
||||
@@ -196,6 +197,27 @@ class UserServiceTest {
|
||||
verify(userRepository).save(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addApiKeyToUserRevokesOldMigratedShadowRow() {
|
||||
User user = new User();
|
||||
user.setUsername("user");
|
||||
user.setApiKey("old-secret");
|
||||
when(userRepository.findByUsernameIgnoreCase("user")).thenReturn(Optional.of(user));
|
||||
when(userRepository.findByApiKey(any())).thenReturn(Optional.empty());
|
||||
when(userRepository.save(any(User.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
User updated = userService.addApiKeyToUser("user");
|
||||
|
||||
// Rotating a legacy key must revoke its migrated api_keys shadow row with the OLD secret,
|
||||
// and do so before the new key is generated - otherwise the old secret keeps
|
||||
// authenticating.
|
||||
org.mockito.InOrder inOrder = inOrder(apiKeyAuthenticationService, userRepository);
|
||||
inOrder.verify(apiKeyAuthenticationService).revokeMigratedKey("old-secret");
|
||||
inOrder.verify(userRepository).save(user);
|
||||
assertNotEquals("old-secret", updated.getApiKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getApiKeyForUserCreatesWhenMissing() {
|
||||
User user = new User();
|
||||
|
||||
+14
@@ -70,4 +70,18 @@ class PortalDocumentsServiceTest {
|
||||
assertThat(doc.getProduct()).isEqualTo("API");
|
||||
assertThat(doc.getSource()).isEqualTo("API integration");
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiDocumentIsAttributedToItsNamedKey() {
|
||||
PortalReviewDocumentDto doc =
|
||||
onlyDoc(
|
||||
"{\"path\":\"/api/v1/misc/compress-pdf\",\"__origin\":\"API\","
|
||||
+ "\"__apiKeyLabel\":\"Production ingest (sk_demo0000)\","
|
||||
+ "\"files\":[{\"name\":\"a.pdf\",\"type\":\"application/pdf\"}],"
|
||||
+ "\"statusCode\":200}");
|
||||
|
||||
// The specific key label surfaces as the source; product stays "API".
|
||||
assertThat(doc.getProduct()).isEqualTo("API");
|
||||
assertThat(doc.getSource()).isEqualTo("API key · Production ingest (sk_demo0000)");
|
||||
}
|
||||
}
|
||||
|
||||
+20
-5
@@ -18,6 +18,7 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
@@ -43,6 +44,8 @@ import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
|
||||
import stirling.software.proprietary.security.model.AuthenticationType;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService.ApiKeyAuthentication;
|
||||
import stirling.software.proprietary.security.service.TeamService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.saas.model.AmrMethod;
|
||||
@@ -65,6 +68,7 @@ public class SupabaseAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final SupabaseUserService supabaseUserService;
|
||||
private final SaasTeamService saasTeamService;
|
||||
private final JwtDecoder jwtDecoder;
|
||||
private final ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
private final AuthenticationEntryPoint authenticationEntryPoint =
|
||||
new BearerTokenAuthenticationEntryPoint();
|
||||
|
||||
@@ -73,12 +77,14 @@ public class SupabaseAuthenticationFilter extends OncePerRequestFilter {
|
||||
UserService userService,
|
||||
SupabaseUserService supabaseUserService,
|
||||
SaasTeamService saasTeamService,
|
||||
JwtDecoder jwtDecoder) {
|
||||
JwtDecoder jwtDecoder,
|
||||
ApiKeyAuthenticationService apiKeyAuthenticationService) {
|
||||
this.teamService = teamService;
|
||||
this.userService = userService;
|
||||
this.supabaseUserService = supabaseUserService;
|
||||
this.saasTeamService = saasTeamService;
|
||||
this.jwtDecoder = jwtDecoder;
|
||||
this.apiKeyAuthenticationService = apiKeyAuthenticationService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -86,6 +92,9 @@ public class SupabaseAuthenticationFilter extends OncePerRequestFilter {
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// Start clean so a pooled thread can't inherit a prior request's API-key label.
|
||||
MDC.remove(ApiKeyAuthenticationService.AUDIT_LABEL_MDC_KEY);
|
||||
|
||||
if (isStaticResource(request.getContextPath(), request.getRequestURI())) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
@@ -406,16 +415,22 @@ public class SupabaseAuthenticationFilter extends OncePerRequestFilter {
|
||||
return false;
|
||||
}
|
||||
|
||||
Optional<User> user = userService.getUserByApiKey(apiKey);
|
||||
if (user.isEmpty()) {
|
||||
// Resolves the multi-key table then the legacy key, records per-key usage, and yields a
|
||||
// label for the processor's document-source attribution.
|
||||
Optional<ApiKeyAuthentication> resolved = apiKeyAuthenticationService.authenticate(apiKey);
|
||||
if (resolved.isEmpty()) {
|
||||
throw new InvalidBearerTokenException("Invalid API Key.");
|
||||
}
|
||||
User user = resolved.get().user();
|
||||
|
||||
userService.trackApiKeyFirstUse(user.get());
|
||||
userService.trackApiKeyFirstUse(user);
|
||||
|
||||
ApiKeyAuthenticationToken authToken =
|
||||
new ApiKeyAuthenticationToken(user.get(), apiKey, user.get().getAuthorities());
|
||||
new ApiKeyAuthenticationToken(user, apiKey, resolved.get().authorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
if (resolved.get().auditLabel() != null) {
|
||||
MDC.put(ApiKeyAuthenticationService.AUDIT_LABEL_MDC_KEY, resolved.get().auditLabel());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.util.RequestUriUtils;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;
|
||||
import stirling.software.proprietary.security.service.TeamService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.saas.accountlink.DeviceCredentialAuthenticationFilter;
|
||||
@@ -69,6 +70,7 @@ public class SupabaseSecurityConfig {
|
||||
private final SupabaseUserService supabaseUserService;
|
||||
private final SaasTeamService saasTeamService;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final ApiKeyAuthenticationService apiKeyAuthenticationService;
|
||||
|
||||
@Value("${app.supabase.issuer:}")
|
||||
private String issuer;
|
||||
@@ -125,7 +127,8 @@ public class SupabaseSecurityConfig {
|
||||
userService,
|
||||
supabaseUserService,
|
||||
saasTeamService,
|
||||
jwtDecoder),
|
||||
jwtDecoder,
|
||||
apiKeyAuthenticationService),
|
||||
BearerTokenAuthenticationFilter.class)
|
||||
.exceptionHandling(
|
||||
ex ->
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Named, multi-key personal API keys, plus per-key daily usage.
|
||||
-- Idempotent: Hibernate ddl-auto=update may already have created these on some deployments.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
key_hash VARCHAR(64) NOT NULL,
|
||||
prefix VARCHAR(32) NOT NULL,
|
||||
owner_user_id BIGINT NOT NULL,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
last_used_at TIMESTAMPTZ,
|
||||
revoked_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_api_key_hash ON api_keys (key_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_key_owner ON api_keys (owner_user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_key_daily_usage (
|
||||
api_key_id BIGINT NOT NULL,
|
||||
epoch_day BIGINT NOT NULL,
|
||||
count BIGINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (api_key_id, epoch_day)
|
||||
);
|
||||
+16
-2
@@ -58,6 +58,10 @@ class SupabaseAuthenticationFilterMoreTest {
|
||||
@Mock private SaasTeamService saasTeamService;
|
||||
@Mock private JwtDecoder jwtDecoder;
|
||||
|
||||
@Mock
|
||||
private stirling.software.proprietary.security.service.ApiKeyAuthenticationService
|
||||
apiKeyAuthenticationService;
|
||||
|
||||
private SupabaseAuthenticationFilter filter;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
@@ -68,7 +72,12 @@ class SupabaseAuthenticationFilterMoreTest {
|
||||
SecurityContextHolder.clearContext();
|
||||
filter =
|
||||
new SupabaseAuthenticationFilter(
|
||||
teamService, userService, supabaseUserService, saasTeamService, jwtDecoder);
|
||||
teamService,
|
||||
userService,
|
||||
supabaseUserService,
|
||||
saasTeamService,
|
||||
jwtDecoder,
|
||||
apiKeyAuthenticationService);
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
chain = new MockFilterChain();
|
||||
@@ -234,7 +243,12 @@ class SupabaseAuthenticationFilterMoreTest {
|
||||
@DisplayName("returns true and skips lookup when an api key sets an authenticated context")
|
||||
void apiKeyValidStillAuthenticates() throws Exception {
|
||||
User user = newUser("alice");
|
||||
when(userService.getUserByApiKey("k1")).thenReturn(Optional.of(user));
|
||||
when(apiKeyAuthenticationService.authenticate("k1"))
|
||||
.thenReturn(
|
||||
Optional.of(
|
||||
new stirling.software.proprietary.security.service
|
||||
.ApiKeyAuthenticationService.ApiKeyAuthentication(
|
||||
user, null, user.getAuthorities())));
|
||||
|
||||
request.setRequestURI("/api/v1/something");
|
||||
request.setMethod("POST");
|
||||
|
||||
+17
-3
@@ -48,6 +48,10 @@ class SupabaseAuthenticationFilterTest {
|
||||
@Mock private stirling.software.saas.service.SaasTeamService saasTeamService;
|
||||
@Mock private JwtDecoder jwtDecoder;
|
||||
|
||||
@Mock
|
||||
private stirling.software.proprietary.security.service.ApiKeyAuthenticationService
|
||||
apiKeyAuthenticationService;
|
||||
|
||||
private SupabaseAuthenticationFilter filter;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
@@ -58,7 +62,12 @@ class SupabaseAuthenticationFilterTest {
|
||||
SecurityContextHolder.clearContext();
|
||||
filter =
|
||||
new SupabaseAuthenticationFilter(
|
||||
teamService, userService, supabaseUserService, saasTeamService, jwtDecoder);
|
||||
teamService,
|
||||
userService,
|
||||
supabaseUserService,
|
||||
saasTeamService,
|
||||
jwtDecoder,
|
||||
apiKeyAuthenticationService);
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
chain = new MockFilterChain();
|
||||
@@ -85,7 +94,12 @@ class SupabaseAuthenticationFilterTest {
|
||||
void apiKeyHeaderPopulatesSecurityContext() throws Exception {
|
||||
User user = newUser("alice");
|
||||
user.setApiKey("api-key-123");
|
||||
when(userService.getUserByApiKey("api-key-123")).thenReturn(Optional.of(user));
|
||||
when(apiKeyAuthenticationService.authenticate("api-key-123"))
|
||||
.thenReturn(
|
||||
Optional.of(
|
||||
new stirling.software.proprietary.security.service
|
||||
.ApiKeyAuthenticationService.ApiKeyAuthentication(
|
||||
user, null, user.getAuthorities())));
|
||||
|
||||
request.setRequestURI("/api/v1/something");
|
||||
request.setMethod("POST");
|
||||
@@ -103,7 +117,7 @@ class SupabaseAuthenticationFilterTest {
|
||||
|
||||
@Test
|
||||
void invalidApiKeyTriggers401() throws Exception {
|
||||
when(userService.getUserByApiKey("nope")).thenReturn(Optional.empty());
|
||||
when(apiKeyAuthenticationService.authenticate("nope")).thenReturn(Optional.empty());
|
||||
|
||||
request.setRequestURI("/api/v1/something");
|
||||
request.setMethod("POST");
|
||||
|
||||
+10
-1
@@ -43,9 +43,18 @@ class SupabaseSecurityConfigMoreTest {
|
||||
@Mock private SupabaseUserService supabaseUserService;
|
||||
@Mock private SaasTeamService saasTeamService;
|
||||
|
||||
@Mock
|
||||
private stirling.software.proprietary.security.service.ApiKeyAuthenticationService
|
||||
apiKeyAuthenticationService;
|
||||
|
||||
private SupabaseSecurityConfig config(ApplicationProperties props) {
|
||||
return new SupabaseSecurityConfig(
|
||||
userService, teamService, supabaseUserService, saasTeamService, props);
|
||||
userService,
|
||||
teamService,
|
||||
supabaseUserService,
|
||||
saasTeamService,
|
||||
props,
|
||||
apiKeyAuthenticationService);
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
+22
@@ -21,6 +21,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import stirling.software.common.model.enumeration.TeamRole;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.model.TeamMembership;
|
||||
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
@@ -107,6 +108,27 @@ class TeamSecurityExpressionsTest {
|
||||
assertNull(expressions().currentUserTeamId());
|
||||
}
|
||||
|
||||
private User leaderUser() {
|
||||
User leader = new User();
|
||||
leader.setId(USER_ID);
|
||||
Team team = new Team();
|
||||
team.setId(TEAM_ID);
|
||||
leader.setTeam(team);
|
||||
return leader;
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiKeyOfALeaderStillLeads() {
|
||||
// A key acts as the owner; if they lead the team, the key leads.
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(
|
||||
new ApiKeyAuthenticationToken(leaderUser(), "sk_personal", List.of()));
|
||||
when(membershipRepository.findByTeamIdAndUserId(TEAM_ID, USER_ID))
|
||||
.thenReturn(Optional.of(membershipWithRole(TeamRole.LEADER)));
|
||||
|
||||
assertTrue(expressions().isCurrentUserTeamLeader());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unauthenticatedIsNotLeader() {
|
||||
// No authentication set on the context.
|
||||
|
||||
+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"
|
||||
|
||||
@@ -468,14 +468,6 @@ class EmlToPdfParams(ApiModel):
|
||||
)
|
||||
|
||||
|
||||
class EncodeCharcodesParams(ApiModel):
|
||||
font_name: str | None = None
|
||||
locator_char: str | None = None
|
||||
page_index: int | None = None
|
||||
pdf_base64: str | None = None
|
||||
text: str | None = None
|
||||
|
||||
|
||||
class ExtractAttachmentsParams(ApiModel):
|
||||
pass
|
||||
|
||||
@@ -1425,7 +1417,6 @@ class Model(
|
||||
| EditTextParams
|
||||
| MergePdfsParams
|
||||
| MultiPageLayoutParams
|
||||
| EncodeCharcodesParams
|
||||
| PdfToSinglePageParams
|
||||
| RearrangePagesParams
|
||||
| RemoveImagePdfParams
|
||||
@@ -1499,7 +1490,6 @@ class Model(
|
||||
| EditTextParams
|
||||
| MergePdfsParams
|
||||
| MultiPageLayoutParams
|
||||
| EncodeCharcodesParams
|
||||
| PdfToSinglePageParams
|
||||
| RearrangePagesParams
|
||||
| RemoveImagePdfParams
|
||||
@@ -1574,7 +1564,6 @@ type ParamToolModel = (
|
||||
| EditTextParams
|
||||
| MergePdfsParams
|
||||
| MultiPageLayoutParams
|
||||
| EncodeCharcodesParams
|
||||
| PdfToSinglePageParams
|
||||
| RearrangePagesParams
|
||||
| RemoveImagePdfParams
|
||||
@@ -1650,7 +1639,6 @@ class ToolEndpoint(StrEnum):
|
||||
EDIT_TEXT = "/api/v1/general/edit-text"
|
||||
MERGE_PDFS = "/api/v1/general/merge-pdfs"
|
||||
MULTI_PAGE_LAYOUT = "/api/v1/general/multi-page-layout"
|
||||
ENCODE_CHARCODES = "/api/v1/general/pdf-text-editor-v2/encode-charcodes"
|
||||
PDF_TO_SINGLE_PAGE = "/api/v1/general/pdf-to-single-page"
|
||||
REARRANGE_PAGES = "/api/v1/general/rearrange-pages"
|
||||
REMOVE_IMAGE_PDF = "/api/v1/general/remove-image-pdf"
|
||||
@@ -1724,7 +1712,6 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {
|
||||
ToolEndpoint.EDIT_TEXT: EditTextParams,
|
||||
ToolEndpoint.MERGE_PDFS: MergePdfsParams,
|
||||
ToolEndpoint.MULTI_PAGE_LAYOUT: MultiPageLayoutParams,
|
||||
ToolEndpoint.ENCODE_CHARCODES: EncodeCharcodesParams,
|
||||
ToolEndpoint.PDF_TO_SINGLE_PAGE: PdfToSinglePageParams,
|
||||
ToolEndpoint.REARRANGE_PAGES: RearrangePagesParams,
|
||||
ToolEndpoint.REMOVE_IMAGE_PDF: RemoveImagePdfParams,
|
||||
|
||||
@@ -22,10 +22,6 @@ const chromiumViewport = {
|
||||
viewport: { width: 1920, height: 1080 },
|
||||
};
|
||||
|
||||
// Dedicated dev-server port via V2_PORT so local runs don't collide with a
|
||||
// vite already on 5173 from other parallel work. Defaults to 5173.
|
||||
const DEV_PORT = process.env.V2_PORT ?? "5173";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./src/core/tests",
|
||||
testMatch: "**/*.spec.ts",
|
||||
@@ -50,7 +46,7 @@ export default defineConfig({
|
||||
expect: { timeout: 10_000 },
|
||||
|
||||
use: {
|
||||
baseURL: process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,
|
||||
baseURL: process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:5173",
|
||||
trace: "on-first-retry",
|
||||
screenshot: "only-on-failure",
|
||||
video: "on-first-retry",
|
||||
@@ -116,9 +112,9 @@ export default defineConfig({
|
||||
// blew the 30s navigationTimeout under --workers=3 - see
|
||||
// all-tool-pages-load.spec.ts). Locally, keep `vite` dev for HMR.
|
||||
command: process.env.CI
|
||||
? `npx vite preview --port ${DEV_PORT} --strictPort`
|
||||
: `npx vite --port ${DEV_PORT} --strictPort`,
|
||||
url: `http://localhost:${DEV_PORT}`,
|
||||
? "npx vite preview --port 5173 --strictPort"
|
||||
: "npx vite",
|
||||
url: "http://localhost:5173",
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
},
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Noto Sans'.
|
||||
Copyright 2014-2021 Google Inc (http://www.google.com/), with Reserved Font Name 'Noto Sans'.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
@@ -5724,282 +5724,6 @@ notIdealFor2 = "Magazines, brochures, or heavily designed documents"
|
||||
notIdealFor3 = "Instruction manuals with complex layouts"
|
||||
title = "Welcome to PDF Text Editor (Early Access)"
|
||||
|
||||
[pdfTextEditorV2]
|
||||
confirmReplaceDirty = "You have unsaved changes. Replace the open document and discard them?"
|
||||
save = "Save PDF"
|
||||
saveTooltip = "Download edited PDF (Ctrl+S)"
|
||||
title = "PDF Text Editor"
|
||||
workbenchLabel = "Editor"
|
||||
|
||||
[pdfTextEditorV2.drop]
|
||||
hint = "Releases on the editor stage replace any open document."
|
||||
title = "Drop a PDF to open"
|
||||
|
||||
[pdfTextEditorV2.error]
|
||||
decodeImage = "Could not decode the selected image."
|
||||
insertImage = "Could not insert the selected image."
|
||||
|
||||
[pdfTextEditorV2.find]
|
||||
close = "Close find bar"
|
||||
count = "{{current}} of {{total}}"
|
||||
findPlaceholder = "Find"
|
||||
noMatches = "No matches"
|
||||
replace = "Replace"
|
||||
replaceAll = "Replace all"
|
||||
replaced = " · {{count}} replaced"
|
||||
replacePlaceholder = "Replace with"
|
||||
title = "Find & replace"
|
||||
typeToSearch = "Type to search"
|
||||
|
||||
[pdfTextEditorV2.fonts]
|
||||
allPresent = "All letters & numbers present"
|
||||
missing = "Missing: {{glyphs}}"
|
||||
missingTooltip = "This font has no glyph for: {{glyphs}}. Typing one uses a standard fallback font."
|
||||
title = "Fonts"
|
||||
|
||||
[pdfTextEditorV2.fonts.compat]
|
||||
info = "Existing text edits perfectly. A new character an embedded font doesn't include falls back to a standard font."
|
||||
ok = "Every font includes the full alphabet and digits - type freely."
|
||||
warnOne = "{{count}} font missing some letters or numbers - typing those uses a standard fallback font."
|
||||
warnOther = "{{count}} fonts missing some letters or numbers - typing those uses a standard fallback font."
|
||||
|
||||
[pdfTextEditorV2.fonts.help]
|
||||
ariaLabel = "What do the font statuses mean?"
|
||||
embeddedDesc = "full font shipped in the PDF - most new characters match; a glyph the font lacks falls back."
|
||||
heading = "How fonts affect editing"
|
||||
standardDesc = "base-14 PDF font - the full standard character set is always available."
|
||||
subsetDesc = "only the document's existing characters are embedded - new ones usually fall back."
|
||||
|
||||
[pdfTextEditorV2.fonts.status.embedded]
|
||||
hint = "Full font embedded in the PDF. Existing text edits perfectly. New characters render in this font when it includes them - any it lacks (e.g. an accent or symbol the font never carried) fall back to a standard font."
|
||||
label = "Embedded"
|
||||
|
||||
[pdfTextEditorV2.fonts.status.standard]
|
||||
hint = "Standard PDF font (Helvetica / Times / Courier family). The full standard character set is always available, so existing text AND new characters render in this font."
|
||||
label = "Standard"
|
||||
|
||||
[pdfTextEditorV2.fonts.status.subset]
|
||||
hint = "Only the characters the document already uses are embedded. Existing text edits fine, but a new character the document never used will usually fall back to a standard font."
|
||||
label = "Subset"
|
||||
|
||||
[pdfTextEditorV2.help]
|
||||
ariaLabel = "Keyboard shortcuts"
|
||||
title = "Keyboard shortcuts"
|
||||
tooltip = "Keyboard shortcuts (?)"
|
||||
|
||||
[pdfTextEditorV2.help.arrangement]
|
||||
alignDesc = "Align edges L / centre / R / T / mid / B"
|
||||
alignKey = "Toolbar align"
|
||||
distributeDesc = "Equal horizontal / vertical spacing (3+)"
|
||||
distributeKey = "Toolbar distribute"
|
||||
frontBackDesc = "Bring to front / send to back"
|
||||
frontBackKey = "Toolbar front/back"
|
||||
heading = "Object arrangement"
|
||||
lockDesc = "Lock / unlock selection (session-only)"
|
||||
lockKey = "Lock button"
|
||||
orderDesc = "Bring forward / send backward (one step)"
|
||||
orderKey = "Toolbar ↑ ↓"
|
||||
|
||||
[pdfTextEditorV2.help.clipboard]
|
||||
copyDesc = "Copy selected text"
|
||||
copyKey = "Ctrl+C"
|
||||
cutDesc = "Cut selected (copy + delete)"
|
||||
cutKey = "Ctrl+X"
|
||||
heading = "Clipboard"
|
||||
pasteDesc = "Paste clipboard text as new run"
|
||||
pasteKey = "Ctrl+V"
|
||||
pastePlainDesc = "Paste as plain text"
|
||||
pastePlainKey = "Ctrl+Shift+V"
|
||||
|
||||
[pdfTextEditorV2.help.document]
|
||||
escDesc = "Clear selection / close find / close help"
|
||||
escKey = "Esc"
|
||||
heading = "Document"
|
||||
helpDesc = "This help"
|
||||
helpKey = "? / F1"
|
||||
saveDesc = "Download edited PDF"
|
||||
saveKey = "Ctrl+S"
|
||||
|
||||
[pdfTextEditorV2.help.editing]
|
||||
clickDesc = "Edit text"
|
||||
clickKey = "Click"
|
||||
deleteDesc = "Remove selected"
|
||||
deleteKey = "Delete"
|
||||
duplicateDesc = "Duplicate selected"
|
||||
duplicateKey = "Ctrl+D"
|
||||
groupDesc = "Group selected runs (Group button)"
|
||||
groupKey = "Ctrl+M"
|
||||
heading = "Editing"
|
||||
marqueeDesc = "Marquee multi-select"
|
||||
marqueeKey = "Ctrl+Shift+drag"
|
||||
moveDesc = "Move text run"
|
||||
moveKey = "Ctrl+Click + drag"
|
||||
selectAllDesc = "Select all"
|
||||
selectAllKey = "Ctrl+A"
|
||||
shiftClickDesc = "Add / remove a run from selection"
|
||||
shiftClickKey = "Shift+Click"
|
||||
undoRedoDesc = "Undo / Redo"
|
||||
undoRedoKey = "Ctrl+Z / Ctrl+Y"
|
||||
ungroupDesc = "Ungroup paragraph: select it, click Ungroup"
|
||||
ungroupKey = "-"
|
||||
|
||||
[pdfTextEditorV2.help.find]
|
||||
enterFindDesc = "Next match"
|
||||
enterFindKey = "Enter (in find)"
|
||||
enterReplaceDesc = "Replace one (Shift = Replace All)"
|
||||
enterReplaceKey = "Enter (in replace)"
|
||||
heading = "Find & Replace"
|
||||
nextDesc = "Next match (Shift = previous)"
|
||||
nextKey = "F3 / Ctrl+G"
|
||||
openDesc = "Open find bar (and replace)"
|
||||
openKey = "Ctrl+F"
|
||||
|
||||
[pdfTextEditorV2.help.formatting]
|
||||
boldItalicDesc = "Bold / italic"
|
||||
boldItalicKey = "Toolbar B / I"
|
||||
caseDesc = "Change case (upper/lower/title/sentence)"
|
||||
caseKey = "Toolbar case (Aa)"
|
||||
colourDesc = "Change fill colour"
|
||||
colourKey = "Toolbar colour"
|
||||
fontFamilyDesc = "Swap to base-14 font"
|
||||
fontFamilyKey = "Toolbar font family"
|
||||
fontSizeDesc = "Change font size"
|
||||
fontSizeKey = "Toolbar font size"
|
||||
heading = "Text formatting"
|
||||
|
||||
[pdfTextEditorV2.help.image]
|
||||
flipDesc = "Flip horizontally or vertically"
|
||||
flipKey = "Toolbar flip"
|
||||
heading = "Image"
|
||||
moveDesc = "Move image"
|
||||
moveKey = "Drag"
|
||||
resizeDesc = "Resize image"
|
||||
resizeKey = "Corner drag"
|
||||
rotateDesc = "Rotate 90° clockwise or counter-clockwise"
|
||||
rotateKey = "Toolbar rotate"
|
||||
|
||||
[pdfTextEditorV2.help.navigation]
|
||||
firstLastDesc = "First / last page"
|
||||
firstLastKey = "Ctrl+Home / Ctrl+End"
|
||||
heading = "Navigation"
|
||||
pageDesc = "Next / previous page"
|
||||
pageKey = "PageDown / PageUp"
|
||||
toolbarZoomDesc = "Manual zoom + Fit to width"
|
||||
toolbarZoomKey = "Toolbar zoom"
|
||||
zoomDesc = "Zoom in / out"
|
||||
zoomKey = "Ctrl+Wheel"
|
||||
|
||||
[pdfTextEditorV2.password]
|
||||
cancel = "Cancel"
|
||||
incorrect = "Incorrect password - try again."
|
||||
label = "Password"
|
||||
open = "Open"
|
||||
protected = "This PDF is password-protected."
|
||||
protectedNamed = "\"{{fileName}}\" is password-protected."
|
||||
title = "Password required"
|
||||
|
||||
[pdfTextEditorV2.run]
|
||||
lockedTitle = "Locked - use the Unlock button to edit"
|
||||
|
||||
[pdfTextEditorV2.saveRisk]
|
||||
cancel = "Cancel"
|
||||
downloadAnyway = "Download anyway"
|
||||
intro = "Downloading the edited copy rewrites the whole file. That means:"
|
||||
note = "Your edits are kept. The changes listed above are unavoidable when downloading the edited copy."
|
||||
title = "Saving will change this PDF"
|
||||
|
||||
[pdfTextEditorV2.sidebar]
|
||||
addImage = "Add image"
|
||||
addText = "Add text"
|
||||
clickPageToAddText = "Click page to add text"
|
||||
editorSettings = "Editor settings"
|
||||
group = "Group"
|
||||
groupingAuto = "Auto"
|
||||
groupingAutoHint = "Equal-spaced lines group into editable paragraphs."
|
||||
groupingLine = "Line"
|
||||
groupingLineHint = "Each source line is edited on its own. Switching clears undo history."
|
||||
groupTooltip = "Merge selected runs into one paragraph (Ctrl+M)"
|
||||
groupTooltipDisabled = "Select 2+ runs to merge"
|
||||
imageSelectedOne = "{{count}} image selected"
|
||||
imageSelectedOther = "{{count}} images selected"
|
||||
insert = "Insert"
|
||||
moveTipPrefix = "Hold "
|
||||
moveTipSuffix = " and drag a text box to move it."
|
||||
noFile = "No file loaded"
|
||||
noFileHint = "Pick a PDF from the Files panel on the left, or drop one in. The editor will open it automatically."
|
||||
opening = "Opening document..."
|
||||
paragraph = "Paragraph"
|
||||
runSelectedOne = "{{count}} text run selected"
|
||||
runSelectedOther = "{{count}} text runs selected"
|
||||
textBoxWidth = "Text box width"
|
||||
textGrouping = "Text grouping"
|
||||
ungroup = "Ungroup"
|
||||
ungroupTooltip = "Split this paragraph into one run per line"
|
||||
ungroupTooltipDisabled = "Select a multi-line paragraph to ungroup"
|
||||
widthGrow = "Grow"
|
||||
widthGrowHint = "Boxes widen to the right as you type (no wrapping)."
|
||||
widthWrap = "Wrap"
|
||||
widthWrapHint = "Boxes keep their width; extra text wraps onto new lines."
|
||||
|
||||
[pdfTextEditorV2.stage]
|
||||
loadingDocument = "Loading document"
|
||||
loadingProgress = "Loading progress"
|
||||
noDocument = "No document loaded."
|
||||
pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
|
||||
renderingPreview = "Rendering preview"
|
||||
|
||||
[pdfTextEditorV2.toolbar]
|
||||
alignBottom = "Align bottom"
|
||||
alignCentre = "Align centre"
|
||||
alignLabel = "Align · needs 2+ objects"
|
||||
alignLeft = "Align left"
|
||||
alignMiddle = "Align middle"
|
||||
alignRight = "Align right"
|
||||
alignTop = "Align top"
|
||||
arrange = "Arrange"
|
||||
bold = "Bold"
|
||||
bringForward = "Bring forward"
|
||||
bringToFront = "Bring to front"
|
||||
caseLower = "lowercase"
|
||||
caseSentence = "Sentence case"
|
||||
caseTitle = "Title Case"
|
||||
caseUpper = "UPPERCASE"
|
||||
changeCase = "Change case"
|
||||
changeCaseTooltip = "Change case (text runs only)"
|
||||
delete = "Delete selected"
|
||||
deleteTooltip = "Delete (Del)"
|
||||
distributeHorizontally = "Distribute horizontally"
|
||||
distributeLabel = "Distribute · needs 3+ objects"
|
||||
distributeVertically = "Distribute vertically"
|
||||
flipHorizontal = "Flip horizontal"
|
||||
flipVertical = "Flip vertical"
|
||||
fontColour = "Font colour"
|
||||
fontFamily = "Font family"
|
||||
fontSize = "Font size"
|
||||
image = "Image"
|
||||
italic = "Italic"
|
||||
lock = "Lock selection"
|
||||
lockTooltip = "Lock selection - prevents accidental edits"
|
||||
order = "Order"
|
||||
redo = "Redo"
|
||||
redoTooltip = "Redo (Ctrl+Y)"
|
||||
rotateLeft = "Rotate 90° left"
|
||||
rotateRight = "Rotate 90° right"
|
||||
selectImageFirst = "Select an image first"
|
||||
sendBackward = "Send backward"
|
||||
sendToBack = "Send to back"
|
||||
undo = "Undo"
|
||||
undoTooltip = "Undo (Ctrl+Z)"
|
||||
unlock = "Unlock selection"
|
||||
unlockTooltip = "Unlock selection - makes it editable again"
|
||||
|
||||
[pdfTextEditorV2.zoom]
|
||||
fit = "Fit"
|
||||
fitToWidth = "Fit to width"
|
||||
in = "Zoom in"
|
||||
out = "Zoom out"
|
||||
reset = "Reset zoom"
|
||||
|
||||
[PDFToCSV]
|
||||
header = "PDF to CSV"
|
||||
title = "PDF to CSV"
|
||||
|
||||
@@ -5781,288 +5781,6 @@ notIdealFor2 = "Magazines, brochures, or heavily designed documents"
|
||||
notIdealFor3 = "Instruction manuals with complex layouts"
|
||||
title = "Welcome to PDF Text Editor (Early Access)"
|
||||
|
||||
[pdfTextEditorV2]
|
||||
confirmReplaceDirty = "You have unsaved changes. Replace the open document and discard them?"
|
||||
save = "Save PDF"
|
||||
saveTooltip = "Download edited PDF (Ctrl+S)"
|
||||
title = "PDF Text Editor"
|
||||
workbenchLabel = "Editor"
|
||||
|
||||
[pdfTextEditorV2.drop]
|
||||
hint = "Releases on the editor stage replace any open document."
|
||||
title = "Drop a PDF to open"
|
||||
|
||||
[pdfTextEditorV2.error]
|
||||
decodeImage = "Could not decode the selected image."
|
||||
insertImage = "Could not insert the selected image."
|
||||
|
||||
[pdfTextEditorV2.find]
|
||||
close = "Close find bar"
|
||||
count = "{{current}} of {{total}}"
|
||||
findPlaceholder = "Find"
|
||||
next = "Next match"
|
||||
noMatches = "No matches"
|
||||
previous = "Previous match"
|
||||
replace = "Replace"
|
||||
replaceAll = "Replace all"
|
||||
replaced = " · {{count}} replaced"
|
||||
replacePlaceholder = "Replace with"
|
||||
title = "Find & replace"
|
||||
typeToSearch = "Type to search"
|
||||
|
||||
[pdfTextEditorV2.fonts]
|
||||
allPresent = "All letters & numbers present"
|
||||
missing = "Missing: {{glyphs}}"
|
||||
missingTooltip = "This font has no glyph for: {{glyphs}}. Typing one uses a standard fallback font."
|
||||
title = "Fonts"
|
||||
|
||||
[pdfTextEditorV2.fonts.compat]
|
||||
info = "Existing text edits perfectly. A new character an embedded font doesn't include falls back to a standard font."
|
||||
ok = "Every font includes the full alphabet and digits - type freely."
|
||||
warnOne = "{{count}} font missing some letters or numbers - typing those uses a standard fallback font."
|
||||
warnOther = "{{count}} fonts missing some letters or numbers - typing those uses a standard fallback font."
|
||||
|
||||
[pdfTextEditorV2.fonts.help]
|
||||
ariaLabel = "What do the font statuses mean?"
|
||||
embeddedDesc = "full font shipped in the PDF - most new characters match; a glyph the font lacks falls back."
|
||||
existingBody = "always edits in its original font."
|
||||
existingLabel = "Existing text"
|
||||
heading = "How fonts affect editing"
|
||||
newBody = "you type keep the original font only when that font includes them - otherwise they fall back to a standard font (Helvetica)."
|
||||
newLabel = "New characters"
|
||||
standardDesc = "base-14 PDF font - the full standard character set is always available."
|
||||
subsetDesc = "only the document's existing characters are embedded - new ones usually fall back."
|
||||
|
||||
[pdfTextEditorV2.fonts.status.embedded]
|
||||
hint = "Full font embedded in the PDF. Existing text edits perfectly. New characters render in this font when it includes them - any it lacks (e.g. an accent or symbol the font never carried) fall back to a standard font."
|
||||
label = "Embedded"
|
||||
|
||||
[pdfTextEditorV2.fonts.status.standard]
|
||||
hint = "Standard PDF font (Helvetica / Times / Courier family). The full standard character set is always available, so existing text AND new characters render in this font."
|
||||
label = "Standard"
|
||||
|
||||
[pdfTextEditorV2.fonts.status.subset]
|
||||
hint = "Only the characters the document already uses are embedded. Existing text edits fine, but a new character the document never used will usually fall back to a standard font."
|
||||
label = "Subset"
|
||||
|
||||
[pdfTextEditorV2.help]
|
||||
ariaLabel = "Keyboard shortcuts"
|
||||
title = "Keyboard shortcuts"
|
||||
tooltip = "Keyboard shortcuts (?)"
|
||||
|
||||
[pdfTextEditorV2.help.arrangement]
|
||||
alignDesc = "Align edges L / centre / R / T / mid / B"
|
||||
alignKey = "Toolbar align"
|
||||
distributeDesc = "Equal horizontal / vertical spacing (3+)"
|
||||
distributeKey = "Toolbar distribute"
|
||||
frontBackDesc = "Bring to front / send to back"
|
||||
frontBackKey = "Toolbar front/back"
|
||||
heading = "Object arrangement"
|
||||
lockDesc = "Lock / unlock selection (session-only)"
|
||||
lockKey = "Lock button"
|
||||
orderDesc = "Bring forward / send backward (one step)"
|
||||
orderKey = "Toolbar ↑ ↓"
|
||||
|
||||
[pdfTextEditorV2.help.clipboard]
|
||||
copyDesc = "Copy selected text"
|
||||
copyKey = "Ctrl+C"
|
||||
cutDesc = "Cut selected (copy + delete)"
|
||||
cutKey = "Ctrl+X"
|
||||
heading = "Clipboard"
|
||||
pasteDesc = "Paste clipboard text as new run"
|
||||
pasteKey = "Ctrl+V"
|
||||
pastePlainDesc = "Paste as plain text"
|
||||
pastePlainKey = "Ctrl+Shift+V"
|
||||
|
||||
[pdfTextEditorV2.help.document]
|
||||
escDesc = "Clear selection / close find / close help"
|
||||
escKey = "Esc"
|
||||
heading = "Document"
|
||||
helpDesc = "This help"
|
||||
helpKey = "? / F1"
|
||||
saveDesc = "Download edited PDF"
|
||||
saveKey = "Ctrl+S"
|
||||
|
||||
[pdfTextEditorV2.help.editing]
|
||||
clickDesc = "Edit text"
|
||||
clickKey = "Click"
|
||||
deleteDesc = "Remove selected"
|
||||
deleteKey = "Delete"
|
||||
duplicateDesc = "Duplicate selected"
|
||||
duplicateKey = "Ctrl+D"
|
||||
groupDesc = "Group selected runs (Group button)"
|
||||
groupKey = "Ctrl+M"
|
||||
heading = "Editing"
|
||||
marqueeDesc = "Marquee multi-select"
|
||||
marqueeKey = "Ctrl+Shift+drag"
|
||||
moveDesc = "Move text run"
|
||||
moveKey = "Ctrl+Click + drag"
|
||||
selectAllDesc = "Select all"
|
||||
selectAllKey = "Ctrl+A"
|
||||
shiftClickDesc = "Add / remove a run from selection"
|
||||
shiftClickKey = "Shift+Click"
|
||||
undoRedoDesc = "Undo / Redo"
|
||||
undoRedoKey = "Ctrl+Z / Ctrl+Y"
|
||||
ungroupDesc = "Ungroup paragraph: select it, click Ungroup"
|
||||
ungroupKey = "-"
|
||||
|
||||
[pdfTextEditorV2.help.find]
|
||||
enterFindDesc = "Next match"
|
||||
enterFindKey = "Enter (in find)"
|
||||
enterReplaceDesc = "Replace one (Shift = Replace All)"
|
||||
enterReplaceKey = "Enter (in replace)"
|
||||
heading = "Find & Replace"
|
||||
nextDesc = "Next match (Shift = previous)"
|
||||
nextKey = "F3 / Ctrl+G"
|
||||
openDesc = "Open find bar (and replace)"
|
||||
openKey = "Ctrl+F"
|
||||
|
||||
[pdfTextEditorV2.help.formatting]
|
||||
boldItalicDesc = "Bold / italic"
|
||||
boldItalicKey = "Toolbar B / I"
|
||||
caseDesc = "Change case (upper/lower/title/sentence)"
|
||||
caseKey = "Toolbar case (Aa)"
|
||||
colourDesc = "Change fill colour"
|
||||
colourKey = "Toolbar colour"
|
||||
fontFamilyDesc = "Swap to base-14 font"
|
||||
fontFamilyKey = "Toolbar font family"
|
||||
fontSizeDesc = "Change font size"
|
||||
fontSizeKey = "Toolbar font size"
|
||||
heading = "Text formatting"
|
||||
|
||||
[pdfTextEditorV2.help.image]
|
||||
flipDesc = "Flip horizontally or vertically"
|
||||
flipKey = "Toolbar flip"
|
||||
heading = "Image"
|
||||
moveDesc = "Move image"
|
||||
moveKey = "Drag"
|
||||
resizeDesc = "Resize image"
|
||||
resizeKey = "Corner drag"
|
||||
rotateDesc = "Rotate 90° clockwise or counter-clockwise"
|
||||
rotateKey = "Toolbar rotate"
|
||||
|
||||
[pdfTextEditorV2.help.navigation]
|
||||
firstLastDesc = "First / last page"
|
||||
firstLastKey = "Ctrl+Home / Ctrl+End"
|
||||
heading = "Navigation"
|
||||
pageDesc = "Next / previous page"
|
||||
pageKey = "PageDown / PageUp"
|
||||
toolbarZoomDesc = "Manual zoom + Fit to width"
|
||||
toolbarZoomKey = "Toolbar zoom"
|
||||
zoomDesc = "Zoom in / out"
|
||||
zoomKey = "Ctrl+Wheel"
|
||||
|
||||
[pdfTextEditorV2.password]
|
||||
cancel = "Cancel"
|
||||
incorrect = "Incorrect password - try again."
|
||||
label = "Password"
|
||||
open = "Open"
|
||||
protected = "This PDF is password-protected."
|
||||
protectedNamed = "\"{{fileName}}\" is password-protected."
|
||||
title = "Password required"
|
||||
|
||||
[pdfTextEditorV2.run]
|
||||
lockedTitle = "Locked - use the Unlock button to edit"
|
||||
|
||||
[pdfTextEditorV2.saveRisk]
|
||||
cancel = "Cancel"
|
||||
downloadAnyway = "Download anyway"
|
||||
intro = "Downloading the edited copy rewrites the whole file. That means:"
|
||||
note = "Your edits are kept. The changes listed above are unavoidable when downloading the edited copy."
|
||||
title = "Saving will change this PDF"
|
||||
|
||||
[pdfTextEditorV2.sidebar]
|
||||
addImage = "Add image"
|
||||
addText = "Add text"
|
||||
clickPageToAddText = "Click page to add text"
|
||||
editorSettings = "Editor settings"
|
||||
group = "Group"
|
||||
groupingAuto = "Auto"
|
||||
groupingAutoHint = "Equal-spaced lines group into editable paragraphs."
|
||||
groupingLine = "Line"
|
||||
groupingLineHint = "Each source line is edited on its own. Switching clears undo history."
|
||||
groupTooltip = "Merge selected runs into one paragraph (Ctrl+M)"
|
||||
groupTooltipDisabled = "Select 2+ runs to merge"
|
||||
imageSelectedOne = "{{count}} image selected"
|
||||
imageSelectedOther = "{{count}} images selected"
|
||||
insert = "Insert"
|
||||
moveTipPrefix = "Hold "
|
||||
moveTipSuffix = " and drag a text box to move it."
|
||||
noFile = "No file loaded"
|
||||
noFileHint = "Pick a PDF from the Files panel on the left, or drop one in. The editor will open it automatically."
|
||||
opening = "Opening document..."
|
||||
paragraph = "Paragraph"
|
||||
runSelectedOne = "{{count}} text run selected"
|
||||
runSelectedOther = "{{count}} text runs selected"
|
||||
textBoxWidth = "Text box width"
|
||||
textGrouping = "Text grouping"
|
||||
ungroup = "Ungroup"
|
||||
ungroupTooltip = "Split this paragraph into one run per line"
|
||||
ungroupTooltipDisabled = "Select a multi-line paragraph to ungroup"
|
||||
widthGrow = "Grow"
|
||||
widthGrowHint = "Boxes widen to the right as you type (no wrapping)."
|
||||
widthWrap = "Wrap"
|
||||
widthWrapHint = "Boxes keep their width; extra text wraps onto new lines."
|
||||
|
||||
[pdfTextEditorV2.stage]
|
||||
loadingDocument = "Loading document"
|
||||
loadingProgress = "Loading progress"
|
||||
noDocument = "No document loaded."
|
||||
pickPrompt = "Pick a PDF from the Files panel on the left to begin editing."
|
||||
renderingPreview = "Rendering preview"
|
||||
|
||||
[pdfTextEditorV2.toolbar]
|
||||
alignBottom = "Align bottom"
|
||||
alignCentre = "Align centre"
|
||||
alignLabel = "Align · needs 2+ objects"
|
||||
alignLeft = "Align left"
|
||||
alignMiddle = "Align middle"
|
||||
alignRight = "Align right"
|
||||
alignTop = "Align top"
|
||||
arrange = "Arrange"
|
||||
bold = "Bold"
|
||||
bringForward = "Bring forward"
|
||||
bringToFront = "Bring to front"
|
||||
caseLower = "lowercase"
|
||||
caseSentence = "Sentence case"
|
||||
caseTitle = "Title Case"
|
||||
caseUpper = "UPPERCASE"
|
||||
changeCase = "Change case"
|
||||
changeCaseTooltip = "Change case (text runs only)"
|
||||
delete = "Delete selected"
|
||||
deleteTooltip = "Delete (Del)"
|
||||
distributeHorizontally = "Distribute horizontally"
|
||||
distributeLabel = "Distribute · needs 3+ objects"
|
||||
distributeVertically = "Distribute vertically"
|
||||
flipHorizontal = "Flip horizontal"
|
||||
flipVertical = "Flip vertical"
|
||||
fontColour = "Font colour"
|
||||
fontFamily = "Font family"
|
||||
fontSize = "Font size"
|
||||
image = "Image"
|
||||
italic = "Italic"
|
||||
lock = "Lock selection"
|
||||
lockTooltip = "Lock selection - prevents accidental edits"
|
||||
order = "Order"
|
||||
redo = "Redo"
|
||||
redoTooltip = "Redo (Ctrl+Y)"
|
||||
rotateLeft = "Rotate 90° left"
|
||||
rotateRight = "Rotate 90° right"
|
||||
selectImageFirst = "Select an image first"
|
||||
sendBackward = "Send backward"
|
||||
sendToBack = "Send to back"
|
||||
undo = "Undo"
|
||||
undoTooltip = "Undo (Ctrl+Z)"
|
||||
unlock = "Unlock selection"
|
||||
unlockTooltip = "Unlock selection - makes it editable again"
|
||||
|
||||
[pdfTextEditorV2.zoom]
|
||||
fit = "Fit"
|
||||
fitToWidth = "Fit to width"
|
||||
in = "Zoom in"
|
||||
out = "Zoom out"
|
||||
reset = "Reset zoom"
|
||||
|
||||
[PDFToCSV]
|
||||
header = "PDF to CSV"
|
||||
title = "PDF to CSV"
|
||||
@@ -6522,6 +6240,10 @@ muted = "muted"
|
||||
nameLabel = "Name"
|
||||
namePlaceholder = "e.g. Compliance escalation"
|
||||
|
||||
[portal.agentBuilder.status]
|
||||
draft = "Draft"
|
||||
published = "Published"
|
||||
|
||||
[portal.agentBuilder.tabs]
|
||||
evals = "Evals"
|
||||
scenarios = "Scenarios"
|
||||
@@ -6745,7 +6467,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]
|
||||
@@ -6812,6 +6534,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"
|
||||
@@ -7200,31 +6951,31 @@ subtitle = "Deployments, credentials, security posture, storage, and the audit t
|
||||
title = "Infrastructure"
|
||||
|
||||
# Fixed-enum label maps rendered via t(MAP[value]) in the infrastructure tabs.
|
||||
[portal.infrastructure.apiKeyPermission]
|
||||
admin = "Admin"
|
||||
read = "Read"
|
||||
write = "Write"
|
||||
|
||||
[portal.infrastructure.apiKeys]
|
||||
createKey = "Create key"
|
||||
heading = "API keys"
|
||||
subheading = "Scoped credentials with per-key rate limits, permissions, and IP allowlists."
|
||||
subheading = "Personal credentials, each with its own usage tracking."
|
||||
|
||||
[portal.infrastructure.apiKeys.card]
|
||||
allowedIps = "Allowed IPs"
|
||||
anyIp = "Any IP (no allowlist)"
|
||||
created = "Created"
|
||||
lastUsed = "Last used"
|
||||
permissions = "Permissions"
|
||||
rateLimit = "Rate limit"
|
||||
rateLimitValue = "{{value}} req/min"
|
||||
revoke = "Revoke key"
|
||||
usageMonth = "Usage this month"
|
||||
usageToday = "Usage today"
|
||||
|
||||
[portal.infrastructure.apiKeys.empty]
|
||||
description = "Create a scoped key to start calling the Stirling API."
|
||||
description = "Create a key to start calling the Stirling API."
|
||||
title = "No API keys yet"
|
||||
|
||||
[portal.infrastructure.apiKeys.error]
|
||||
load = "Couldn't load your API keys. Please try again."
|
||||
|
||||
[portal.infrastructure.apiKeys.revoke]
|
||||
body = "Revoke \"{{name}}\"? Any integration still using this key will immediately start receiving 401 errors. This can't be undone."
|
||||
cancel = "Cancel"
|
||||
confirm = "Revoke key"
|
||||
title = "Revoke API key"
|
||||
|
||||
[portal.infrastructure.attestationLabel]
|
||||
attested = "Attested"
|
||||
inScope = "In scope"
|
||||
@@ -7310,14 +7061,11 @@ notStarted = "Not started"
|
||||
cancel = "Cancel"
|
||||
createKey = "Create key"
|
||||
done = "Done"
|
||||
ipAllowlistHelper = "Comma-separated CIDR ranges. Leave blank to allow any IP."
|
||||
ipAllowlistLabel = "IP allowlist"
|
||||
keyNameLabel = "Key name"
|
||||
keyNamePlaceholder = "e.g. Production · ingest"
|
||||
permissionsLabel = "Permissions"
|
||||
keyNamePlaceholder = "e.g. Production ingest"
|
||||
secretKeyCaption = "Secret key"
|
||||
secretWarning = "Store this in a secrets manager. Stirling only ever stores a hash — there is no way to recover it later."
|
||||
subtitle = "Scope the key to the minimum it needs. You can rotate or revoke at any time."
|
||||
secretWarning = "Store this in a secrets manager. Stirling only ever stores a hash, so there is no way to recover it later."
|
||||
subtitle = "Give the key a name so you can recognise it later. You can revoke it at any time."
|
||||
subtitleCreated = "Copy this secret now — it won't be shown again."
|
||||
title = "Create API key"
|
||||
titleCreated = "Key created"
|
||||
@@ -7366,7 +7114,6 @@ title = "No regions deployed"
|
||||
[portal.infrastructure.keyLabel]
|
||||
active = "Active"
|
||||
revoked = "Revoked"
|
||||
rotateSoon = "Rotate soon"
|
||||
|
||||
[portal.infrastructure.modelLabel]
|
||||
active = "Active"
|
||||
@@ -7623,10 +7370,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"
|
||||
@@ -7697,6 +7440,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"
|
||||
|
||||
@@ -8268,12 +8012,23 @@ 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"
|
||||
createApiKey = "Create API key"
|
||||
|
||||
[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."
|
||||
@@ -8281,21 +8036,6 @@ 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"
|
||||
@@ -8311,10 +8051,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"
|
||||
@@ -8362,6 +8107,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"
|
||||
@@ -8391,21 +8140,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"
|
||||
@@ -10421,6 +10163,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"
|
||||
@@ -10491,7 +10246,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",
|
||||
|
||||
@@ -399,22 +399,14 @@ export default function WorkbenchBar({
|
||||
);
|
||||
|
||||
// View options
|
||||
// Tools that own a custom workbench (e.g. the v2 PDF text editor) ship
|
||||
// their own canvas; the generic Viewer tab is redundant noise while
|
||||
// those tools are active. Hide it for those tools.
|
||||
const ownsCustomWorkbenchAsDefault = selectedTool === "pdfTextEditor";
|
||||
const viewOptions: ViewOption[] = [
|
||||
...(ownsCustomWorkbenchAsDefault
|
||||
? []
|
||||
: [
|
||||
{
|
||||
value: "viewer" as WorkbenchType,
|
||||
label: t("workbenchBar.viewer", "Viewer"),
|
||||
icon: <InsertDriveFileOutlinedIcon fontSize="small" />,
|
||||
},
|
||||
]),
|
||||
{
|
||||
value: "fileEditor" as WorkbenchType,
|
||||
value: "viewer",
|
||||
label: t("workbenchBar.viewer", "Viewer"),
|
||||
icon: <InsertDriveFileOutlinedIcon fontSize="small" />,
|
||||
},
|
||||
{
|
||||
value: "fileEditor",
|
||||
label: t("workbenchBar.activeFiles", "Active Files"),
|
||||
icon: <FolderOutlinedIcon fontSize="small" />,
|
||||
},
|
||||
|
||||
@@ -93,9 +93,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
|
||||
/>
|
||||
),
|
||||
name: t("home.pdfTextEditor.title", "PDF Text Editor"),
|
||||
component: lazy(
|
||||
() => import("@app/tools/pdfTextEditor/v2/PdfTextEditorV2"),
|
||||
),
|
||||
component: lazy(() => import("@app/tools/pdfTextEditor/PdfTextEditor")),
|
||||
description: t(
|
||||
"home.pdfTextEditor.desc",
|
||||
"Review and edit text and images in PDFs with grouped text editing and PDF regeneration",
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -289,43 +289,6 @@ function copyToWasmHeap(
|
||||
(m.pdfium as typeof m.pdfium & ExtendedPdfiumRuntime).HEAPU8.set(bytes, ptr);
|
||||
}
|
||||
|
||||
/** Human-readable message for an FPDF_GetLastError() code. */
|
||||
function pdfiumOpenErrorMessage(err: number): string {
|
||||
switch (err) {
|
||||
case 1:
|
||||
return "Could not open the PDF (unknown error).";
|
||||
case 2:
|
||||
return "This file is not a valid PDF or is corrupted.";
|
||||
case 3:
|
||||
return "The PDF file is corrupted and could not be read.";
|
||||
case 4:
|
||||
return "This PDF is password-protected.";
|
||||
case 5:
|
||||
return "This PDF uses an unsupported security scheme.";
|
||||
case 6:
|
||||
return "A page in this PDF could not be loaded.";
|
||||
default:
|
||||
return `Could not open the PDF (error ${err}).`;
|
||||
}
|
||||
}
|
||||
|
||||
/** FPDF_GetLastError() code for a missing/incorrect document password. */
|
||||
export const FPDF_ERR_PASSWORD = 4;
|
||||
|
||||
/**
|
||||
* Open failure carrying the raw FPDF_GetLastError() code so callers can tell a
|
||||
* password prompt (code 4) apart from a corrupt file. Still an `Error`, so
|
||||
* existing `instanceof Error` handlers keep working.
|
||||
*/
|
||||
export class PdfiumOpenError extends Error {
|
||||
readonly code: number;
|
||||
constructor(code: number) {
|
||||
super(pdfiumOpenErrorMessage(code));
|
||||
this.name = "PdfiumOpenError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a PDF into PDFium memory and return the document pointer.
|
||||
* Caller MUST call `closeRawDocument(docPtr)` when finished.
|
||||
@@ -343,7 +306,8 @@ export async function openRawDocument(
|
||||
const docPtr = m.FPDF_LoadMemDocument(ptr, len, password ?? "");
|
||||
if (!docPtr) {
|
||||
m.pdfium.wasmExports.free(ptr);
|
||||
throw new PdfiumOpenError(m.FPDF_GetLastError());
|
||||
const err = m.FPDF_GetLastError();
|
||||
throw new Error(`PDFium: failed to open document (error ${err})`);
|
||||
}
|
||||
// Keep the buffer alive — freed in closeRawDocument()
|
||||
_docDataPtrs.set(docPtr, ptr);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/test-base";
|
||||
import { loginAndSetup } from "@app/tests/helpers/login";
|
||||
import * as path from "path";
|
||||
import * as fs from "fs";
|
||||
|
||||
/**
|
||||
* In dev environments where the Stirling backend ships with login
|
||||
* disabled (anonymous-mode), `loginAndSetup` will throw because /login
|
||||
* doesn't render. Detect that and silently skip the call. Live CI
|
||||
* still hits the real login flow (login enabled in the CI backend
|
||||
* profile), so this conditional only takes effect when running the
|
||||
* suite against a no-auth dev backend.
|
||||
*/
|
||||
async function loginIfNeeded(
|
||||
page: import("@playwright/test").Page,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await loginAndSetup(page);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (/email|login/i.test(msg)) {
|
||||
// anonymous-mode backend - nothing to log in to.
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Live e2e coverage for the v2 PDF text editor's `backend` charcode
|
||||
* strategy.
|
||||
*
|
||||
* Unlike the `stubbed` suite, these tests hit the REAL Spring backend
|
||||
* (`/api/v1/general/pdf-text-editor-v2/encode-charcodes`) via PDFBox.
|
||||
* Sample.pdf is the standout repro: every glyph is a per-char Type3
|
||||
* font where naive Helvetica fallback renders "M" as the wrong glyph
|
||||
* shape. The backend's ToUnicode-reverse-CMap lookup resolves each
|
||||
* char to its native font + charcode, the frontend's per-char emit
|
||||
* branch creates one text object per char with the correct font
|
||||
* handle + SetCharcodes(charcode), and the result visually matches
|
||||
* the source text.
|
||||
*
|
||||
* The two things this suite guards against:
|
||||
* 1. Regression of the per-char emit branch (must fire on the
|
||||
* FIRST keystroke after focus, NOT the second - the prewarm in
|
||||
* TextRunOverlay.onFocus exists precisely to eliminate the
|
||||
* old 2-attempt UX).
|
||||
* 2. Wrong charcode being emitted (e.g. M → 0 / .notdef instead of
|
||||
* the real glyph index that PDFBox's ToUnicode reverse map
|
||||
* returns).
|
||||
*/
|
||||
|
||||
function fixture(filename: string): string {
|
||||
const candidates = [
|
||||
path.resolve(
|
||||
process.cwd(),
|
||||
"src",
|
||||
"core",
|
||||
"tests",
|
||||
"test-fixtures",
|
||||
filename,
|
||||
),
|
||||
path.resolve(
|
||||
process.cwd(),
|
||||
"frontend",
|
||||
"src",
|
||||
"core",
|
||||
"tests",
|
||||
"test-fixtures",
|
||||
filename,
|
||||
),
|
||||
];
|
||||
for (const p of candidates) {
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
throw new Error(
|
||||
`Test fixture not found: ${filename} (tried: ${candidates.join(", ")})`,
|
||||
);
|
||||
}
|
||||
|
||||
// `user-sample.pdf` is the same file as `frontend/editor/public/samples/Sample.pdf`,
|
||||
// copied into the test fixtures dir so this suite is self-contained.
|
||||
const USER_SAMPLE_PDF = fixture("user-sample.pdf");
|
||||
|
||||
async function gotoEditorWithBackendStrategy(
|
||||
page: import("@playwright/test").Page,
|
||||
): Promise<void> {
|
||||
// `charcodeDebug=1` enables the HUD overlay (CharcodeDebugHud) that
|
||||
// emits one row per attempt, which is what this test scrapes.
|
||||
await page.goto("/pdf-text-editor?charcodeStrategy=backend&charcodeDebug=1", {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function loadUserSamplePdf(
|
||||
page: import("@playwright/test").Page,
|
||||
): Promise<void> {
|
||||
await page
|
||||
.locator('[data-testid="v2-file-input"]')
|
||||
.setInputFiles(USER_SAMPLE_PDF);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 60_000 });
|
||||
}
|
||||
|
||||
test.describe("v2 charcode backend strategy (live PDFBox)", () => {
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await loginIfNeeded(page);
|
||||
});
|
||||
|
||||
test("Sample.pdf 10M+: typing M into the per-glyph Type3 font emits charcodes-ok on the FIRST keystroke", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoEditorWithBackendStrategy(page);
|
||||
await loadUserSamplePdf(page);
|
||||
|
||||
// Find the 10M+ run.
|
||||
const runEl = page
|
||||
.locator('[data-testid^="v2-run-p"]')
|
||||
.filter({ hasText: /^10M\+$/ })
|
||||
.first();
|
||||
await expect(runEl).toBeVisible({ timeout: 15_000 });
|
||||
const runTestId = (await runEl.getAttribute("data-testid")) ?? "";
|
||||
expect(runTestId).toMatch(/^v2-run-p\d+-/);
|
||||
|
||||
// Listen for the prewarm-complete console.debug log BEFORE we
|
||||
// focus the run, so we don't race the message.
|
||||
// Match either of:
|
||||
// "backend prewarm pageIdx=0 probes=N" - the completion log
|
||||
// "backend prewarm pageIdx=0 probes=0 (already-prewarmed)" -
|
||||
// cached from a prior test, treat as complete
|
||||
// The prewarm-START log ("prewarm-start pageIdx=") confirms that
|
||||
// the focus actually triggered the lazy-import path even on the
|
||||
// early-return branches.
|
||||
const prewarmComplete = page.waitForEvent("console", {
|
||||
predicate: (msg) =>
|
||||
/\[v2\.charcode\] backend prewarm pageIdx=/.test(msg.text()),
|
||||
timeout: 90_000,
|
||||
});
|
||||
|
||||
// Surface ALL console messages to the test stdout so we can see
|
||||
// what's happening if the prewarm log doesn't fire. Wrapping
|
||||
// page.on now means messages from before THIS line are missed,
|
||||
// but the prewarm fires after focus (below) so we catch it.
|
||||
page.on("console", (msg) => {
|
||||
if (/v2\.charcode|prewarm/.test(msg.text())) {
|
||||
process.stdout.write(`[page-console-${msg.type()}] ${msg.text()}\n`);
|
||||
}
|
||||
});
|
||||
|
||||
// Use Playwright's physical click - that dispatches real
|
||||
// mousedown/up/click + focus events that React's synthetic
|
||||
// event system catches reliably. Calling el.focus() from
|
||||
// page.evaluate works for native DOM focus but can race React's
|
||||
// focus delegation in unmount/mount transitions.
|
||||
await runEl.click();
|
||||
|
||||
// Wait for prewarm to log "[v2.charcode] backend prewarm pageIdx=
|
||||
// probes=N". After this fires the per-char cache for the page is
|
||||
// populated and the next keystroke hits charcodes-ok on the FIRST
|
||||
// try.
|
||||
await prewarmComplete;
|
||||
|
||||
// First keystroke: should hit the per-char emit branch on the
|
||||
// FIRST try (no Helvetica fallback). Use execCommand("insertText")
|
||||
// because Playwright's keyboard.type on contenteditable can
|
||||
// occasionally route through synthetic key events that the
|
||||
// editor's onInput debounce drops.
|
||||
await page.evaluate((tid) => {
|
||||
const el = document.querySelector<HTMLDivElement>(
|
||||
`[data-testid="${tid}"]`,
|
||||
);
|
||||
if (!el) throw new Error(`run ${tid} not in DOM`);
|
||||
el.focus();
|
||||
const sel = window.getSelection();
|
||||
if (!sel) throw new Error("no Selection api");
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand("insertText", false, "M");
|
||||
}, runTestId);
|
||||
|
||||
// The debug HUD was removed from production builds, so verify the emit
|
||||
// through the window-exposed telemetry buffer instead (charcodeRegistry
|
||||
// mirrors recent CharcodeEvents onto window.__v2_charcode_events for
|
||||
// exactly this purpose). Poll for a charcodes-ok event covering the
|
||||
// typed "M": robust to whether prewarm beat the keystroke (1-attempt)
|
||||
// or the resolver's auto-prefetch retried slightly after.
|
||||
type CharcodeEmitEvent = {
|
||||
text: string;
|
||||
outcome: string;
|
||||
resolved: number[];
|
||||
};
|
||||
const readCharcodeEvents = () =>
|
||||
page.evaluate(
|
||||
() =>
|
||||
(
|
||||
window as unknown as {
|
||||
__v2_charcode_events?: CharcodeEmitEvent[];
|
||||
}
|
||||
).__v2_charcode_events ?? [],
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const events = await readCharcodeEvents();
|
||||
return events.some(
|
||||
(e) =>
|
||||
e.text.includes("M") &&
|
||||
e.outcome === "charcodes-ok" &&
|
||||
e.resolved.length > 0,
|
||||
);
|
||||
},
|
||||
{ timeout: 10_000, intervals: [250, 500, 1000] },
|
||||
)
|
||||
.toBe(true);
|
||||
|
||||
// Cross-check: the editor's model must reflect "10M+M" - the
|
||||
// typed M became a real text run via the per-char emit branch.
|
||||
const runText = await page.evaluate((tid) => {
|
||||
const w = window as unknown as {
|
||||
__v2_editor_store: {
|
||||
state: { pages: { runs: { id: string; text: string }[] }[] };
|
||||
};
|
||||
};
|
||||
for (const p of w.__v2_editor_store.state.pages) {
|
||||
for (const r of p.runs) {
|
||||
if (`v2-run-${r.id}` === tid) return r.text;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}, runTestId);
|
||||
expect(runText).toBe("10M+M");
|
||||
|
||||
// No-regression guard: the MOST RECENT emit covering "M" must be a
|
||||
// source-font charcodes-ok emit, NOT a Helvetica fallback. This is
|
||||
// the "first-keystroke-must-work" assertion.
|
||||
const events = await readCharcodeEvents();
|
||||
const mEvents = events.filter((e) => e.text.includes("M"));
|
||||
const lastM = mEvents[mEvents.length - 1];
|
||||
expect(
|
||||
lastM?.outcome,
|
||||
`latest M emit must be charcodes-ok. Events:\n${JSON.stringify(events, null, 2)}`,
|
||||
).toBe("charcodes-ok");
|
||||
});
|
||||
});
|
||||
@@ -1,870 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import type { Page } from "@playwright/test";
|
||||
import path from "path";
|
||||
import type {
|
||||
V2Matrix,
|
||||
V2TestWindow,
|
||||
} from "@app/tests/stubbed/v2EditorTestTypes";
|
||||
|
||||
/**
|
||||
* Combined-feature regression suite: the new editor features (image
|
||||
* rotate/flip, z-order, align/distribute, lock, change-case, cut/paste,
|
||||
* find+replace) AND their interaction with the 12 bug fixes. Page-level
|
||||
* operations (page rotate/print/reset) are intentionally absent.
|
||||
*/
|
||||
const SAMPLE = path.join(
|
||||
import.meta.dirname,
|
||||
"../../../../public/samples/Sample.pdf",
|
||||
);
|
||||
const PNG = path.join(import.meta.dirname, "../test-fixtures/sample.png");
|
||||
|
||||
// z-order / align / distribute live in the toolbar's "Arrange" menu, and
|
||||
// image rotate/flip in the "Image" menu. Open the menu, then click the item.
|
||||
async function clickArrange(page: Page, testid: string): Promise<void> {
|
||||
await page.getByTestId("v2-arrange-menu").click();
|
||||
await page.getByTestId(testid).click();
|
||||
}
|
||||
async function clickImage(page: Page, testid: string): Promise<void> {
|
||||
await page.getByTestId("v2-imgop-menu").click();
|
||||
await page.getByTestId(testid).click();
|
||||
}
|
||||
|
||||
async function open(page: Page, firstPage = 0): Promise<void> {
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
|
||||
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE);
|
||||
await expect(page.getByTestId(`v2-page-${firstPage}`)).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await page.waitForTimeout(900);
|
||||
}
|
||||
async function runId(
|
||||
page: Page,
|
||||
pageIdx: number,
|
||||
src: string,
|
||||
): Promise<string> {
|
||||
const id = await page.evaluate(
|
||||
({ pageIdx, src }: { pageIdx: number; src: string }) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
const r = s.doc
|
||||
.page(pageIdx)
|
||||
.runs.find((x) => new RegExp(src).test(x.text));
|
||||
return r ? r.id : null;
|
||||
},
|
||||
{ pageIdx, src },
|
||||
);
|
||||
if (!id) throw new Error(`run /${src}/ not found`);
|
||||
return id;
|
||||
}
|
||||
async function selectRun(page: Page, id: string): Promise<void> {
|
||||
await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.selection.selectOne(
|
||||
rid,
|
||||
),
|
||||
id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
}
|
||||
async function selectMany(page: Page, ids: string[]): Promise<void> {
|
||||
await page.evaluate(
|
||||
(rids: string[]) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectMany(rids),
|
||||
ids,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
}
|
||||
async function runText(
|
||||
page: Page,
|
||||
pageIdx: number,
|
||||
id: string,
|
||||
): Promise<string> {
|
||||
return page.evaluate(
|
||||
({ pageIdx, id }: { pageIdx: number; id: string }) => {
|
||||
const r = (window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(pageIdx)
|
||||
.runs.find((x) => x.id === id);
|
||||
return r ? (r.text as string) : "(gone)";
|
||||
},
|
||||
{ pageIdx, id },
|
||||
);
|
||||
}
|
||||
async function insertImage(
|
||||
page: Page,
|
||||
): Promise<{ id: string; matrix: V2Matrix } | null> {
|
||||
await page.locator('[data-testid="v2-image-input"]').setInputFiles(PNG);
|
||||
await page.waitForTimeout(1200);
|
||||
return page.evaluate(() => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
for (const p of s.doc.loadedPages()) {
|
||||
if (p.images.length > 0) {
|
||||
const img = p.images[p.images.length - 1];
|
||||
return { id: img.id, matrix: { ...img.matrix } };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
async function imageMatrix(
|
||||
page: Page,
|
||||
imageId: string,
|
||||
): Promise<V2Matrix | null> {
|
||||
return page.evaluate((iid: string) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
for (const p of s.doc.loadedPages()) {
|
||||
const img = p.images.find((x) => x.id === iid);
|
||||
if (img) return { ...img.matrix };
|
||||
}
|
||||
return null;
|
||||
}, imageId);
|
||||
}
|
||||
async function totalRuns(page: Page): Promise<number> {
|
||||
return page.evaluate(() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.loadedPages()
|
||||
.reduce((n: number, p) => n + p.runs.length, 0),
|
||||
);
|
||||
}
|
||||
async function countRunsContaining(page: Page, sub: string): Promise<number> {
|
||||
return page.evaluate((sub: string) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
const needle = sub.toLowerCase();
|
||||
let n = 0;
|
||||
for (const p of s.doc.loadedPages())
|
||||
for (const r of p.runs) if (r.text.toLowerCase().includes(needle)) n += 1;
|
||||
return n;
|
||||
}, sub);
|
||||
}
|
||||
async function firstRunIds(
|
||||
page: Page,
|
||||
pageIdx: number,
|
||||
n: number,
|
||||
): Promise<string[]> {
|
||||
return page.evaluate(
|
||||
({ pageIdx, n }: { pageIdx: number; n: number }) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(pageIdx)
|
||||
.runs.slice(0, n)
|
||||
.map((r) => r.id),
|
||||
{ pageIdx, n },
|
||||
);
|
||||
}
|
||||
async function undoSize(page: Page): Promise<number> {
|
||||
return page.evaluate(
|
||||
() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.history.size().undo,
|
||||
);
|
||||
}
|
||||
|
||||
test.describe("v2 editor - combined feature set", () => {
|
||||
// Editor edits fire encode-charcodes; with no backend an UNMOCKED call 401s
|
||||
// and redirects to login, unmounting the editor (the __v2_editor_store goes
|
||||
// undefined mid-test). Abort it so the resolver sees a clean cold-cache miss.
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route("**/encode-charcodes", (route) => route.abort());
|
||||
});
|
||||
|
||||
test("image insert (real png) adds an image, then rotate-cw changes its matrix and undo reverts", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins, "image insert must add an image").not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
await clickImage(page, "v2-imgop-rotate-cw");
|
||||
await page.waitForTimeout(300);
|
||||
const rotated = await imageMatrix(page, ins!.id);
|
||||
// A 90deg rotation swaps the axes: original diagonal (a,d) becomes off-diagonal (b,c).
|
||||
expect(
|
||||
Math.abs(rotated!.a) + Math.abs(rotated!.d),
|
||||
"rotate must move scale off the main diagonal",
|
||||
).toBeLessThan(Math.abs(rotated!.b) + Math.abs(rotated!.c) + 0.01);
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(300);
|
||||
const reverted = await imageMatrix(page, ins!.id);
|
||||
expect(reverted!.a).toBeCloseTo(ins!.matrix.a, 1);
|
||||
expect(reverted!.d).toBeCloseTo(ins!.matrix.d, 1);
|
||||
});
|
||||
|
||||
test("image flip-h mirrors the matrix and undo reverts", async ({ page }) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
await clickImage(page, "v2-imgop-flip-h");
|
||||
await page.waitForTimeout(300);
|
||||
const flipped = await imageMatrix(page, ins!.id);
|
||||
expect(Math.sign(flipped!.a), "flip-h negates horizontal scale").toBe(
|
||||
-Math.sign(ins!.matrix.a || 1),
|
||||
);
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(300);
|
||||
const reverted = await imageMatrix(page, ins!.id);
|
||||
expect(reverted!.a).toBeCloseTo(ins!.matrix.a, 1);
|
||||
});
|
||||
|
||||
test("change case UPPER then LOWER transforms the selected run's text", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const orig = await runText(page, 1, id);
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-change-case").click();
|
||||
await page.getByTestId("v2-change-case-upper").click();
|
||||
await page.waitForTimeout(400);
|
||||
const upper = await runText(page, 1, id);
|
||||
expect(upper).toBe(orig.toUpperCase());
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-change-case").click();
|
||||
await page.getByTestId("v2-change-case-lower").click();
|
||||
await page.waitForTimeout(400);
|
||||
const lower = await runText(page, 1, id);
|
||||
expect(lower).toBe(orig.toLowerCase());
|
||||
});
|
||||
|
||||
test("lock makes a run inert (no select on click); unlock restores it", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-toggle-lock").click();
|
||||
await page.waitForTimeout(200);
|
||||
const locked = await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.locked,
|
||||
id,
|
||||
);
|
||||
expect(locked, "run should be locked").toBe(true);
|
||||
// The overlay snapshot must refresh so the lock takes visible effect:
|
||||
// a locked run drops contentEditable and exposes data-locked.
|
||||
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
|
||||
"data-locked",
|
||||
"true",
|
||||
);
|
||||
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
|
||||
"contenteditable",
|
||||
"false",
|
||||
);
|
||||
// Clear selection, then clicking the locked run must NOT select it.
|
||||
await page.evaluate(() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.selection.clear(),
|
||||
);
|
||||
await page
|
||||
.getByTestId(`v2-run-${id}`)
|
||||
.click()
|
||||
.catch(() => {});
|
||||
await page.waitForTimeout(150);
|
||||
const selAfterClick = await page.evaluate(
|
||||
() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.selection.value
|
||||
.runIds.length,
|
||||
);
|
||||
expect(selAfterClick, "locked run must not be selectable by click").toBe(0);
|
||||
});
|
||||
|
||||
test("align-left makes selected runs share the same left x", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const a = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const b = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
await selectMany(page, [a, b]);
|
||||
await clickArrange(page, "v2-align-left");
|
||||
await page.waitForTimeout(300);
|
||||
const xs = await page.evaluate(
|
||||
({ a, b }: { a: string; b: string }) => {
|
||||
const pg = (
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.doc.page(1);
|
||||
const ra = pg.runs.find((x) => x.id === a)!;
|
||||
const rb = pg.runs.find((x) => x.id === b)!;
|
||||
return [ra.bounds.x, rb.bounds.x];
|
||||
},
|
||||
{ a, b },
|
||||
);
|
||||
expect(
|
||||
Math.abs(xs[0] - xs[1]),
|
||||
"aligned runs share a left edge",
|
||||
).toBeLessThan(1.5);
|
||||
});
|
||||
|
||||
test("cut (Ctrl+X) removes the run and paste (Ctrl+V) brings it back", async ({
|
||||
page,
|
||||
}) => {
|
||||
// Cut/paste round-trips through the real system clipboard; the headless
|
||||
// context blocks clipboard.read by default, so grant it explicitly.
|
||||
await page
|
||||
.context()
|
||||
.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const before = await totalRuns(page);
|
||||
await selectRun(page, id);
|
||||
// Cut is suppressed while focus is inside a contentEditable run (so the
|
||||
// browser's native cut wins there). The real editor-level cut path fires
|
||||
// from a marquee/store selection with focus outside any run - mirror that.
|
||||
await page.evaluate(() =>
|
||||
(document.activeElement as HTMLElement | null)?.blur(),
|
||||
);
|
||||
await page.keyboard.press("Control+x");
|
||||
await page.waitForTimeout(400);
|
||||
const afterCut = await totalRuns(page);
|
||||
expect(afterCut, "cut removes the run").toBeLessThan(before);
|
||||
await page.keyboard.press("Control+v");
|
||||
await page.waitForTimeout(600);
|
||||
const afterPaste = await totalRuns(page);
|
||||
expect(afterPaste, "paste re-adds a run").toBeGreaterThan(afterCut);
|
||||
});
|
||||
|
||||
test("z-order: bring-to-front on an inserted image applies and undoes cleanly", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
const undoBefore = await page.evaluate(
|
||||
() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.history.size()
|
||||
.undo,
|
||||
);
|
||||
await clickArrange(page, "v2-z-to-front");
|
||||
await page.waitForTimeout(300);
|
||||
const undoAfter = await page.evaluate(
|
||||
() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.history.size()
|
||||
.undo,
|
||||
);
|
||||
expect(undoAfter, "z-order is its own undo step").toBe(undoBefore + 1);
|
||||
// No crash + still one image present.
|
||||
const imgs = await page.evaluate(() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.loadedPages()
|
||||
.reduce((n: number, p) => n + p.images.length, 0),
|
||||
);
|
||||
expect(imgs).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("editing a run still preserves unedited paragraph lines (fix holds in combined build)", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const before = await page.evaluate(
|
||||
(rid: string) => [
|
||||
...(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.paragraphLeafPtrs,
|
||||
],
|
||||
id,
|
||||
);
|
||||
await page.evaluate((rid: string) => {
|
||||
const el = document.querySelector<HTMLDivElement>(
|
||||
`[data-testid="v2-run-${rid}"]`,
|
||||
)!;
|
||||
el.focus();
|
||||
const sel = window.getSelection()!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand("insertText", false, " APPENDED");
|
||||
}, id);
|
||||
await page.waitForTimeout(150);
|
||||
await page.evaluate(
|
||||
(rid: string) =>
|
||||
document
|
||||
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
|
||||
?.blur(),
|
||||
id,
|
||||
);
|
||||
await page.waitForTimeout(1200);
|
||||
const after = await page.evaluate((rid: string) => {
|
||||
const r = (window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid);
|
||||
return r ? [...r.paragraphLeafPtrs] : [];
|
||||
}, id);
|
||||
const kept = before.filter((p: number) => after.includes(p)).length;
|
||||
expect(
|
||||
kept,
|
||||
"most original glyph objects survive an append",
|
||||
).toBeGreaterThan(before.length * 0.6);
|
||||
const text = await runText(page, 1, id);
|
||||
expect(text).toContain("APPENDED");
|
||||
expect(text).not.toContain("ÿ");
|
||||
});
|
||||
|
||||
test("image rotate-ccw changes the matrix and undo reverts", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
await clickImage(page, "v2-imgop-rotate-ccw");
|
||||
await page.waitForTimeout(300);
|
||||
const rotated = await imageMatrix(page, ins!.id);
|
||||
expect(
|
||||
Math.abs(rotated!.a) + Math.abs(rotated!.d),
|
||||
"rotate moves scale off the main diagonal",
|
||||
).toBeLessThan(Math.abs(rotated!.b) + Math.abs(rotated!.c) + 0.01);
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(300);
|
||||
const reverted = await imageMatrix(page, ins!.id);
|
||||
expect(reverted!.a).toBeCloseTo(ins!.matrix.a, 1);
|
||||
expect(reverted!.d).toBeCloseTo(ins!.matrix.d, 1);
|
||||
});
|
||||
|
||||
test("image flip-v mirrors the vertical scale and undo reverts", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
await clickImage(page, "v2-imgop-flip-v");
|
||||
await page.waitForTimeout(300);
|
||||
const flipped = await imageMatrix(page, ins!.id);
|
||||
expect(Math.sign(flipped!.d), "flip-v negates vertical scale").toBe(
|
||||
-Math.sign(ins!.matrix.d || 1),
|
||||
);
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(300);
|
||||
const reverted = await imageMatrix(page, ins!.id);
|
||||
expect(reverted!.d).toBeCloseTo(ins!.matrix.d, 1);
|
||||
});
|
||||
|
||||
test("rotating an image four times clockwise returns to the original matrix", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
await clickImage(page, "v2-imgop-rotate-cw");
|
||||
await page.waitForTimeout(180);
|
||||
}
|
||||
const m = await imageMatrix(page, ins!.id);
|
||||
expect(m!.a).toBeCloseTo(ins!.matrix.a, 1);
|
||||
expect(m!.d).toBeCloseTo(ins!.matrix.d, 1);
|
||||
expect(Math.abs(m!.b), "no residual shear after full turn").toBeLessThan(
|
||||
0.01,
|
||||
);
|
||||
expect(Math.abs(m!.c), "no residual shear after full turn").toBeLessThan(
|
||||
0.01,
|
||||
);
|
||||
});
|
||||
|
||||
test("locking an image makes it inert; unlocking restores selectability", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
await page.getByTestId("v2-toggle-lock").click();
|
||||
await page.waitForTimeout(200);
|
||||
const locked = await page.evaluate((iid: string) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
for (const p of s.doc.loadedPages()) {
|
||||
const im = p.images.find((x) => x.id === iid);
|
||||
if (im) return im.locked;
|
||||
}
|
||||
return null;
|
||||
}, ins!.id);
|
||||
expect(locked, "image should be locked").toBe(true);
|
||||
// Snapshot must refresh so the handle reflects the lock.
|
||||
await expect(page.getByTestId(`v2-image-${ins!.id}`)).toHaveAttribute(
|
||||
"data-locked",
|
||||
"true",
|
||||
);
|
||||
// Clicking the locked image must not select it.
|
||||
await page.evaluate(() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.selection.clear(),
|
||||
);
|
||||
await page
|
||||
.getByTestId(`v2-image-${ins!.id}`)
|
||||
.click()
|
||||
.catch(() => {});
|
||||
await page.waitForTimeout(150);
|
||||
const selImgs = await page.evaluate(
|
||||
() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.selection.value
|
||||
.imageIds,
|
||||
);
|
||||
expect(
|
||||
selImgs.includes(ins!.id),
|
||||
"locked image not selectable by click",
|
||||
).toBe(false);
|
||||
// Unlock via store-selection (bypasses the inert UI) then toggle.
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.getByTestId("v2-toggle-lock").click();
|
||||
await page.waitForTimeout(200);
|
||||
await expect(page.getByTestId(`v2-image-${ins!.id}`)).not.toHaveAttribute(
|
||||
"data-locked",
|
||||
"true",
|
||||
);
|
||||
});
|
||||
|
||||
test("z-order: send-to-back is its own undo step and keeps the image", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
const undoBefore = await undoSize(page);
|
||||
await clickArrange(page, "v2-z-to-back");
|
||||
await page.waitForTimeout(300);
|
||||
expect(await undoSize(page), "send-to-back is one undo step").toBe(
|
||||
undoBefore + 1,
|
||||
);
|
||||
const imgs = await page.evaluate(() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.loadedPages()
|
||||
.reduce((n: number, p) => n + p.images.length, 0),
|
||||
);
|
||||
expect(imgs).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("z-order: forward then backward each add an undoable step", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 0);
|
||||
const ins = await insertImage(page);
|
||||
expect(ins).not.toBeNull();
|
||||
await page.evaluate(
|
||||
(iid: string) =>
|
||||
(
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.selection.selectImage(iid),
|
||||
ins!.id,
|
||||
);
|
||||
await page.waitForTimeout(120);
|
||||
const base = await undoSize(page);
|
||||
await clickArrange(page, "v2-z-forward");
|
||||
await page.waitForTimeout(250);
|
||||
await clickArrange(page, "v2-z-backward");
|
||||
await page.waitForTimeout(250);
|
||||
expect(await undoSize(page), "two z-order steps recorded").toBe(base + 2);
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(200);
|
||||
expect(await undoSize(page)).toBe(base + 1);
|
||||
});
|
||||
|
||||
test("align-right makes selected runs share the same right edge", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const a = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const b = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
await selectMany(page, [a, b]);
|
||||
await clickArrange(page, "v2-align-right");
|
||||
await page.waitForTimeout(300);
|
||||
const rights = await page.evaluate(
|
||||
({ a, b }: { a: string; b: string }) => {
|
||||
const pg = (
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.doc.page(1);
|
||||
const ra = pg.runs.find((x) => x.id === a)!;
|
||||
const rb = pg.runs.find((x) => x.id === b)!;
|
||||
return [ra.bounds.x + ra.bounds.width, rb.bounds.x + rb.bounds.width];
|
||||
},
|
||||
{ a, b },
|
||||
);
|
||||
expect(
|
||||
Math.abs(rights[0] - rights[1]),
|
||||
"aligned runs share a right edge",
|
||||
).toBeLessThan(1.5);
|
||||
});
|
||||
|
||||
test("align-top makes selected runs share the same top edge", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const a = await runId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const b = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
await selectMany(page, [a, b]);
|
||||
await clickArrange(page, "v2-align-top");
|
||||
await page.waitForTimeout(300);
|
||||
const tops = await page.evaluate(
|
||||
({ a, b }: { a: string; b: string }) => {
|
||||
const pg = (
|
||||
window as unknown as V2TestWindow
|
||||
).__v2_editor_store.doc.page(1);
|
||||
const ra = pg.runs.find((x) => x.id === a)!;
|
||||
const rb = pg.runs.find((x) => x.id === b)!;
|
||||
return [ra.bounds.y + ra.bounds.height, rb.bounds.y + rb.bounds.height];
|
||||
},
|
||||
{ a, b },
|
||||
);
|
||||
expect(
|
||||
Math.abs(tops[0] - tops[1]),
|
||||
"aligned runs share a top edge",
|
||||
).toBeLessThan(1.5);
|
||||
});
|
||||
|
||||
test("distribute-v equalizes the vertical gaps across three runs", async ({
|
||||
page,
|
||||
}) => {
|
||||
// Page text runs are stacked vertically (one per line/paragraph), so
|
||||
// vertical distribution is the natural axis - they don't overlap on y,
|
||||
// so the middle run stays between its neighbours and gaps equalize.
|
||||
await open(page, 1);
|
||||
const ids = await firstRunIds(page, 1, 3);
|
||||
expect(ids.length, "need three runs to distribute").toBe(3);
|
||||
await selectMany(page, ids);
|
||||
await clickArrange(page, "v2-distribute-v");
|
||||
await page.waitForTimeout(300);
|
||||
const gaps = await page.evaluate((ids: string[]) => {
|
||||
const pg = (window as unknown as V2TestWindow).__v2_editor_store.doc.page(
|
||||
1,
|
||||
);
|
||||
const items = ids
|
||||
.map((id) => pg.runs.find((r) => r.id === id)!)
|
||||
.map((r) => ({ y: r.bounds.y, h: r.bounds.height }))
|
||||
.sort((p, q) => p.y - q.y);
|
||||
const g: number[] = [];
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
g.push(items[i].y - (items[i - 1].y + items[i - 1].h));
|
||||
}
|
||||
return g;
|
||||
}, ids);
|
||||
expect(
|
||||
Math.abs(gaps[0] - gaps[1]),
|
||||
"consecutive gaps become equal",
|
||||
).toBeLessThan(1.0);
|
||||
});
|
||||
|
||||
test("change case Title Case transforms the selected run", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const orig = await runText(page, 1, id);
|
||||
const expected = orig.replace(
|
||||
/\b\w[\w']*/g,
|
||||
(w) => w[0].toUpperCase() + w.slice(1).toLowerCase(),
|
||||
);
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-change-case").click();
|
||||
await page.getByTestId("v2-change-case-title").click();
|
||||
await page.waitForTimeout(400);
|
||||
expect(await runText(page, 1, id)).toBe(expected);
|
||||
});
|
||||
|
||||
test("change case Sentence case capitalizes after a lowercase pass", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const orig = await runText(page, 1, id);
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-change-case").click();
|
||||
await page.getByTestId("v2-change-case-lower").click();
|
||||
await page.waitForTimeout(400);
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-change-case").click();
|
||||
await page.getByTestId("v2-change-case-sentence").click();
|
||||
await page.waitForTimeout(400);
|
||||
const expected = orig
|
||||
.toLowerCase()
|
||||
.replace(/(^\s*\w|[.!?]\s+\w)/g, (m) => m.toUpperCase());
|
||||
expect(await runText(page, 1, id)).toBe(expected);
|
||||
});
|
||||
|
||||
test("change case is undoable - undo restores the original text", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const orig = await runText(page, 1, id);
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-change-case").click();
|
||||
await page.getByTestId("v2-change-case-upper").click();
|
||||
await page.waitForTimeout(400);
|
||||
expect(await runText(page, 1, id)).toBe(orig.toUpperCase());
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(400);
|
||||
expect(await runText(page, 1, id)).toBe(orig);
|
||||
});
|
||||
|
||||
test("duplicate (Ctrl+D) clones the selected run", async ({ page }) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const before = await totalRuns(page);
|
||||
await selectRun(page, id);
|
||||
await page.evaluate(() =>
|
||||
(document.activeElement as HTMLElement | null)?.blur(),
|
||||
);
|
||||
await page.keyboard.press("Control+d");
|
||||
await page.waitForTimeout(300);
|
||||
expect(await totalRuns(page), "duplicate adds one run").toBe(before + 1);
|
||||
});
|
||||
|
||||
test("Delete key removes the selected run", async ({ page }) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const before = await totalRuns(page);
|
||||
await selectRun(page, id);
|
||||
await page.evaluate(() =>
|
||||
(document.activeElement as HTMLElement | null)?.blur(),
|
||||
);
|
||||
await page.keyboard.press("Delete");
|
||||
await page.waitForTimeout(300);
|
||||
expect(await totalRuns(page), "delete removes one run").toBe(before - 1);
|
||||
expect(await runText(page, 1, id)).toBe("(gone)");
|
||||
});
|
||||
|
||||
test("undo restores a locked run to unlocked + editable", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const id = await runId(page, 1, "Comprehensive\\s+toolkit");
|
||||
await selectRun(page, id);
|
||||
await page.getByTestId("v2-toggle-lock").click();
|
||||
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
|
||||
"data-locked",
|
||||
"true",
|
||||
);
|
||||
await page.getByTestId("v2-undo").click();
|
||||
await page.waitForTimeout(250);
|
||||
const locked = await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.locked,
|
||||
id,
|
||||
);
|
||||
expect(locked, "undo unlocks the run").toBe(false);
|
||||
await expect(page.getByTestId(`v2-run-${id}`)).toHaveAttribute(
|
||||
"contenteditable",
|
||||
"true",
|
||||
);
|
||||
});
|
||||
|
||||
test("find (Ctrl+F) reports a match count for an existing term", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
await page.keyboard.press("Control+f");
|
||||
await expect(page.getByTestId("v2-find-bar")).toBeVisible();
|
||||
await page.getByTestId("v2-find-input").fill("PDF");
|
||||
await page.waitForTimeout(400);
|
||||
const count = await page.getByTestId("v2-find-count").innerText();
|
||||
expect(count, "find reports N of M for a present term").toMatch(
|
||||
/\d+ of \d+/,
|
||||
);
|
||||
});
|
||||
|
||||
test("replace swaps the matched run's text for the new term", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, 1);
|
||||
const before = await countRunsContaining(page, "toolkit");
|
||||
expect(before, "fixture must contain the search term").toBeGreaterThan(0);
|
||||
await page.keyboard.press("Control+f");
|
||||
await expect(page.getByTestId("v2-find-bar")).toBeVisible();
|
||||
await page.getByTestId("v2-find-input").fill("toolkit");
|
||||
await page.waitForTimeout(400);
|
||||
await page.getByTestId("v2-replace-input").fill("widget");
|
||||
await page.getByTestId("v2-replace-one").click();
|
||||
await page.waitForTimeout(600);
|
||||
expect(
|
||||
await countRunsContaining(page, "toolkit"),
|
||||
"one match-run replaced",
|
||||
).toBe(before - 1);
|
||||
expect(
|
||||
await countRunsContaining(page, "widget"),
|
||||
"replacement text present",
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("replace all rewrites every matching run", async ({ page }) => {
|
||||
await open(page, 1);
|
||||
const before = await countRunsContaining(page, "pdf");
|
||||
expect(before, "fixture must contain the search term").toBeGreaterThan(0);
|
||||
await page.keyboard.press("Control+f");
|
||||
await expect(page.getByTestId("v2-find-bar")).toBeVisible();
|
||||
await page.getByTestId("v2-find-input").fill("PDF");
|
||||
await page.waitForTimeout(400);
|
||||
await page.getByTestId("v2-replace-input").fill("DOC");
|
||||
await page.getByTestId("v2-replace-all").click();
|
||||
await page.waitForTimeout(900);
|
||||
expect(
|
||||
await countRunsContaining(page, "pdf"),
|
||||
"no matches remain after replace-all",
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,336 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import {
|
||||
DisplayTransform,
|
||||
type DisplayTransformData,
|
||||
} from "@app/tools/pdfTextEditor/v2/model/DisplayTransform";
|
||||
import path from "path";
|
||||
|
||||
/**
|
||||
* Regression for the CropBox/rotation positioning bug (root-caused on
|
||||
* spirit-sx-user-guide.pdf, which is NEVER committed). These use SYNTHETIC
|
||||
* fixtures generated by generate-cropbox-fixtures.py:
|
||||
*
|
||||
* - cropbox-control.pdf : CropBox == MediaBox, /Rotate 0 (must be identity)
|
||||
* - cropbox-offset.pdf : CropBox origin (50,30), 300x350 visible page
|
||||
* - cropbox-rotate90.pdf : same crop + /Rotate 90 (displayed 350x300)
|
||||
*
|
||||
* The page object stores a DisplayTransform read from the real PDF's CropBox +
|
||||
* rotation; the model stays in raw PDF (MediaBox) space; the overlay maps raw
|
||||
* coords to the rendered (cropped/rotated) bitmap. Each fixture draws "Hi" at
|
||||
* user-space baseline (60,350).
|
||||
*/
|
||||
|
||||
interface Probe {
|
||||
width: number;
|
||||
height: number;
|
||||
runCount: number;
|
||||
matrixE: number;
|
||||
matrixF: number;
|
||||
boundsX: number;
|
||||
display: DisplayTransformData;
|
||||
}
|
||||
|
||||
async function load(
|
||||
page: import("@playwright/test").Page,
|
||||
name: string,
|
||||
): Promise<Probe> {
|
||||
await page.goto("/pdf-text-editor?charcodeStrategy=content-stream", {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
|
||||
await page
|
||||
.locator('[data-testid="v2-file-input"]')
|
||||
.setInputFiles(
|
||||
path.join(import.meta.dirname, `../test-fixtures/${name}.pdf`),
|
||||
);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(800);
|
||||
return page.evaluate(() => {
|
||||
const s = (
|
||||
window as unknown as {
|
||||
__v2_editor_store: {
|
||||
doc: {
|
||||
page: (i: number) => {
|
||||
width: number;
|
||||
height: number;
|
||||
runs: Array<{
|
||||
bounds: { x: number };
|
||||
matrix: { e: number; f: number };
|
||||
}>;
|
||||
display: Probe["display"];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
).__v2_editor_store;
|
||||
const pg = s.doc.page(0);
|
||||
const r = pg.runs[0];
|
||||
return {
|
||||
width: pg.width,
|
||||
height: pg.height,
|
||||
runCount: pg.runs.length,
|
||||
matrixE: r?.matrix.e,
|
||||
matrixF: r?.matrix.f,
|
||||
boundsX: r?.bounds.x,
|
||||
display: pg.display,
|
||||
};
|
||||
}) as Promise<Probe>;
|
||||
}
|
||||
|
||||
test("control fixture (CropBox==MediaBox) yields an identity transform", async ({
|
||||
page,
|
||||
}) => {
|
||||
const p = await load(page, "cropbox-control");
|
||||
expect(p.width).toBe(400);
|
||||
expect(p.height).toBe(400);
|
||||
expect(p.display.cropLeft).toBe(0);
|
||||
expect(p.display.cropBottom).toBe(0);
|
||||
expect(p.display.rotate).toBe(0);
|
||||
const t = DisplayTransform.fromData(p.display);
|
||||
expect(t.isIdentity).toBe(true);
|
||||
// Model is raw; with identity the display position equals the raw position.
|
||||
expect(t.apply(p.boundsX, p.matrixF)).toEqual({ x: p.boundsX, y: p.matrixF });
|
||||
});
|
||||
|
||||
test("CropBox-offset fixture: page sized to CropBox, model raw, overlay offset", async ({
|
||||
page,
|
||||
}) => {
|
||||
const p = await load(page, "cropbox-offset");
|
||||
// page dims are the CropBox (visible) size, not the square MediaBox.
|
||||
expect(p.width).toBe(300);
|
||||
expect(p.height).toBe(350);
|
||||
// The transform read the real PDF's CropBox origin.
|
||||
expect(p.display.cropLeft).toBe(50);
|
||||
expect(p.display.cropBottom).toBe(30);
|
||||
expect(p.display.rotate).toBe(0);
|
||||
// The MODEL stays in raw PDF (MediaBox) space - Td(60,350) baseline intact.
|
||||
expect(p.matrixE).toBeCloseTo(60, 1);
|
||||
expect(p.matrixF).toBeCloseTo(350, 1);
|
||||
// The display anchor subtracts the CropBox origin: raw (~61.8,350) -> (~11.8,320).
|
||||
const t = DisplayTransform.fromData(p.display);
|
||||
const disp = t.apply(p.boundsX, p.matrixF);
|
||||
expect(disp.x).toBeCloseTo(p.boundsX - 50, 3);
|
||||
expect(disp.y).toBeCloseTo(320, 3);
|
||||
// ...and the anchor now lands INSIDE the visible page (the bug put it past
|
||||
// the right edge / above the top because the +50/-30 offset wasn't removed).
|
||||
expect(disp.x).toBeGreaterThanOrEqual(0);
|
||||
expect(disp.x).toBeLessThanOrEqual(p.width);
|
||||
expect(disp.y).toBeGreaterThanOrEqual(0);
|
||||
expect(disp.y).toBeLessThanOrEqual(p.height);
|
||||
// Teeth: the un-transformed (pre-fix) x carried the +50 crop offset.
|
||||
expect(p.boundsX).toBeGreaterThan(disp.x + 40);
|
||||
});
|
||||
|
||||
test("CropBox + Rotate 90 fixture: dims swap, rotation in the transform, model raw", async ({
|
||||
page,
|
||||
}) => {
|
||||
const p = await load(page, "cropbox-rotate90");
|
||||
// /Rotate 90 swaps the displayed page dimensions.
|
||||
expect(p.width).toBe(350);
|
||||
expect(p.height).toBe(300);
|
||||
expect(p.display.rotate).toBe(1);
|
||||
expect(p.display.cropLeft).toBe(50);
|
||||
expect(p.display.cropBottom).toBe(30);
|
||||
// 90 CW affine is a proper rotation (det +1): a=0,b=-1,c=1,d=0.
|
||||
expect([p.display.a, p.display.b, p.display.c, p.display.d]).toEqual([
|
||||
0, -1, 1, 0,
|
||||
]);
|
||||
expect(
|
||||
p.display.a * p.display.d - p.display.b * p.display.c,
|
||||
"rotation must be det +1, not a reflection",
|
||||
).toBeCloseTo(1, 9);
|
||||
// Model still raw.
|
||||
expect(p.matrixF).toBeCloseTo(350, 1);
|
||||
// The display anchor lands inside the rotated visible page.
|
||||
const t = DisplayTransform.fromData(p.display);
|
||||
const disp = t.apply(p.boundsX, p.matrixF);
|
||||
expect(disp.x).toBeGreaterThanOrEqual(0);
|
||||
expect(disp.x).toBeLessThanOrEqual(p.width);
|
||||
expect(disp.y).toBeGreaterThanOrEqual(0);
|
||||
expect(disp.y).toBeLessThanOrEqual(p.height);
|
||||
});
|
||||
|
||||
test("editing text on a Rotate-90 page applies cleanly and keeps placement in-bounds", async ({
|
||||
page,
|
||||
}) => {
|
||||
// Editing happens in raw PDF space (commands are rotation-agnostic); the
|
||||
// overlay maps the anchor through the rotation transform. Verify a real
|
||||
// type-edit round-trips on a rotated page with no crash and in-bounds anchor.
|
||||
const errs: string[] = [];
|
||||
page.on("pageerror", (e) => errs.push(e.message));
|
||||
await page.goto("/pdf-text-editor?charcodeStrategy=content-stream", {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
|
||||
await page
|
||||
.locator('[data-testid="v2-file-input"]')
|
||||
.setInputFiles(
|
||||
path.join(import.meta.dirname, "../test-fixtures/cropbox-rotate90.pdf"),
|
||||
);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(800);
|
||||
|
||||
const id = await page.evaluate(() => {
|
||||
const s = (
|
||||
window as unknown as {
|
||||
__v2_editor_store: {
|
||||
doc: { page: (i: number) => { runs: Array<{ id: string }> } };
|
||||
};
|
||||
}
|
||||
).__v2_editor_store;
|
||||
return s.doc.page(0).runs[0]?.id ?? "";
|
||||
});
|
||||
expect(id).toMatch(/^p0-/);
|
||||
|
||||
await page.locator(`[data-testid="v2-run-${id}"]`).click();
|
||||
await page.waitForTimeout(150);
|
||||
await page.evaluate((rid) => {
|
||||
const el = document.querySelector<HTMLDivElement>(
|
||||
`[data-testid="v2-run-${rid}"]`,
|
||||
)!;
|
||||
el.focus();
|
||||
const sel = window.getSelection()!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand("insertText", false, "Z");
|
||||
}, id);
|
||||
await page.waitForTimeout(150);
|
||||
await page.evaluate(
|
||||
(rid) =>
|
||||
document
|
||||
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
|
||||
?.blur(),
|
||||
id,
|
||||
);
|
||||
await page.waitForTimeout(800);
|
||||
|
||||
const after = await page.evaluate(() => {
|
||||
const s = (
|
||||
window as unknown as {
|
||||
__v2_editor_store: {
|
||||
doc: {
|
||||
page: (i: number) => {
|
||||
width: number;
|
||||
height: number;
|
||||
runs: Array<{
|
||||
id: string;
|
||||
text: string;
|
||||
bounds: { x: number };
|
||||
matrix: { f: number };
|
||||
}>;
|
||||
display: {
|
||||
a: number;
|
||||
b: number;
|
||||
c: number;
|
||||
d: number;
|
||||
e: number;
|
||||
f: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
).__v2_editor_store;
|
||||
const pg = s.doc.page(0);
|
||||
const r = pg.runs[0];
|
||||
const d = pg.display;
|
||||
return {
|
||||
text: r.text,
|
||||
width: pg.width,
|
||||
height: pg.height,
|
||||
dispX: d.a * r.bounds.x + d.c * r.matrix.f + d.e,
|
||||
dispY: d.b * r.bounds.x + d.d * r.matrix.f + d.f,
|
||||
};
|
||||
});
|
||||
|
||||
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
|
||||
expect(after.text).toContain("Z"); // edit applied
|
||||
// Anchor still inside the rotated visible page (no off-page drift).
|
||||
expect(after.dispX).toBeGreaterThanOrEqual(0);
|
||||
expect(after.dispX).toBeLessThanOrEqual(after.width);
|
||||
expect(after.dispY).toBeGreaterThanOrEqual(0);
|
||||
expect(after.dispY).toBeLessThanOrEqual(after.height);
|
||||
});
|
||||
|
||||
test("CropBox-offset: the rendered glyph pixels overlap the run overlay box", async ({
|
||||
page,
|
||||
}) => {
|
||||
// End-to-end: the PDFium-rendered bitmap (CropBox-cropped) and the HTML
|
||||
// overlay (positioned via the transform) must agree on where "Hi" sits.
|
||||
await page.goto("/pdf-text-editor?charcodeStrategy=content-stream", {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 30_000 });
|
||||
await page
|
||||
.locator('[data-testid="v2-file-input"]')
|
||||
.setInputFiles(
|
||||
path.join(import.meta.dirname, "../test-fixtures/cropbox-offset.pdf"),
|
||||
);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(1200);
|
||||
|
||||
const result = await page.evaluate(() => {
|
||||
const pageEl = document.querySelector<HTMLElement>(
|
||||
'[data-testid="v2-page-0"]',
|
||||
)!;
|
||||
const canvas = pageEl.querySelector("canvas")!;
|
||||
const pageRect = pageEl.getBoundingClientRect();
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
// Find the dark-pixel bounding box (the "Hi" glyphs) in canvas px.
|
||||
let minX = Infinity,
|
||||
minY = Infinity,
|
||||
maxX = -Infinity,
|
||||
maxY = -Infinity;
|
||||
const { data, width, height } = img;
|
||||
for (let y = 0; y < height; y++) {
|
||||
for (let x = 0; x < width; x++) {
|
||||
const o = (y * width + x) * 4;
|
||||
const lum = (data[o] + data[o + 1] + data[o + 2]) / 3;
|
||||
if (lum < 128 && data[o + 3] > 32) {
|
||||
if (x < minX) minX = x;
|
||||
if (x > maxX) maxX = x;
|
||||
if (y < minY) minY = y;
|
||||
if (y > maxY) maxY = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Canvas is rendered at devicePixelRatio*scale; normalise to CSS px by the
|
||||
// canvas's own client size.
|
||||
const sx = canvas.clientWidth / canvas.width;
|
||||
const sy = canvas.clientHeight / canvas.height;
|
||||
const glyph = {
|
||||
left: minX * sx,
|
||||
top: minY * sy,
|
||||
right: maxX * sx,
|
||||
bottom: maxY * sy,
|
||||
};
|
||||
const overlay = document
|
||||
.querySelector<HTMLElement>('[data-testid^="v2-run-"]')!
|
||||
.getBoundingClientRect();
|
||||
const ov = {
|
||||
left: overlay.left - pageRect.left,
|
||||
top: overlay.top - pageRect.top,
|
||||
right: overlay.right - pageRect.left,
|
||||
bottom: overlay.bottom - pageRect.top,
|
||||
};
|
||||
return { glyph, ov, found: maxX >= minX };
|
||||
});
|
||||
|
||||
expect(result.found).toBe(true);
|
||||
// The overlay box and the rendered-glyph box must overlap (loose: the
|
||||
// overlay box is taller than the glyph ink, but they must not be disjoint -
|
||||
// a pre-fix overlay would sit ~50px to the right and ~30px too high).
|
||||
const overlaps =
|
||||
result.ov.left <= result.glyph.right + 8 &&
|
||||
result.ov.right >= result.glyph.left - 8 &&
|
||||
result.ov.top <= result.glyph.bottom + 12 &&
|
||||
result.ov.bottom >= result.glyph.top - 12;
|
||||
expect(
|
||||
overlaps,
|
||||
`overlay ${JSON.stringify(result.ov)} must overlap glyph ${JSON.stringify(result.glyph)}`,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import type { Page, Route } from "@playwright/test";
|
||||
import path from "path";
|
||||
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
|
||||
|
||||
/**
|
||||
* Cross-font charcode disambiguation (H1H2/U).
|
||||
*
|
||||
* The backend encode-charcodes endpoint now accepts a `fontName` so a page with
|
||||
* two fonts rendering the same char encodes against the RIGHT one. This test
|
||||
* mocks the endpoint and asserts the frontend reads the run's /BaseFont name
|
||||
* (FPDFFont_GetBaseFontName) and sends it - the wiring that makes the backend
|
||||
* disambiguation reachable. The backend half is covered by the Java unit test
|
||||
* (fontNameDisambiguatesBetweenTwoFontsRenderingTheSameChar).
|
||||
*/
|
||||
|
||||
const SUBSET = path.join(
|
||||
import.meta.dirname,
|
||||
"../test-fixtures/subset-font-sample.pdf",
|
||||
);
|
||||
|
||||
test("editor sends the run's font name to encode-charcodes", async ({
|
||||
page,
|
||||
}: {
|
||||
page: Page;
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
const bodies: Array<Record<string, unknown>> = [];
|
||||
await page.route("**/encode-charcodes", async (route: Route) => {
|
||||
try {
|
||||
bodies.push(route.request().postDataJSON() as Record<string, unknown>);
|
||||
} catch {
|
||||
/* ignore non-JSON */
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ charcodes: [65], missing: [], note: "stub" }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
|
||||
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SUBSET);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(800);
|
||||
|
||||
// Edit a run - the cache-miss prefetch (and focus prewarm) POST to the
|
||||
// endpoint, now carrying the resolved font's name.
|
||||
const id = await page.evaluate(() => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
return s.doc.page(0).runs[0]?.id ?? null;
|
||||
});
|
||||
expect(id, "page 0 has a run").toBeTruthy();
|
||||
await page.evaluate((rid: string) => {
|
||||
const el = document.querySelector<HTMLDivElement>(
|
||||
`[data-testid="v2-run-${rid}"]`,
|
||||
)!;
|
||||
el.focus();
|
||||
const sel = window.getSelection()!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand("insertText", false, "s");
|
||||
}, id as string);
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
expect(bodies.length, "endpoint was called").toBeGreaterThan(0);
|
||||
const named = bodies.filter(
|
||||
(b) => typeof b.fontName === "string" && (b.fontName as string).length > 0,
|
||||
);
|
||||
expect(
|
||||
named.length,
|
||||
`at least one request carries a non-empty fontName; bodies=${JSON.stringify(
|
||||
bodies.map((b) => b.fontName),
|
||||
)}`,
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import type { Page, Route } from "@playwright/test";
|
||||
import path from "path";
|
||||
|
||||
/**
|
||||
* End-to-end coverage for the fonts panel's client-side glyph-coverage probe.
|
||||
*
|
||||
* The document loader primes each embedded font's cmap into a cache during its
|
||||
* SERIALIZED text-read phase (reading font data at render time corrupts PDFium
|
||||
* - that path is deliberately avoided). The panel then reports, per font, which
|
||||
* of a-z A-Z 0-9 the font actually has glyphs for, with zero render-time WASM.
|
||||
*
|
||||
* subset-font-sample.pdf embeds a TrueType subset whose cmap omits most
|
||||
* alphanumerics, so the panel must surface concrete "Missing: ..." chars and a
|
||||
* yellow summary - all without backend help (encode-charcodes is aborted).
|
||||
*/
|
||||
|
||||
const SUBSET = path.join(
|
||||
import.meta.dirname,
|
||||
"../test-fixtures/subset-font-sample.pdf",
|
||||
);
|
||||
|
||||
async function open(page: Page, file: string): Promise<void> {
|
||||
await page.route("**/encode-charcodes", (route: Route) => route.abort());
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
|
||||
await page.locator('[data-testid="v2-file-input"]').setInputFiles(file);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(1500);
|
||||
}
|
||||
|
||||
test("fonts panel reports concrete a-zA-Z0-9 coverage gaps client-side", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
const errs: string[] = [];
|
||||
page.on("pageerror", (e) => errs.push(e.message));
|
||||
await open(page, SUBSET);
|
||||
|
||||
// The editor must still render (the canvas page) - reading font data at load
|
||||
// must not corrupt PDFium.
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible();
|
||||
|
||||
const panel = page.getByTestId("v2-fonts-panel");
|
||||
await expect(panel).toBeVisible();
|
||||
|
||||
// A subset TrueType font with a parseable cmap => concrete missing chars.
|
||||
const missing = panel.getByTestId("v2-font-missing").first();
|
||||
await expect(missing).toBeVisible();
|
||||
await expect(missing).toContainText(/Missing:/);
|
||||
|
||||
// ...and the summary escalates to the yellow "warn" tone accordingly.
|
||||
await expect(panel.getByTestId("v2-font-compat")).toHaveAttribute(
|
||||
"data-compat",
|
||||
"warn",
|
||||
);
|
||||
|
||||
expect(errs, `no page errors:\n${errs.join("\n")}`).toEqual([]);
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import type { Page, Route } from "@playwright/test";
|
||||
import path from "path";
|
||||
|
||||
/**
|
||||
* Inserting a JPEG embeds the original JPEG stream (DCTDecode) instead of
|
||||
* re-encoding decoded RGBA pixels (FlateDecode), so the output stays small
|
||||
* (finding R). Verified by scanning the saved PDF for the DCTDecode filter.
|
||||
*/
|
||||
|
||||
const SAMPLE_PDF = path.join(
|
||||
import.meta.dirname,
|
||||
"../test-fixtures/sample.pdf",
|
||||
);
|
||||
const SAMPLE_JPG = path.join(
|
||||
import.meta.dirname,
|
||||
"../test-fixtures/sample.jpg",
|
||||
);
|
||||
|
||||
test("inserting a JPEG embeds it as DCTDecode, not re-encoded RGBA", async ({
|
||||
page,
|
||||
}: {
|
||||
page: Page;
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.route("**/encode-charcodes", (route: Route) => route.abort());
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 20_000 });
|
||||
await page.locator('[data-testid="v2-file-input"]').setInputFiles(SAMPLE_PDF);
|
||||
await expect(page.getByTestId("v2-page-0")).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Insert the JPEG via the editor's image input.
|
||||
await page
|
||||
.locator('[data-testid="v2-image-input"]')
|
||||
.setInputFiles(SAMPLE_JPG);
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
// Save and scan the bytes for the JPEG (DCTDecode) filter.
|
||||
const downloadPromise = page.waitForEvent("download");
|
||||
await page.getByTestId("v2-save").click();
|
||||
const dl = await downloadPromise;
|
||||
const stream = await dl.createReadStream();
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const c of stream) chunks.push(c as Buffer);
|
||||
const saved = Buffer.concat(chunks);
|
||||
const asText = saved.toString("latin1");
|
||||
|
||||
expect(saved.subarray(0, 4).toString("ascii")).toBe("%PDF");
|
||||
expect(
|
||||
asText.includes("DCTDecode"),
|
||||
"saved PDF embeds the JPEG as DCTDecode (passthrough)",
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -1,560 +0,0 @@
|
||||
import { test, expect } from "@app/tests/helpers/stub-test-base";
|
||||
import type { Page } from "@playwright/test";
|
||||
import path from "path";
|
||||
import type { V2TestWindow } from "@app/tests/stubbed/v2EditorTestTypes";
|
||||
|
||||
/**
|
||||
* REGRESSION suite for the 12 issues found by the QA sweep of the v2 PDF text
|
||||
* editor - all since fixed. Each test asserts the desired behaviour and must
|
||||
* pass. They were previously `test.fail()` placeholders documenting the bugs;
|
||||
* the markers were removed as each fix landed.
|
||||
*
|
||||
* Scenarios are weighted to the shipped marketing Sample.pdf (Type3,
|
||||
* per-glyph fonts) because that is what users actually load.
|
||||
*/
|
||||
const SAMPLE = path.join(
|
||||
import.meta.dirname,
|
||||
"../../../../public/samples/Sample.pdf",
|
||||
);
|
||||
const SUBSET = path.join(
|
||||
import.meta.dirname,
|
||||
"../test-fixtures/subset-font-sample.pdf",
|
||||
);
|
||||
|
||||
async function open(page: Page, file: string, firstPage = 0): Promise<void> {
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
|
||||
await page.locator('[data-testid="v2-file-input"]').setInputFiles(file);
|
||||
await expect(page.getByTestId(`v2-page-${firstPage}`)).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await page.waitForTimeout(900);
|
||||
}
|
||||
async function findId(
|
||||
page: Page,
|
||||
pageIdx: number,
|
||||
src: string,
|
||||
): Promise<string> {
|
||||
const id = await page.evaluate(
|
||||
({ pageIdx, src }: { pageIdx: number; src: string }) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
const r = s.doc
|
||||
.page(pageIdx)
|
||||
.runs.find((x) => new RegExp(src).test(x.text));
|
||||
return r ? r.id : null;
|
||||
},
|
||||
{ pageIdx, src },
|
||||
);
|
||||
if (!id) throw new Error(`run /${src}/ not found on page ${pageIdx}`);
|
||||
return id;
|
||||
}
|
||||
async function leafPtrs(
|
||||
page: Page,
|
||||
pageIdx: number,
|
||||
id: string,
|
||||
): Promise<number[]> {
|
||||
return page.evaluate(
|
||||
({ pageIdx, id }: { pageIdx: number; id: string }) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
const r = s.doc.page(pageIdx).runs.find((x) => x.id === id);
|
||||
return r ? [...r.paragraphLeafPtrs] : [];
|
||||
},
|
||||
{ pageIdx, id },
|
||||
);
|
||||
}
|
||||
async function caretEndInsert(
|
||||
page: Page,
|
||||
id: string,
|
||||
text: string,
|
||||
): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ id, text }: { id: string; text: string }) => {
|
||||
const el = document.querySelector<HTMLDivElement>(
|
||||
`[data-testid="v2-run-${id}"]`,
|
||||
)!;
|
||||
el.focus();
|
||||
const sel = window.getSelection()!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand("insertText", false, text);
|
||||
},
|
||||
{ id, text },
|
||||
);
|
||||
await page.waitForTimeout(150);
|
||||
}
|
||||
async function replaceAll(page: Page, id: string, full: string): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ id, full }: { id: string; full: string }) => {
|
||||
const el = document.querySelector<HTMLDivElement>(
|
||||
`[data-testid="v2-run-${id}"]`,
|
||||
)!;
|
||||
el.focus();
|
||||
const sel = window.getSelection()!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand("insertText", false, full);
|
||||
},
|
||||
{ id, full },
|
||||
);
|
||||
await page.waitForTimeout(200);
|
||||
}
|
||||
async function blur(page: Page, id: string): Promise<void> {
|
||||
await page.evaluate((rid: string) => {
|
||||
document
|
||||
.querySelector<HTMLElement>(`[data-testid="v2-run-${rid}"]`)
|
||||
?.blur();
|
||||
}, id);
|
||||
await page.waitForTimeout(1200);
|
||||
}
|
||||
/** Per-glyph geometry + extracted text for a run, straight from PDFium. */
|
||||
async function glyphs(
|
||||
page: Page,
|
||||
pageIdx: number,
|
||||
id: string,
|
||||
): Promise<{
|
||||
boundsRight: number;
|
||||
pageWidth: number;
|
||||
fontId: string;
|
||||
text: string;
|
||||
maxGap: number;
|
||||
hasYdieresis: boolean;
|
||||
}> {
|
||||
return page.evaluate(
|
||||
({ pageIdx, id }: { pageIdx: number; id: string }) => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
const m = s.doc.module;
|
||||
const pg = s.doc.page(pageIdx);
|
||||
pg.flushGenerate(m);
|
||||
const r = pg.runs.find((x) => x.id === id)!;
|
||||
const ptrs: number[] = r.paragraphLeafPtrs.length
|
||||
? r.paragraphLeafPtrs
|
||||
: r.mergedFromPtrs.length
|
||||
? r.mergedFromPtrs
|
||||
: [r.pdfiumObjPtr];
|
||||
const tp = m.FPDFText_LoadPage(pg.pagePtr);
|
||||
const seg: Array<{ x: number; right: number; base: number }> = [];
|
||||
let hasY = false;
|
||||
try {
|
||||
for (const ptr of ptrs) {
|
||||
if (!ptr) continue;
|
||||
const l = m.pdfium.wasmExports.malloc(4);
|
||||
const b = m.pdfium.wasmExports.malloc(4);
|
||||
const rr = m.pdfium.wasmExports.malloc(4);
|
||||
const t = m.pdfium.wasmExports.malloc(4);
|
||||
const mat = m.pdfium.wasmExports.malloc(24);
|
||||
try {
|
||||
if (!m.FPDFPageObj_GetBounds(ptr, l, b, rr, t)) continue;
|
||||
let base = m.pdfium.getValue(b, "float");
|
||||
if (m.FPDFPageObj_GetMatrix(ptr, mat))
|
||||
base = m.pdfium.getValue(mat + 20, "float");
|
||||
seg.push({
|
||||
x: m.pdfium.getValue(l, "float"),
|
||||
right: m.pdfium.getValue(rr, "float"),
|
||||
base: Math.round(base),
|
||||
});
|
||||
const len = m.FPDFTextObj_GetText(ptr, tp, 0, 0);
|
||||
if (len > 2) {
|
||||
const buf = m.pdfium.wasmExports.malloc(len);
|
||||
try {
|
||||
m.FPDFTextObj_GetText(ptr, tp, buf, len);
|
||||
let str = "";
|
||||
for (let o = 0; o < len - 2; o += 2)
|
||||
str += String.fromCharCode(m.pdfium.getValue(buf + o, "i16"));
|
||||
if (str.includes("ÿ")) hasY = true;
|
||||
} finally {
|
||||
m.pdfium.wasmExports.free(buf);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
m.pdfium.wasmExports.free(l);
|
||||
m.pdfium.wasmExports.free(b);
|
||||
m.pdfium.wasmExports.free(rr);
|
||||
m.pdfium.wasmExports.free(t);
|
||||
m.pdfium.wasmExports.free(mat);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
m.FPDFText_ClosePage(tp);
|
||||
}
|
||||
// Largest gap between consecutive glyphs on the TOP line.
|
||||
const top = seg.length ? Math.max(...seg.map((g) => g.base)) : 0;
|
||||
const line = seg
|
||||
.filter((g) => Math.abs(g.base - top) <= 2)
|
||||
.sort((a, b) => a.x - b.x);
|
||||
let maxGap = 0;
|
||||
for (let i = 1; i < line.length; i++) {
|
||||
maxGap = Math.max(maxGap, line[i].x - line[i - 1].right);
|
||||
}
|
||||
return {
|
||||
boundsRight: r.bounds.x + r.bounds.width,
|
||||
pageWidth: pg.width,
|
||||
fontId: r.fontId as string,
|
||||
text: (r.text as string) ?? "",
|
||||
maxGap,
|
||||
hasYdieresis: hasY,
|
||||
};
|
||||
},
|
||||
{ pageIdx, id },
|
||||
);
|
||||
}
|
||||
|
||||
test.describe("v2 editor - fixed-issue regressions", () => {
|
||||
// ISSUE: a single-line run grows past the right page edge when you type a
|
||||
// long string - the overflow is clipped/lost in the saved PDF instead of
|
||||
// wrapping or being clamped to the page.
|
||||
test("typing a long string into a single-line run stays on the page", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 0);
|
||||
const id = await findId(page, 0, "Adobe.*Acrobat.*Alternative");
|
||||
await caretEndInsert(
|
||||
page,
|
||||
id,
|
||||
" plus a very long appended tail that keeps going and going and going",
|
||||
);
|
||||
await blur(page, id);
|
||||
const g = await glyphs(page, 0, id);
|
||||
expect(
|
||||
g.boundsRight,
|
||||
"run must not extend past the page width",
|
||||
).toBeLessThanOrEqual(g.pageWidth + 2);
|
||||
});
|
||||
|
||||
// ISSUE: typing non-Latin text (CJK / emoji) into a paragraph re-emits the
|
||||
// WHOLE paragraph (surrogate guard bails), so every original line loses its
|
||||
// source font objects.
|
||||
test("typing non-Latin text keeps the paragraph's other lines' objects", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const before = await leafPtrs(page, 1, id);
|
||||
await caretEndInsert(page, id, " 日本語 🎉");
|
||||
await blur(page, id);
|
||||
const after = await leafPtrs(page, 1, id);
|
||||
const kept = before.filter((p) => after.includes(p)).length;
|
||||
expect(
|
||||
kept,
|
||||
"unedited lines must keep their objects when non-Latin text is added",
|
||||
).toBe(before.length);
|
||||
});
|
||||
|
||||
// ISSUE: non-Latin glyphs render as U+00FF (ydieresis "ÿ") tofu because the
|
||||
// base-14 fallback font has no glyph for them.
|
||||
test("typing non-Latin text does not render as ydieresis tofu", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
await caretEndInsert(page, id, " 日本語");
|
||||
await blur(page, id);
|
||||
const g = await glyphs(page, 1, id);
|
||||
expect(g.hasYdieresis, "CJK must not be replaced by 'ÿ' tofu glyphs").toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
// ISSUE: typing an emoji (astral / surrogate-pair char) then saving must
|
||||
// round-trip the FULL surrogate pair - a code-unit-level edit could split it
|
||||
// and leave a lone surrogate, and the base-14 fallback must not render it as
|
||||
// U+00FF ("ÿ") tofu. Exercises the surrogate path through a save+reopen.
|
||||
test("typing an emoji round-trips without a lone surrogate or U+00FF tofu", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
await caretEndInsert(page, id, " 🎉");
|
||||
await blur(page, id);
|
||||
|
||||
// Save, then reopen the produced bytes.
|
||||
const downloadPromise = page.waitForEvent("download");
|
||||
await page.getByTestId("v2-save").click();
|
||||
const dl = await downloadPromise;
|
||||
const stream = await dl.createReadStream();
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const c of stream) chunks.push(c as Buffer);
|
||||
const saved = Buffer.concat(chunks);
|
||||
|
||||
await page.locator('[data-testid="v2-file-input"]').setInputFiles({
|
||||
name: "emoji-round-trip.pdf",
|
||||
mimeType: "application/pdf",
|
||||
buffer: saved,
|
||||
});
|
||||
await expect(
|
||||
page.locator('[data-testid^="v2-run-p1-"]').first(),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const reopened = await page.evaluate(() => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
return s.doc
|
||||
.page(1)
|
||||
.runs.map((r) => r.text)
|
||||
.join("");
|
||||
});
|
||||
// No lone high surrogate (one not immediately followed by a low surrogate).
|
||||
expect(
|
||||
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(reopened),
|
||||
"saved model must not contain a lone surrogate",
|
||||
).toBe(false);
|
||||
expect(
|
||||
reopened.includes("ÿ"),
|
||||
"emoji must not be replaced by 'ÿ' tofu",
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// NOTE: two more issues are VISUALLY confirmed (see __qa screenshots) but
|
||||
// omitted here because a stable automated assertion is hard:
|
||||
// - replacing a long Type3 run with a short string leaves the surviving
|
||||
// glyphs spread out ("He llo Wo r ld") - kept glyphs are not re-flowed.
|
||||
// - deleting a word from a Type3 line leaves an internal gap
|
||||
// ("The Free Adobe Acrob at" after removing "Alternative").
|
||||
|
||||
// ISSUE: deleting the LEADING word of a paragraph line injects a stray
|
||||
// U+00FF ("ÿ") into the model text.
|
||||
test("deleting the leading word does not inject a U+00FF artifact", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const cur = await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.text as string,
|
||||
id,
|
||||
);
|
||||
await replaceAll(page, id, cur.replace(/^Comprehensive/, ""));
|
||||
await blur(page, id);
|
||||
const g = await glyphs(page, 1, id);
|
||||
expect(g.text.includes("ÿ"), "model text must not contain 'ÿ'").toBe(false);
|
||||
});
|
||||
|
||||
// ISSUE: deleting a single character from the MIDDLE of a Type3 word leaves
|
||||
// a spurious space at the deletion point ("Comprehensive" -> "Compre ensive"
|
||||
// after removing the 'h') - the surviving glyphs are not re-flowed together.
|
||||
test("deleting a mid-word character does not inject a spurious space", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Comprehensive\\s+toolkit");
|
||||
const cur = await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.text as string,
|
||||
id,
|
||||
);
|
||||
// drop the 'h' from "Comprehensive" -> the word should read "Compreensive"
|
||||
await replaceAll(page, id, cur.replace("Comprehensive", "Compreensive"));
|
||||
await blur(page, id);
|
||||
const g = await glyphs(page, 1, id);
|
||||
expect(
|
||||
g.text.includes("Compre ensive"),
|
||||
"mid-word delete must not split the word with a space",
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// ISSUE: inserting an image through the toolbar picker (the v2-image-input
|
||||
// file input) does not add an image to the page - the count stays the same.
|
||||
// createImageBitmap works headless (verified), so this is a real no-op, not
|
||||
// an environment limitation.
|
||||
test("inserting an image via the picker adds an image to the page", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 0);
|
||||
const countImages = () =>
|
||||
page.evaluate(() => {
|
||||
const s = (window as unknown as V2TestWindow).__v2_editor_store;
|
||||
return s.doc
|
||||
.loadedPages()
|
||||
.reduce((n: number, p) => n + p.images.length, 0);
|
||||
});
|
||||
const before = await countImages();
|
||||
// a 1x1 red PNG, decoded in-browser by handleInsertImage
|
||||
const png = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||
"base64",
|
||||
);
|
||||
await page.locator('[data-testid="v2-image-input"]').setInputFiles({
|
||||
name: "dot.png",
|
||||
mimeType: "image/png",
|
||||
buffer: png,
|
||||
});
|
||||
await page.waitForTimeout(1800);
|
||||
const after = await countImages();
|
||||
expect(after, "image insert must add an image to the page").toBeGreaterThan(
|
||||
before,
|
||||
);
|
||||
});
|
||||
|
||||
// ISSUE: injecting several consecutive spaces into a multi-line paragraph
|
||||
// collapses them - the paragraph-edit/overlay path re-derives spacing from
|
||||
// glyph geometry, so "Stirling PDF" (5 spaces) lands in the model with
|
||||
// fewer spaces and the saved PDF loses the intended gap. (A short single-line
|
||||
// replace preserves them, so this is specific to the multi-line path.)
|
||||
test("injecting consecutive spaces into a paragraph preserves them", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const cur = await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.text as string,
|
||||
id,
|
||||
);
|
||||
await replaceAll(
|
||||
page,
|
||||
id,
|
||||
cur.replace(/Stirling\s+PDF/, "Stirling PDF"),
|
||||
);
|
||||
await blur(page, id);
|
||||
const g = await glyphs(page, 1, id);
|
||||
expect(
|
||||
/Stirling {5}PDF/.test(g.text),
|
||||
"five consecutive injected spaces must survive into the model",
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// ISSUE: redo after undo-all does NOT reproduce the text the original edit
|
||||
// produced. A simple append to a Type3 paragraph keeps the source glyphs on
|
||||
// first apply, but redo re-emits the whole paragraph through the overlay path
|
||||
// (collapsing the Type3 double-space extraction), so redone != edited.
|
||||
test("redo after undo-all reproduces the originally edited text", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const get = (): Promise<string> =>
|
||||
page.evaluate((r: string) => {
|
||||
const x = (window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((y) => y.id === r);
|
||||
return x ? (x.text as string) : "(gone)";
|
||||
}, id);
|
||||
await caretEndInsert(page, id, " UNIQ");
|
||||
await blur(page, id);
|
||||
const edited = await get();
|
||||
await page.evaluate(() =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.resetAll(),
|
||||
);
|
||||
await page.waitForTimeout(400);
|
||||
// Redo until the button is disabled. The edit + its auto-reflow coalesce
|
||||
// into ONE undo/redo step, so this is typically a single click - clicking
|
||||
// a disabled button would hang, so stop once redo is exhausted.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const redoBtn = page.getByTestId("v2-redo");
|
||||
if (await redoBtn.isDisabled()) break;
|
||||
await redoBtn.click();
|
||||
await page.waitForTimeout(120);
|
||||
}
|
||||
const redone = await get();
|
||||
expect(
|
||||
redone,
|
||||
"redo must reproduce the exact text the original edit produced",
|
||||
).toBe(edited);
|
||||
});
|
||||
|
||||
// ISSUE / LIMITATION: editing embedded / subset / form-xobject text used to
|
||||
// re-font the run to base-14 Helvetica even when the edit only adds chars the
|
||||
// subset already embeds. Appending chars present in the source ("test", all
|
||||
// of which appear in "Subset font sample") must keep the subset font - the
|
||||
// reuse is safe because those glyphs are proven present, and emitTextLine
|
||||
// falls back to base-14 only if a reused glyph fails to render.
|
||||
test("editing a subset-font run keeps a non-base-14 font", async ({
|
||||
page,
|
||||
}) => {
|
||||
await open(page, SUBSET, 0);
|
||||
const id = await findId(page, 0, "Subset font sample");
|
||||
await caretEndInsert(page, id, "test");
|
||||
await blur(page, id);
|
||||
const g = await glyphs(page, 0, id);
|
||||
expect(
|
||||
g.fontId.startsWith("base14:"),
|
||||
"subset edit flips to Helvetica",
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// ISSUE / UX: a single Enter-then-type produces several `input` events, so
|
||||
// several undo steps are needed to revert one logical edit. One undo should
|
||||
// suffice.
|
||||
test("one undo reverts a single Enter+type action", async ({ page }) => {
|
||||
await open(page, SAMPLE, 1);
|
||||
const id = await findId(page, 1, "Stirling\\s+PDF\\s+is\\s+a\\s+robust");
|
||||
const before = await page.evaluate(
|
||||
(rid: string) =>
|
||||
(window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)!.text as string,
|
||||
id,
|
||||
);
|
||||
await caretEndInsert(page, id, "\n");
|
||||
await caretEndInsert(page, id, "Z");
|
||||
await page.getByTestId("v2-undo").click();
|
||||
// Poll for the revert rather than a fixed wait - the undo's store update can
|
||||
// lag the click under load, which made a single fixed timeout flaky.
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
page.evaluate(
|
||||
(rid: string) =>
|
||||
((window as unknown as V2TestWindow).__v2_editor_store.doc
|
||||
.page(1)
|
||||
.runs.find((x) => x.id === rid)?.text ?? null) as string | null,
|
||||
id,
|
||||
),
|
||||
{ timeout: 6000, message: "one undo should fully revert Enter+type" },
|
||||
)
|
||||
.toBe(before);
|
||||
});
|
||||
|
||||
// ISSUE: opening an ENCRYPTED PDF fails silently - the editor shows "No
|
||||
// document loaded" with no error message and no password prompt. It now
|
||||
// prompts for the password (client-side decrypt) instead of dead-ending.
|
||||
test("opening an encrypted PDF surfaces an error or password prompt", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
|
||||
await page
|
||||
.locator('[data-testid="v2-file-input"]')
|
||||
.setInputFiles(
|
||||
path.join(import.meta.dirname, "../test-fixtures/encrypted.pdf"),
|
||||
);
|
||||
await page.waitForTimeout(2500);
|
||||
const loaded = await page.getByTestId("v2-page-0").count();
|
||||
const error = await page.getByTestId("v2-error").count();
|
||||
const prompt = await page.getByTestId("v2-password-modal").count();
|
||||
expect(
|
||||
loaded > 0 || error > 0 || prompt > 0,
|
||||
"an encrypted PDF must either open or tell the user why it can't",
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// ISSUE: opening a CORRUPTED PDF fails silently - same "No document loaded"
|
||||
// with no error feedback.
|
||||
test("opening a corrupted PDF surfaces an error", async ({ page }) => {
|
||||
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
|
||||
await expect(page.getByTestId("v2-root")).toBeVisible({ timeout: 15_000 });
|
||||
await page
|
||||
.locator('[data-testid="v2-file-input"]')
|
||||
.setInputFiles(
|
||||
path.join(import.meta.dirname, "../test-fixtures/corrupted.pdf"),
|
||||
);
|
||||
await page.waitForTimeout(2500);
|
||||
const loaded = await page.getByTestId("v2-page-0").count();
|
||||
const error = await page.getByTestId("v2-error").count();
|
||||
expect(
|
||||
loaded > 0 || error > 0,
|
||||
"a corrupted PDF must surface an error instead of failing silently",
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user