Compare commits

..
1 Commits
Author SHA1 Message Date
Anthony Stirling 71c4419b7e sso in server plan 2025-12-03 13:11:32 +00:00
308 changed files with 2752 additions and 14148 deletions
+14 -3
View File
@@ -52,6 +52,7 @@ jobs:
core.setOutput('repository', pr.head.repo.full_name); core.setOutput('repository', pr.head.repo.full_name);
core.setOutput('ref', pr.head.ref); core.setOutput('ref', pr.head.ref);
core.setOutput('is_fork', String(pr.head.repo.fork)); core.setOutput('is_fork', String(pr.head.repo.fork));
core.setOutput('base_ref', pr.base.ref);
core.setOutput('author', pr.user.login); core.setOutput('author', pr.user.login);
core.setOutput('state', pr.state); core.setOutput('state', pr.state);
@@ -64,6 +65,10 @@ jobs:
IS_FORK: ${{ steps.resolve.outputs.is_fork }} IS_FORK: ${{ steps.resolve.outputs.is_fork }}
# nur bei workflow_dispatch gesetzt: # nur bei workflow_dispatch gesetzt:
ALLOW_FORK_INPUT: ${{ inputs.allow_fork }} ALLOW_FORK_INPUT: ${{ inputs.allow_fork }}
# für Auto-PR-Logik:
PR_TITLE: ${{ github.event.pull_request.title }}
PR_BRANCH: ${{ github.event.pull_request.head.ref }}
PR_BASE: ${{ steps.resolve.outputs.base_ref }}
PR_AUTHOR: ${{ steps.resolve.outputs.author }} PR_AUTHOR: ${{ steps.resolve.outputs.author }}
run: | run: |
set -e set -e
@@ -84,8 +89,14 @@ jobs:
else else
auth_users=("Frooodle" "sf298" "Ludy87" "LaserKaspar" "sbplat" "reecebrowne" "DarioGii" "ConnorYoh" "EthanHealy01" "jbrunton96" "balazs-szucs") auth_users=("Frooodle" "sf298" "Ludy87" "LaserKaspar" "sbplat" "reecebrowne" "DarioGii" "ConnorYoh" "EthanHealy01" "jbrunton96" "balazs-szucs")
is_auth=false; for u in "${auth_users[@]}"; do [ "$u" = "$PR_AUTHOR" ] && is_auth=true && break; done is_auth=false; for u in "${auth_users[@]}"; do [ "$u" = "$PR_AUTHOR" ] && is_auth=true && break; done
if [ "$is_auth" = true ]; then if [ "$PR_BASE" = "V2" ] && [ "$is_auth" = true ]; then
should=true should=true
else
title_has_v2=false; echo "$PR_TITLE" | grep -qiE 'v2|version.?2|version.?two' && title_has_v2=true
branch_has_kw=false; echo "$PR_BRANCH" | grep -qiE 'v2|react' && branch_has_kw=true
if [ "$is_auth" = true ] && { [ "$title_has_v2" = true ] || [ "$branch_has_kw" = true ]; }; then
should=true
fi
fi fi
fi fi
@@ -163,7 +174,7 @@ jobs:
owner, owner,
repo, repo,
issue_number: prNumber, issue_number: prNumber,
body: `🚀 **Auto-deploying V2 version** for PR #${prNumber}...\n\n_This is an automated deployment for approved V2 contributors._\n\n⚠️ **Note:** If new commits are pushed during deployment, this build will be cancelled and replaced with the latest version.` body: `🚀 **Auto-deploying V2 version** for PR #${prNumber}...\n\n_This is an automated deployment triggered by V2/version2 keywords in the PR title or V2/React keywords in the branch name._\n\n⚠️ **Note:** If new commits are pushed during deployment, this build will be cancelled and replaced with the latest version.`
}); });
return newComment.id; return newComment.id;
@@ -383,7 +394,7 @@ jobs:
`🔗 **Direct Test URL (non-SSL)** [${deploymentUrl}](${deploymentUrl})\n\n` + `🔗 **Direct Test URL (non-SSL)** [${deploymentUrl}](${deploymentUrl})\n\n` +
`🔐 **Secure HTTPS URL**: [${httpsUrl}](${httpsUrl})\n\n` + `🔐 **Secure HTTPS URL**: [${httpsUrl}](${httpsUrl})\n\n` +
`_This deployment will be automatically cleaned up when the PR is closed._\n\n` + `_This deployment will be automatically cleaned up when the PR is closed._\n\n` +
`🔄 **Auto-deployed** for approved V2 contributors.`; `🔄 **Auto-deployed** because PR title or branch name contains V2/version2/React keywords.`;
await github.rest.issues.createComment({ await github.rest.issues.createComment({
owner, owner,
@@ -14,7 +14,6 @@ jobs:
permissions: permissions:
issues: write issues: write
if: | if: |
vars.CI_PROFILE != 'lite' &&
github.event.issue.pull_request && github.event.issue.pull_request &&
( (
contains(github.event.comment.body, 'prdeploy') || contains(github.event.comment.body, 'prdeploy') ||
+2 -15
View File
@@ -262,13 +262,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
include: docker-rev: ["docker/embedded/Dockerfile", "docker/embedded/Dockerfile.ultra-lite", "docker/embedded/Dockerfile.fat"]
- docker-rev: docker/embedded/Dockerfile
artifact-suffix: Dockerfile
- docker-rev: docker/embedded/Dockerfile.ultra-lite
artifact-suffix: Dockerfile.ultra-lite
- docker-rev: docker/embedded/Dockerfile.fat
artifact-suffix: Dockerfile.fat
steps: steps:
- name: Harden Runner - name: Harden Runner
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1 uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
@@ -278,13 +272,6 @@ jobs:
- name: Checkout Repository - name: Checkout Repository
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- name: Free disk space on runner
run: |
echo "Disk space before cleanup:" && df -h
sudo rm -rf /usr/share/dotnet /opt/ghc /usr/local/lib/android /usr/local/share/boost
docker system prune -af || true
echo "Disk space after cleanup:" && df -h
- name: Set up JDK 17 - name: Set up JDK 17
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0 uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with: with:
@@ -326,7 +313,7 @@ jobs:
if: always() if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with: with:
name: reports-docker-${{ matrix.artifact-suffix }} name: reports-docker-${{ matrix.docker-rev }}
path: | path: |
build/reports/tests/ build/reports/tests/
build/test-results/ build/test-results/
-1
View File
@@ -31,7 +31,6 @@ permissions:
jobs: jobs:
determine-matrix: determine-matrix:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs: outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }} matrix: ${{ steps.set-matrix.outputs.matrix }}
-1
View File
@@ -24,7 +24,6 @@ permissions:
jobs: jobs:
push: push:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-24.04-8core runs-on: ubuntu-24.04-8core
permissions: permissions:
packages: write packages: write
-1
View File
@@ -24,7 +24,6 @@ permissions:
jobs: jobs:
push: push:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
packages: write packages: write
-1
View File
@@ -17,7 +17,6 @@ permissions: read-all
jobs: jobs:
analysis: analysis:
if: ${{ vars.CI_PROFILE != 'lite' }}
name: Scorecard analysis name: Scorecard analysis
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
-1
View File
@@ -27,7 +27,6 @@ permissions:
jobs: jobs:
sonarqube: sonarqube:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Harden Runner - name: Harden Runner
-1
View File
@@ -10,7 +10,6 @@ permissions:
jobs: jobs:
stale: stale:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
issues: write issues: write
-1
View File
@@ -23,7 +23,6 @@ permissions:
jobs: jobs:
push: push:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Harden Runner - name: Harden Runner
-3
View File
@@ -28,7 +28,6 @@ permissions:
jobs: jobs:
determine-matrix: determine-matrix:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs: outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }} matrix: ${{ steps.set-matrix.outputs.matrix }}
@@ -637,8 +636,6 @@ jobs:
if [ "${{ needs.build.result }}" = "success" ]; then if [ "${{ needs.build.result }}" = "success" ]; then
echo "✅ All Tauri builds completed successfully!" echo "✅ All Tauri builds completed successfully!"
echo "Artifacts are ready for distribution." echo "Artifacts are ready for distribution."
elif [ "${{ needs.build.result }}" = "skipped" ]; then
echo "⏭️ Tauri builds skipped (CI lite mode enabled)"
else else
echo "❌ Some Tauri builds failed." echo "❌ Some Tauri builds failed."
echo "Please check the logs and fix any issues." echo "Please check the logs and fix any issues."
-1
View File
@@ -21,7 +21,6 @@ permissions:
jobs: jobs:
deploy: deploy:
if: ${{ vars.CI_PROFILE != 'lite' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Harden Runner - name: Harden Runner
@@ -491,9 +491,6 @@ public class EndpointConfiguration {
addEndpointToGroup("Ghostscript", "repair"); addEndpointToGroup("Ghostscript", "repair");
addEndpointToGroup("Ghostscript", "compress-pdf"); addEndpointToGroup("Ghostscript", "compress-pdf");
/* ImageMagick */
addEndpointToGroup("ImageMagick", "compress-pdf");
/* tesseract */ /* tesseract */
addEndpointToGroup("tesseract", "ocr-pdf"); addEndpointToGroup("tesseract", "ocr-pdf");
@@ -577,7 +574,6 @@ public class EndpointConfiguration {
|| "Javascript".equals(group) || "Javascript".equals(group)
|| "Weasyprint".equals(group) || "Weasyprint".equals(group)
|| "Pdftohtml".equals(group) || "Pdftohtml".equals(group)
|| "ImageMagick".equals(group)
|| "rar".equals(group); || "rar".equals(group);
} }
@@ -68,7 +68,6 @@ public class ApplicationProperties {
private AutoPipeline autoPipeline = new AutoPipeline(); private AutoPipeline autoPipeline = new AutoPipeline();
private ProcessExecutor processExecutor = new ProcessExecutor(); private ProcessExecutor processExecutor = new ProcessExecutor();
private PdfEditor pdfEditor = new PdfEditor();
@Bean @Bean
public PropertySource<?> dynamicYamlPropertySource(ConfigurableEnvironment environment) public PropertySource<?> dynamicYamlPropertySource(ConfigurableEnvironment environment)
@@ -101,46 +100,6 @@ public class ApplicationProperties {
private String outputFolder; private String outputFolder;
} }
@Data
public static class PdfEditor {
private Cache cache = new Cache();
private FontNormalization fontNormalization = new FontNormalization();
private CffConverter cffConverter = new CffConverter();
private Type3 type3 = new Type3();
private String fallbackFont = "classpath:/static/fonts/NotoSans-Regular.ttf";
@Data
public static class Cache {
private long maxBytes = -1;
private int maxPercent = 20;
}
@Data
public static class FontNormalization {
private boolean enabled = false;
}
@Data
public static class CffConverter {
private boolean enabled = true;
private String method = "python";
private String pythonCommand = "/opt/venv/bin/python3";
private String pythonScript = "/scripts/convert_cff_to_ttf.py";
private String fontforgeCommand = "fontforge";
}
@Data
public static class Type3 {
private Library library = new Library();
@Data
public static class Library {
private boolean enabled = true;
private String index = "classpath:/type3/library/index.json";
}
}
}
@Data @Data
public static class Legal { public static class Legal {
private String termsAndConditions; private String termsAndConditions;
@@ -153,6 +112,7 @@ public class ApplicationProperties {
@Data @Data
public static class Security { public static class Security {
private Boolean enableLogin; private Boolean enableLogin;
private Boolean csrfDisabled;
private InitialLogin initialLogin = new InitialLogin(); private InitialLogin initialLogin = new InitialLogin();
private OAUTH2 oauth2 = new OAUTH2(); private OAUTH2 oauth2 = new OAUTH2();
private SAML2 saml2 = new SAML2(); private SAML2 saml2 = new SAML2();
@@ -398,7 +358,6 @@ public class ApplicationProperties {
private Boolean enableAnalytics; private Boolean enableAnalytics;
private Boolean enablePosthog; private Boolean enablePosthog;
private Boolean enableScarf; private Boolean enableScarf;
private Boolean enableDesktopInstallSlide;
private Datasource datasource; private Datasource datasource;
private Boolean disableSanitize; private Boolean disableSanitize;
private int maxDPI; private int maxDPI;
@@ -409,12 +368,10 @@ public class ApplicationProperties {
private TempFileManagement tempFileManagement = new TempFileManagement(); private TempFileManagement tempFileManagement = new TempFileManagement();
private DatabaseBackup databaseBackup = new DatabaseBackup(); private DatabaseBackup databaseBackup = new DatabaseBackup();
private List<String> corsAllowedOrigins = new ArrayList<>(); private List<String> corsAllowedOrigins = new ArrayList<>();
private String backendUrl; // Backend base URL for SAML/OAuth/API callbacks (e.g. private String
// 'http://localhost:8080', 'https://api.example.com'). Required for frontendUrl; // Base URL for frontend (used for invite links, etc.). If not set,
// SSO.
private String frontendUrl; // Frontend URL for invite email links (e.g.
// 'https://app.example.com'). If not set, falls back to backendUrl. // falls back to backend URL.
public boolean isAnalyticsEnabled() { public boolean isAnalyticsEnabled() {
return this.getEnableAnalytics() != null && this.getEnableAnalytics(); return this.getEnableAnalytics() != null && this.getEnableAnalytics();
@@ -579,7 +536,6 @@ public class ApplicationProperties {
@ToString.Exclude private String key; @ToString.Exclude private String key;
private String UUID; private String UUID;
private String appVersion; private String appVersion;
private Boolean isNewServer;
} }
// TODO: Remove post migration // TODO: Remove post migration
@@ -619,16 +575,6 @@ public class ApplicationProperties {
private String username; private String username;
@ToString.Exclude private String password; @ToString.Exclude private String password;
private String from; private String from;
// STARTTLS upgrades a plain SMTP connection to TLS after connecting (RFC 3207)
private Boolean startTlsEnable = true;
private Boolean startTlsRequired;
// SSL/TLS wrapper for implicit TLS (typically port 465)
private Boolean sslEnable;
// Hostnames or patterns (e.g., "smtp.example.com" or "*") to trust for TLS certificates;
// defaults to "*" (trust all) when not set
private String sslTrust;
// Enables hostname verification for TLS connections
private Boolean sslCheckServerIdentity;
} }
@Data @Data
@@ -697,7 +643,6 @@ public class ApplicationProperties {
private int weasyPrintSessionLimit; private int weasyPrintSessionLimit;
private int installAppSessionLimit; private int installAppSessionLimit;
private int calibreSessionLimit; private int calibreSessionLimit;
private int imageMagickSessionLimit;
private int qpdfSessionLimit; private int qpdfSessionLimit;
private int tesseractSessionLimit; private int tesseractSessionLimit;
private int ghostscriptSessionLimit; private int ghostscriptSessionLimit;
@@ -735,10 +680,6 @@ public class ApplicationProperties {
return calibreSessionLimit > 0 ? calibreSessionLimit : 1; return calibreSessionLimit > 0 ? calibreSessionLimit : 1;
} }
public int getImageMagickSessionLimit() {
return imageMagickSessionLimit > 0 ? imageMagickSessionLimit : 4;
}
public int getGhostscriptSessionLimit() { public int getGhostscriptSessionLimit() {
return ghostscriptSessionLimit > 0 ? ghostscriptSessionLimit : 8; return ghostscriptSessionLimit > 0 ? ghostscriptSessionLimit : 8;
} }
@@ -768,8 +709,6 @@ public class ApplicationProperties {
@JsonProperty("calibretimeoutMinutes") @JsonProperty("calibretimeoutMinutes")
private long calibreTimeoutMinutes; private long calibreTimeoutMinutes;
private long imageMagickTimeoutMinutes;
private long tesseractTimeoutMinutes; private long tesseractTimeoutMinutes;
private long qpdfTimeoutMinutes; private long qpdfTimeoutMinutes;
private long ghostscriptTimeoutMinutes; private long ghostscriptTimeoutMinutes;
@@ -807,10 +746,6 @@ public class ApplicationProperties {
return calibreTimeoutMinutes > 0 ? calibreTimeoutMinutes : 30; return calibreTimeoutMinutes > 0 ? calibreTimeoutMinutes : 30;
} }
public long getImageMagickTimeoutMinutes() {
return imageMagickTimeoutMinutes > 0 ? imageMagickTimeoutMinutes : 30;
}
public long getGhostscriptTimeoutMinutes() { public long getGhostscriptTimeoutMinutes() {
return ghostscriptTimeoutMinutes > 0 ? ghostscriptTimeoutMinutes : 30; return ghostscriptTimeoutMinutes > 0 ? ghostscriptTimeoutMinutes : 30;
} }
@@ -1,12 +0,0 @@
package stirling.software.common.service;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
public interface LineArtConversionService {
PDImageXObject convertImageToLineArt(
PDDocument doc, PDImageXObject originalImage, double threshold, int edgeLevel)
throws IOException;
}
@@ -254,7 +254,10 @@ public class PostHogService {
properties, properties,
"security_enableLogin", "security_enableLogin",
applicationProperties.getSecurity().getEnableLogin()); applicationProperties.getSecurity().getEnableLogin());
addIfNotEmpty(properties, "security_csrfDisabled", true); addIfNotEmpty(
properties,
"security_csrfDisabled",
applicationProperties.getSecurity().getCsrfDisabled());
addIfNotEmpty( addIfNotEmpty(
properties, properties,
"security_loginAttemptCount", "security_loginAttemptCount",
@@ -86,11 +86,6 @@ public class ProcessExecutor {
.getProcessExecutor() .getProcessExecutor()
.getSessionLimit() .getSessionLimit()
.getCalibreSessionLimit(); .getCalibreSessionLimit();
case IMAGEMAGICK ->
applicationProperties
.getProcessExecutor()
.getSessionLimit()
.getImageMagickSessionLimit();
case GHOSTSCRIPT -> case GHOSTSCRIPT ->
applicationProperties applicationProperties
.getProcessExecutor() .getProcessExecutor()
@@ -146,11 +141,6 @@ public class ProcessExecutor {
.getProcessExecutor() .getProcessExecutor()
.getTimeoutMinutes() .getTimeoutMinutes()
.getCalibreTimeoutMinutes(); .getCalibreTimeoutMinutes();
case IMAGEMAGICK ->
applicationProperties
.getProcessExecutor()
.getTimeoutMinutes()
.getImageMagickTimeoutMinutes();
case GHOSTSCRIPT -> case GHOSTSCRIPT ->
applicationProperties applicationProperties
.getProcessExecutor() .getProcessExecutor()
@@ -311,7 +301,6 @@ public class ProcessExecutor {
WEASYPRINT, WEASYPRINT,
INSTALL_APP, INSTALL_APP,
CALIBRE, CALIBRE,
IMAGEMAGICK,
TESSERACT, TESSERACT,
QPDF, QPDF,
GHOSTSCRIPT, GHOSTSCRIPT,
@@ -26,7 +26,6 @@ public class RequestUriUtils {
|| normalizedUri.startsWith("/public/") || normalizedUri.startsWith("/public/")
|| normalizedUri.startsWith("/pdfjs/") || normalizedUri.startsWith("/pdfjs/")
|| normalizedUri.startsWith("/pdfjs-legacy/") || normalizedUri.startsWith("/pdfjs-legacy/")
|| normalizedUri.startsWith("/pdfium/")
|| normalizedUri.startsWith("/assets/") || normalizedUri.startsWith("/assets/")
|| normalizedUri.startsWith("/locales/") || normalizedUri.startsWith("/locales/")
|| normalizedUri.startsWith("/Login/") || normalizedUri.startsWith("/Login/")
@@ -62,8 +61,7 @@ public class RequestUriUtils {
|| normalizedUri.endsWith(".css") || normalizedUri.endsWith(".css")
|| normalizedUri.endsWith(".mjs") || normalizedUri.endsWith(".mjs")
|| normalizedUri.endsWith(".html") || normalizedUri.endsWith(".html")
|| normalizedUri.endsWith(".toml") || normalizedUri.endsWith(".toml");
|| normalizedUri.endsWith(".wasm");
} }
public static boolean isFrontendRoute(String contextPath, String requestURI) { public static boolean isFrontendRoute(String contextPath, String requestURI) {
@@ -127,13 +125,11 @@ public class RequestUriUtils {
|| requestURI.endsWith("popularity.txt") || requestURI.endsWith("popularity.txt")
|| requestURI.endsWith(".js") || requestURI.endsWith(".js")
|| requestURI.endsWith(".toml") || requestURI.endsWith(".toml")
|| requestURI.endsWith(".wasm")
|| requestURI.contains("swagger") || requestURI.contains("swagger")
|| requestURI.startsWith("/api/v1/info") || requestURI.startsWith("/api/v1/info")
|| requestURI.startsWith("/site.webmanifest") || requestURI.startsWith("/site.webmanifest")
|| requestURI.startsWith("/fonts") || requestURI.startsWith("/fonts")
|| requestURI.startsWith("/pdfjs") || requestURI.startsWith("/pdfjs"));
|| requestURI.startsWith("/pdfium"));
} }
/** /**
@@ -166,9 +162,10 @@ public class RequestUriUtils {
// enableLogin) // enableLogin)
|| trimmedUri.startsWith( || trimmedUri.startsWith(
"/api/v1/ui-data/footer-info") // Public footer configuration "/api/v1/ui-data/footer-info") // Public footer configuration
|| trimmedUri.startsWith("/v1/api-docs")
|| trimmedUri.startsWith("/api/v1/invite/validate") || trimmedUri.startsWith("/api/v1/invite/validate")
|| trimmedUri.startsWith("/api/v1/invite/accept") || trimmedUri.startsWith("/api/v1/invite/accept")
|| trimmedUri.startsWith("/v1/api-docs"); || trimmedUri.contains("/v1/api-docs");
} }
private static String stripContextPath(String contextPath, String requestURI) { private static String stripContextPath(String contextPath, String requestURI) {
@@ -24,9 +24,6 @@ public class RequestUriUtilsTest {
assertTrue( assertTrue(
RequestUriUtils.isStaticResource("/pdfjs/pdf.worker.js"), RequestUriUtils.isStaticResource("/pdfjs/pdf.worker.js"),
"PDF.js files should be static"); "PDF.js files should be static");
assertTrue(
RequestUriUtils.isStaticResource("/pdfium/pdfium.wasm"),
"PDFium wasm should be static");
assertTrue( assertTrue(
RequestUriUtils.isStaticResource("/api/v1/info/status"), RequestUriUtils.isStaticResource("/api/v1/info/status"),
"API status should be static"); "API status should be static");
@@ -113,8 +110,7 @@ public class RequestUriUtilsTest {
"/downloads/document.png", "/downloads/document.png",
"/assets/brand.ico", "/assets/brand.ico",
"/any/path/with/image.svg", "/any/path/with/image.svg",
"/deep/nested/folder/icon.png", "/deep/nested/folder/icon.png"
"/pdfium/pdfium.wasm"
}) })
void testIsStaticResourceWithFileExtensions(String path) { void testIsStaticResourceWithFileExtensions(String path) {
assertTrue( assertTrue(
@@ -152,9 +148,6 @@ public class RequestUriUtilsTest {
assertFalse( assertFalse(
RequestUriUtils.isTrackableResource("/script.js"), RequestUriUtils.isTrackableResource("/script.js"),
"JS files should not be trackable"); "JS files should not be trackable");
assertFalse(
RequestUriUtils.isTrackableResource("/pdfium/pdfium.wasm"),
"PDFium wasm should not be trackable");
assertFalse( assertFalse(
RequestUriUtils.isTrackableResource("/swagger/index.html"), RequestUriUtils.isTrackableResource("/swagger/index.html"),
"Swagger files should not be trackable"); "Swagger files should not be trackable");
@@ -231,8 +224,7 @@ public class RequestUriUtilsTest {
"/api/v1/info/health", "/api/v1/info/health",
"/site.webmanifest", "/site.webmanifest",
"/fonts/roboto.woff", "/fonts/roboto.woff",
"/pdfjs/viewer.js", "/pdfjs/viewer.js"
"/pdfium/pdfium.wasm"
}) })
void testNonTrackableResources(String path) { void testNonTrackableResources(String path) {
assertFalse( assertFalse(
@@ -46,7 +46,6 @@ public class ExternalAppDepConfig {
put("qpdf", List.of("qpdf")); put("qpdf", List.of("qpdf"));
put("tesseract", List.of("tesseract")); put("tesseract", List.of("tesseract"));
put("rar", List.of("rar")); // Required for real CBR output put("rar", List.of("rar")); // Required for real CBR output
put("magick", List.of("ImageMagick"));
} }
}; };
} }
@@ -129,7 +128,6 @@ public class ExternalAppDepConfig {
checkDependencyAndDisableGroup("pdftohtml"); checkDependencyAndDisableGroup("pdftohtml");
checkDependencyAndDisableGroup(unoconvPath); checkDependencyAndDisableGroup(unoconvPath);
checkDependencyAndDisableGroup("rar"); checkDependencyAndDisableGroup("rar");
checkDependencyAndDisableGroup("magick");
// Special handling for Python/OpenCV dependencies // Special handling for Python/OpenCV dependencies
boolean pythonAvailable = isCommandAvailable("python3") || isCommandAvailable("python"); boolean pythonAvailable = isCommandAvailable("python3") || isCommandAvailable("python");
if (!pythonAvailable) { if (!pythonAvailable) {
@@ -34,6 +34,7 @@ public class InitialSetup {
public void init() throws IOException { public void init() throws IOException {
initUUIDKey(); initUUIDKey();
initSecretKey(); initSecretKey();
initEnableCSRFSecurity();
initLegalUrls(); initLegalUrls();
initSetAppVersion(); initSetAppVersion();
GeneralUtils.extractPipeline(); GeneralUtils.extractPipeline();
@@ -59,6 +60,18 @@ public class InitialSetup {
} }
} }
public void initEnableCSRFSecurity() throws IOException {
if (GeneralUtils.isVersionHigher(
"0.46.0", applicationProperties.getAutomaticallyGenerated().getAppVersion())) {
Boolean csrf = applicationProperties.getSecurity().getCsrfDisabled();
if (!csrf) {
GeneralUtils.saveKeyToSettings("security.csrfDisabled", false);
GeneralUtils.saveKeyToSettings("system.enableAnalytics", true);
applicationProperties.getSecurity().setCsrfDisabled(false);
}
}
}
public void initLegalUrls() throws IOException { public void initLegalUrls() throws IOException {
// Initialize Terms and Conditions // Initialize Terms and Conditions
String termsUrl = applicationProperties.getLegal().getTermsAndConditions(); String termsUrl = applicationProperties.getLegal().getTermsAndConditions();
@@ -82,7 +95,7 @@ public class InitialSetup {
isNewServer = isNewServer =
existingVersion == null existingVersion == null
|| existingVersion.isEmpty() || existingVersion.isEmpty()
|| "0.0.0".equals(existingVersion); || existingVersion.equals("0.0.0");
String appVersion = "0.0.0"; String appVersion = "0.0.0";
Resource resource = new ClassPathResource("version.properties"); Resource resource = new ClassPathResource("version.properties");
@@ -94,7 +107,6 @@ public class InitialSetup {
} }
GeneralUtils.saveKeyToSettings("AutomaticallyGenerated.appVersion", appVersion); GeneralUtils.saveKeyToSettings("AutomaticallyGenerated.appVersion", appVersion);
applicationProperties.getAutomaticallyGenerated().setAppVersion(appVersion); applicationProperties.getAutomaticallyGenerated().setAppVersion(appVersion);
applicationProperties.getAutomaticallyGenerated().setIsNewServer(isNewServer);
} }
public static boolean isNewServer() { public static boolean isNewServer() {
@@ -62,15 +62,10 @@ public class OpenApiConfig {
// Add server configuration from environment variable // Add server configuration from environment variable
String swaggerServerUrl = System.getenv("SWAGGER_SERVER_URL"); String swaggerServerUrl = System.getenv("SWAGGER_SERVER_URL");
Server server;
if (swaggerServerUrl != null && !swaggerServerUrl.trim().isEmpty()) { if (swaggerServerUrl != null && !swaggerServerUrl.trim().isEmpty()) {
server = new Server().url(swaggerServerUrl).description("API Server"); Server server = new Server().url(swaggerServerUrl).description("API Server");
} else { openAPI.addServersItem(server);
// Use relative path so Swagger uses the current browser origin to avoid CORS issues
// when accessing via different ports
server = new Server().url("/").description("Current Server");
} }
openAPI.addServersItem(server);
// Add ErrorResponse schema to components // Add ErrorResponse schema to components
Schema<?> errorResponseSchema = Schema<?> errorResponseSchema =
@@ -1,14 +1,10 @@
package stirling.software.SPDF.config; package stirling.software.SPDF.config;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -29,20 +25,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
registry.addInterceptor(endpointInterceptor); registry.addInterceptor(endpointInterceptor);
} }
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Cache hashed assets (JS/CSS with content hashes) for 1 year
// These files have names like index-ChAS4tCC.js that change when content changes
registry.addResourceHandler("/assets/**")
.addResourceLocations("classpath:/static/assets/")
.setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic());
// Don't cache index.html - it needs to be fresh to reference latest hashed assets
registry.addResourceHandler("/index.html")
.addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.noCache().mustRevalidate());
}
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
// Check if running in Tauri mode // Check if running in Tauri mode
@@ -124,6 +124,7 @@ public class SettingsController {
ApplicationProperties.Security security = applicationProperties.getSecurity(); ApplicationProperties.Security security = applicationProperties.getSecurity();
settings.put("enableLogin", security.getEnableLogin()); settings.put("enableLogin", security.getEnableLogin());
settings.put("csrfDisabled", security.getCsrfDisabled());
settings.put("loginMethod", security.getLoginMethod()); settings.put("loginMethod", security.getLoginMethod());
settings.put("loginAttemptCount", security.getLoginAttemptCount()); settings.put("loginAttemptCount", security.getLoginAttemptCount());
settings.put("loginResetTimeMinutes", security.getLoginResetTimeMinutes()); settings.put("loginResetTimeMinutes", security.getLoginResetTimeMinutes());
@@ -158,6 +159,12 @@ public class SettingsController {
.getSecurity() .getSecurity()
.setEnableLogin((Boolean) settings.get("enableLogin")); .setEnableLogin((Boolean) settings.get("enableLogin"));
} }
if (settings.containsKey("csrfDisabled")) {
GeneralUtils.saveKeyToSettings("security.csrfDisabled", settings.get("csrfDisabled"));
applicationProperties
.getSecurity()
.setCsrfDisabled((Boolean) settings.get("csrfDisabled"));
}
if (settings.containsKey("loginMethod")) { if (settings.containsKey("loginMethod")) {
GeneralUtils.saveKeyToSettings("security.loginMethod", settings.get("loginMethod")); GeneralUtils.saveKeyToSettings("security.loginMethod", settings.get("loginMethod"));
applicationProperties applicationProperties
@@ -1,60 +0,0 @@
package stirling.software.SPDF.controller.api.converters;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.exception.CacheUnavailableException;
@ControllerAdvice(assignableTypes = ConvertPdfJsonController.class)
@Slf4j
@RequiredArgsConstructor
public class ConvertPdfJsonExceptionHandler {
private final ObjectMapper objectMapper;
@ExceptionHandler(CacheUnavailableException.class)
@ResponseBody
public ResponseEntity<byte[]> handleCacheUnavailable(CacheUnavailableException ex) {
try {
byte[] body =
objectMapper.writeValueAsBytes(
java.util.Map.of(
"error", "cache_unavailable",
"action", "reupload",
"message", ex.getMessage()));
return ResponseEntity.status(HttpStatus.GONE)
.contentType(MediaType.APPLICATION_JSON)
.body(body);
} catch (Exception e) {
log.warn("Failed to serialize cache_unavailable response", e);
var fallbackBody =
java.util.Map.of(
"error", "cache_unavailable",
"action", "reupload",
"message", String.valueOf(ex.getMessage()));
try {
return ResponseEntity.status(HttpStatus.GONE)
.contentType(MediaType.APPLICATION_JSON)
.body(objectMapper.writeValueAsBytes(fallbackBody));
} catch (Exception ignored) {
// Truly last-ditch fallback
return ResponseEntity.status(HttpStatus.GONE)
.contentType(MediaType.APPLICATION_JSON)
.body(
"{\"error\":\"cache_unavailable\",\"action\":\"reupload\",\"message\":\"Cache unavailable\"}"
.getBytes(StandardCharsets.UTF_8));
}
}
}
}
@@ -28,13 +28,10 @@ import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -47,7 +44,6 @@ import stirling.software.SPDF.model.api.misc.OptimizePdfRequest;
import stirling.software.common.annotations.AutoJobPostMapping; import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.MiscApi; import stirling.software.common.annotations.api.MiscApi;
import stirling.software.common.service.CustomPDFDocumentFactory; import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.LineArtConversionService;
import stirling.software.common.util.ExceptionUtils; import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils; import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.ProcessExecutor; import stirling.software.common.util.ProcessExecutor;
@@ -62,9 +58,6 @@ public class CompressController {
private final CustomPDFDocumentFactory pdfDocumentFactory; private final CustomPDFDocumentFactory pdfDocumentFactory;
private final EndpointConfiguration endpointConfiguration; private final EndpointConfiguration endpointConfiguration;
@Autowired(required = false)
private LineArtConversionService lineArtConversionService;
private boolean isQpdfEnabled() { private boolean isQpdfEnabled() {
return endpointConfiguration.isGroupEnabled("qpdf"); return endpointConfiguration.isGroupEnabled("qpdf");
} }
@@ -73,10 +66,6 @@ public class CompressController {
return endpointConfiguration.isGroupEnabled("Ghostscript"); return endpointConfiguration.isGroupEnabled("Ghostscript");
} }
private boolean isImageMagickEnabled() {
return endpointConfiguration.isGroupEnabled("ImageMagick");
}
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@@ -671,9 +660,6 @@ public class CompressController {
Integer optimizeLevel = request.getOptimizeLevel(); Integer optimizeLevel = request.getOptimizeLevel();
String expectedOutputSizeString = request.getExpectedOutputSize(); String expectedOutputSizeString = request.getExpectedOutputSize();
Boolean convertToGrayscale = request.getGrayscale(); Boolean convertToGrayscale = request.getGrayscale();
Boolean convertToLineArt = request.getLineArt();
Double lineArtThreshold = request.getLineArtThreshold();
Integer lineArtEdgeLevel = request.getLineArtEdgeLevel();
if (expectedOutputSizeString == null && optimizeLevel == null) { if (expectedOutputSizeString == null && optimizeLevel == null) {
throw new Exception("Both expected output size and optimize level are not specified"); throw new Exception("Both expected output size and optimize level are not specified");
} }
@@ -703,26 +689,6 @@ public class CompressController {
optimizeLevel = determineOptimizeLevel(sizeReductionRatio); optimizeLevel = determineOptimizeLevel(sizeReductionRatio);
} }
if (Boolean.TRUE.equals(convertToLineArt)) {
if (lineArtConversionService == null) {
throw new ResponseStatusException(
HttpStatus.FORBIDDEN,
"Line art conversion is unavailable - ImageMagick service not found");
}
if (!isImageMagickEnabled()) {
throw new IOException(
"ImageMagick is not enabled but line art conversion was requested");
}
double thresholdValue =
lineArtThreshold == null
? 55d
: Math.min(100d, Math.max(0d, lineArtThreshold));
int edgeLevel =
lineArtEdgeLevel == null ? 1 : Math.min(3, Math.max(1, lineArtEdgeLevel));
currentFile =
applyLineArtConversion(currentFile, tempFiles, thresholdValue, edgeLevel);
}
boolean sizeMet = false; boolean sizeMet = false;
boolean imageCompressionApplied = false; boolean imageCompressionApplied = false;
boolean externalCompressionApplied = false; boolean externalCompressionApplied = false;
@@ -844,75 +810,6 @@ public class CompressController {
} }
} }
private Path applyLineArtConversion(
Path currentFile, List<Path> tempFiles, double threshold, int edgeLevel)
throws IOException {
Path lineArtFile = Files.createTempFile("lineart_output_", ".pdf");
tempFiles.add(lineArtFile);
try (PDDocument doc = pdfDocumentFactory.load(currentFile.toFile())) {
Map<String, List<ImageReference>> uniqueImages = findImages(doc);
CompressionStats stats = new CompressionStats();
stats.uniqueImagesCount = uniqueImages.size();
calculateImageStats(uniqueImages, stats);
Map<String, PDImageXObject> convertedImages =
createLineArtImages(doc, uniqueImages, stats, threshold, edgeLevel);
replaceImages(doc, uniqueImages, convertedImages, stats);
log.info(
"Applied line art conversion to {} unique images ({} total references)",
stats.uniqueImagesCount,
stats.totalImages);
doc.save(lineArtFile.toString());
return lineArtFile;
}
}
private Map<String, PDImageXObject> createLineArtImages(
PDDocument doc,
Map<String, List<ImageReference>> uniqueImages,
CompressionStats stats,
double threshold,
int edgeLevel)
throws IOException {
Map<String, PDImageXObject> convertedImages = new HashMap<>();
for (Entry<String, List<ImageReference>> entry : uniqueImages.entrySet()) {
String imageHash = entry.getKey();
List<ImageReference> references = entry.getValue();
if (references.isEmpty()) continue;
PDImageXObject originalImage = getOriginalImage(doc, references.get(0));
int originalSize = (int) originalImage.getCOSObject().getLength();
stats.totalOriginalBytes += originalSize;
PDImageXObject converted =
lineArtConversionService.convertImageToLineArt(
doc, originalImage, threshold, edgeLevel);
convertedImages.put(imageHash, converted);
stats.compressedImages++;
int convertedSize = (int) converted.getCOSObject().getLength();
stats.totalCompressedBytes += convertedSize * references.size();
double reductionPercentage = 100.0 - ((convertedSize * 100.0) / originalSize);
log.info(
"Image hash {}: Line art conversion {} → {} (reduced by {}%)",
imageHash,
GeneralUtils.formatBytes(originalSize),
GeneralUtils.formatBytes(convertedSize),
String.format("%.1f", reductionPercentage));
}
return convertedImages;
}
// Run Ghostscript compression // Run Ghostscript compression
private void applyGhostscriptCompression( private void applyGhostscriptCompression(
OptimizePdfRequest request, int optimizeLevel, Path currentFile, List<Path> tempFiles) OptimizePdfRequest request, int optimizeLevel, Path currentFile, List<Path> tempFiles)
@@ -74,7 +74,6 @@ public class ConfigController {
configData.put("appNameNavbar", applicationProperties.getUi().getAppNameNavbar()); configData.put("appNameNavbar", applicationProperties.getUi().getAppNameNavbar());
configData.put("languages", applicationProperties.getUi().getLanguages()); configData.put("languages", applicationProperties.getUi().getLanguages());
configData.put("logoStyle", applicationProperties.getUi().getLogoStyle()); configData.put("logoStyle", applicationProperties.getUi().getLogoStyle());
configData.put("defaultLocale", applicationProperties.getSystem().getDefaultLocale());
// Security settings // Security settings
// enableLogin requires both the config flag AND proprietary features to be loaded // enableLogin requires both the config flag AND proprietary features to be loaded
@@ -124,9 +123,6 @@ public class ConfigController {
"enableAnalytics", applicationProperties.getSystem().getEnableAnalytics()); "enableAnalytics", applicationProperties.getSystem().getEnableAnalytics());
configData.put("enablePosthog", applicationProperties.getSystem().getEnablePosthog()); configData.put("enablePosthog", applicationProperties.getSystem().getEnablePosthog());
configData.put("enableScarf", applicationProperties.getSystem().getEnableScarf()); configData.put("enableScarf", applicationProperties.getSystem().getEnableScarf());
configData.put(
"enableDesktopInstallSlide",
applicationProperties.getSystem().getEnableDesktopInstallSlide());
// Premium/Enterprise settings // Premium/Enterprise settings
configData.put("premiumEnabled", applicationProperties.getPremium().isEnabled()); configData.put("premiumEnabled", applicationProperties.getPremium().isEnabled());
@@ -230,10 +226,4 @@ public class ConfigController {
} }
return ResponseEntity.ok(result); return ResponseEntity.ok(result);
} }
@GetMapping("/group-enabled")
public ResponseEntity<Boolean> isGroupEnabled(@RequestParam(name = "group") String group) {
boolean enabled = endpointConfiguration.isGroupEnabled(group);
return ResponseEntity.ok(enabled);
}
} }
@@ -191,12 +191,6 @@ public class CertSignController {
switch (certType) { switch (certType) {
case "PEM": case "PEM":
privateKeyFile =
validateFilePresent(
privateKeyFile, "PEM private key", "private key file is required");
certFile =
validateFilePresent(
certFile, "PEM certificate", "certificate file is required");
ks = KeyStore.getInstance("JKS"); ks = KeyStore.getInstance("JKS");
ks.load(null); ks.load(null);
PrivateKey privateKey = getPrivateKeyFromPEM(privateKeyFile.getBytes(), password); PrivateKey privateKey = getPrivateKeyFromPEM(privateKeyFile.getBytes(), password);
@@ -206,16 +200,10 @@ public class CertSignController {
break; break;
case "PKCS12": case "PKCS12":
case "PFX": case "PFX":
p12File =
validateFilePresent(
p12File, "PKCS12 keystore", "PKCS12/PFX keystore file is required");
ks = KeyStore.getInstance("PKCS12"); ks = KeyStore.getInstance("PKCS12");
ks.load(p12File.getInputStream(), password.toCharArray()); ks.load(p12File.getInputStream(), password.toCharArray());
break; break;
case "JKS": case "JKS":
jksfile =
validateFilePresent(
jksfile, "JKS keystore", "JKS keystore file is required");
ks = KeyStore.getInstance("JKS"); ks = KeyStore.getInstance("JKS");
ks.load(jksfile.getInputStream(), password.toCharArray()); ks.load(jksfile.getInputStream(), password.toCharArray());
break; break;
@@ -263,17 +251,6 @@ public class CertSignController {
GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_signed.pdf")); GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_signed.pdf"));
} }
private MultipartFile validateFilePresent(
MultipartFile file, String argumentName, String errorDescription) {
if (file == null || file.isEmpty()) {
throw ExceptionUtils.createIllegalArgumentException(
"error.invalidArgument",
"Invalid argument: {0}",
argumentName + " - " + errorDescription);
}
return file;
}
private PrivateKey getPrivateKeyFromPEM(byte[] pemBytes, String password) private PrivateKey getPrivateKeyFromPEM(byte[] pemBytes, String password)
throws IOException, OperatorCreationException, PKCSException { throws IOException, OperatorCreationException, PKCSException {
try (PEMParser pemParser = try (PEMParser pemParser =
@@ -4,6 +4,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -11,7 +13,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
@Controller @Controller
@@ -62,10 +63,9 @@ public class ReactRoutingController {
} }
} }
@GetMapping( @GetMapping(value = {"/", "/index.html"}, produces = MediaType.TEXT_HTML_VALUE)
value = {"/", "/index.html"}, public ResponseEntity<String> serveIndexHtml(HttpServletRequest request)
produces = MediaType.TEXT_HTML_VALUE) throws IOException {
public ResponseEntity<String> serveIndexHtml(HttpServletRequest request) throws IOException {
if (indexHtmlExists && cachedIndexHtml != null) { if (indexHtmlExists && cachedIndexHtml != null) {
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(cachedIndexHtml); return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(cachedIndexHtml);
} }
@@ -74,13 +74,14 @@ public class ReactRoutingController {
} }
@GetMapping( @GetMapping(
"/{path:^(?!api|static|robots\\.txt|favicon\\.ico|manifest.*\\.json|pipeline|pdfjs|pdfjs-legacy|pdfium|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*$}") "/{path:^(?!api|static|robots\\.txt|favicon\\.ico|manifest.*\\.json|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*$}")
public ResponseEntity<String> forwardRootPaths(HttpServletRequest request) throws IOException { public ResponseEntity<String> forwardRootPaths(HttpServletRequest request)
throws IOException {
return serveIndexHtml(request); return serveIndexHtml(request);
} }
@GetMapping( @GetMapping(
"/{path:^(?!api|static|pipeline|pdfjs|pdfjs-legacy|pdfium|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*}/{subpath:^(?!.*\\.).*$}") "/{path:^(?!api|static|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*}/{subpath:^(?!.*\\.).*$}")
public ResponseEntity<String> forwardNestedPaths(HttpServletRequest request) public ResponseEntity<String> forwardNestedPaths(HttpServletRequest request)
throws IOException { throws IOException {
return serveIndexHtml(request); return serveIndexHtml(request);
@@ -1,8 +0,0 @@
package stirling.software.SPDF.exception;
public class CacheUnavailableException extends RuntimeException {
public CacheUnavailableException(String message) {
super(message);
}
}
@@ -45,26 +45,4 @@ public class OptimizePdfRequest extends PDFFile {
requiredMode = Schema.RequiredMode.REQUIRED, requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false") defaultValue = "false")
private Boolean grayscale = false; private Boolean grayscale = false;
@Schema(
description =
"Whether to convert images to high-contrast line art using ImageMagick. Default is false.",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "false")
private Boolean lineArt = false;
@Schema(
description = "Threshold to use for line art conversion (0-100).",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "55")
private Double lineArtThreshold = 55d;
@Schema(
description =
"Edge detection strength to use for line art conversion (1-3). This maps to"
+ " ImageMagick's -edge radius.",
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
defaultValue = "1",
allowableValues = {"1", "2", "3"})
private Integer lineArtEdgeLevel = 1;
} }
@@ -12,6 +12,7 @@
security: security:
enableLogin: true # set to 'true' to enable login enableLogin: true # set to 'true' to enable login
csrfDisabled: false # set to 'true' to disable CSRF protection (not recommended for production)
loginAttemptCount: 5 # lock user account after 5 tries; when using e.g. Fail2Ban you can deactivate the function with -1 loginAttemptCount: 5 # lock user account after 5 tries; when using e.g. Fail2Ban you can deactivate the function with -1
loginResetTimeMinutes: 120 # lock account for 2 hours after x attempts loginResetTimeMinutes: 120 # lock account for 2 hours after x attempts
loginMethod: all # Accepts values like 'all' and 'normal'(only Login with Username/Password), 'oauth2'(only Login with OAuth2) or 'saml2'(only Login with SAML2) loginMethod: all # Accepts values like 'all' and 'normal'(only Login with Username/Password), 'oauth2'(only Login with OAuth2) or 'saml2'(only Login with SAML2)
@@ -58,8 +59,6 @@ security:
idpCert: classpath:okta.cert # The certificate your Provider will use to authenticate your app's SAML authentication requests. Provided by your Provider idpCert: classpath:okta.cert # The certificate your Provider will use to authenticate your app's SAML authentication requests. Provided by your Provider
privateKey: classpath:saml-private-key.key # Your private key. Generated from your keypair privateKey: classpath:saml-private-key.key # Your private key. Generated from your keypair
spCert: classpath:saml-public-cert.crt # Your signing certificate. Generated from your keypair spCert: classpath:saml-public-cert.crt # Your signing certificate. Generated from your keypair
# IMPORTANT: For SAML setup, download your SP metadata from the BACKEND URL: http://localhost:8080/saml2/service-provider-metadata/{registrationId}
# Do NOT use the frontend dev server URL (localhost:5173) as it will generate incorrect ACS URLs. Always use the backend URL (localhost:8080) for SAML configuration.
jwt: # This feature is currently under development and not yet fully supported. Do not use in production. jwt: # This feature is currently under development and not yet fully supported. Do not use in production.
persistence: true # Set to 'true' to enable JWT key store persistence: true # Set to 'true' to enable JWT key store
enableKeyRotation: true # Set to 'true' to enable key pair rotation enableKeyRotation: true # Set to 'true' to enable key pair rotation
@@ -106,11 +105,6 @@ mail:
username: '' # SMTP server username username: '' # SMTP server username
password: '' # SMTP server password password: '' # SMTP server password
from: '' # sender email address from: '' # sender email address
startTlsEnable: true # enable STARTTLS (explicit TLS upgrade after connecting) when supported by the SMTP server
startTlsRequired: false # require STARTTLS; connection fails if the upgrade command is not supported
sslEnable: false # enable SSL/TLS wrapper for implicit TLS (typically used with port 465)
sslTrust: '' # optional trusted host override, e.g. "smtp.example.com" or "*"; defaults to "*" (trust all) when empty
sslCheckServerIdentity: false # enable hostname verification when using SSL/TLS
legal: legal:
termsAndConditions: https://www.stirling.com/legal/terms-of-service # URL to the terms and conditions of your application (e.g. https://example.com/terms). Empty string to disable or filename to load from local file in static folder termsAndConditions: https://www.stirling.com/legal/terms-of-service # URL to the terms and conditions of your application (e.g. https://example.com/terms). Empty string to disable or filename to load from local file in static folder
@@ -128,15 +122,13 @@ system:
customHTMLFiles: false # enable to have files placed in /customFiles/templates override the existing template HTML files customHTMLFiles: false # enable to have files placed in /customFiles/templates override the existing template HTML files
tessdataDir: /usr/share/tessdata # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored. tessdataDir: /usr/share/tessdata # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.
enableAnalytics: null # Master toggle for analytics: set to 'true' to enable all analytics, 'false' to disable all analytics, or leave as 'null' to prompt admin on first launch enableAnalytics: null # Master toggle for analytics: set to 'true' to enable all analytics, 'false' to disable all analytics, or leave as 'null' to prompt admin on first launch
enableDesktopInstallSlide: true # Set to 'false' to hide the desktop app installation slide in the onboarding flow
enablePosthog: null # Enable PostHog analytics (open-source product analytics): set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled enablePosthog: null # Enable PostHog analytics (open-source product analytics): set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled
enableScarf: null # Enable Scarf tracking pixel: set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled enableScarf: null # Enable Scarf tracking pixel: set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled
enableUrlToPDF: false # Set to 'true' to enable URL to PDF, INTERNAL ONLY, known security issues, should not be used externally enableUrlToPDF: false # Set to 'true' to enable URL to PDF, INTERNAL ONLY, known security issues, should not be used externally
disableSanitize: false # set to true to disable Sanitize HTML; (can lead to injections in HTML) disableSanitize: false # set to true to disable Sanitize HTML; (can lead to injections in HTML)
maxDPI: 500 # Maximum allowed DPI for PDF to image conversion maxDPI: 500 # Maximum allowed DPI for PDF to image conversion
corsAllowedOrigins: [] # List of allowed origins for CORS (e.g. ['http://localhost:5173', 'https://app.example.com']). Leave empty to disable CORS. For local development with frontend on port 5173, add 'http://localhost:5173' corsAllowedOrigins: [] # List of allowed origins for CORS (e.g. ['http://localhost:5173', 'https://app.example.com']). Leave empty to disable CORS.
backendUrl: '' # Backend base URL for SAML/OAuth/API callbacks (e.g. 'http://localhost:8080' for dev, 'https://api.example.com' for production). REQUIRED for SSO authentication to work correctly. This is where your IdP will send SAML responses and OAuth callbacks. Leave empty to default to 'http://localhost:8080' in development. frontendUrl: '' # Base URL for frontend (e.g. 'https://pdf.example.com'). Used for generating invite links in emails. If empty, falls back to backend URL.
frontendUrl: '' # Frontend URL for invite email links (e.g. 'https://app.example.com'). Optional - if not set, will use backendUrl. This is the URL users click in invite emails.
serverCertificate: serverCertificate:
enabled: true # Enable server-side certificate for "Sign with Stirling-PDF" option enabled: true # Enable server-side certificate for "Sign with Stirling-PDF" option
organizationName: Stirling-PDF # Organization name for generated certificates organizationName: Stirling-PDF # Organization name for generated certificates
@@ -182,6 +174,23 @@ system:
databaseBackup: databaseBackup:
cron: '0 0 0 * * ?' # Cron expression for automatic database backups "0 0 0 * * ?" daily at midnight cron: '0 0 0 * * ?' # Cron expression for automatic database backups "0 0 0 * * ?" daily at midnight
stirling:
pdf:
fallback-font: classpath:/static/fonts/NotoSans-Regular.ttf # Override to point at a custom fallback font
json:
font-normalization:
enabled: false # IMPORTANT: Disable to preserve ToUnicode CMaps for correct font rendering. Ghostscript strips Unicode mappings from CID fonts.
cff-converter:
enabled: true # Wrap CFF/Type1C fonts as OpenType-CFF for browser compatibility
method: python # Converter method: 'python' (fontTools, recommended - wraps as OTF), 'fontforge' (legacy - converts to TTF, may hang on CID fonts)
python-command: /opt/venv/bin/python3 # Python interpreter path
python-script: /scripts/convert_cff_to_ttf.py # Path to font wrapping script
fontforge-command: fontforge # Override if FontForge is installed under a different name/path
type3:
library:
enabled: true # Match common Type3 fonts against the built-in library of converted programs
index: classpath:/type3/library/index.json # Override to point at a custom index.json (supports http:, file:, classpath:)
ui: ui:
appNameNavbar: '' # name displayed on the navigation bar appNameNavbar: '' # name displayed on the navigation bar
logoStyle: classic # Options: 'classic' (default - classic S icon) or 'modern' (minimalist logo) logoStyle: classic # Options: 'classic' (default - classic S icon) or 'modern' (minimalist logo)
@@ -210,7 +219,6 @@ processExecutor:
weasyPrintSessionLimit: 16 weasyPrintSessionLimit: 16
installAppSessionLimit: 1 installAppSessionLimit: 1
calibreSessionLimit: 1 calibreSessionLimit: 1
imageMagickSessionLimit: 4
ghostscriptSessionLimit: 8 ghostscriptSessionLimit: 8
ocrMyPdfSessionLimit: 2 ocrMyPdfSessionLimit: 2
timeoutMinutes: # Process executor timeout in minutes timeoutMinutes: # Process executor timeout in minutes
@@ -220,26 +228,7 @@ processExecutor:
weasyPrinttimeoutMinutes: 30 weasyPrinttimeoutMinutes: 30
installApptimeoutMinutes: 60 installApptimeoutMinutes: 60
calibretimeoutMinutes: 30 calibretimeoutMinutes: 30
imageMagickTimeoutMinutes: 30
tesseractTimeoutMinutes: 30 tesseractTimeoutMinutes: 30
qpdfTimeoutMinutes: 30 qpdfTimeoutMinutes: 30
ghostscriptTimeoutMinutes: 30 ghostscriptTimeoutMinutes: 30
ocrMyPdfTimeoutMinutes: 30 ocrMyPdfTimeoutMinutes: 30
pdfEditor:
fallback-font: classpath:/static/fonts/NotoSans-Regular.ttf # Override to point at a custom fallback font
cache:
max-bytes: -1 # Max in-memory cache size in bytes; -1 disables byte cap
max-percent: 20 # Max in-memory cache as % of JVM max; used when max-bytes <= 0
font-normalization:
enabled: false # IMPORTANT: Disable to preserve ToUnicode CMaps for correct font rendering. Ghostscript strips Unicode mappings from CID fonts.
cff-converter:
enabled: true # Wrap CFF/Type1CFF fonts as OpenType-CFF for browser compatibility
method: python # Converter method: 'python' (fontTools, recommended - wraps as OTF), 'fontforge' (legacy - converts to TTF, may hang on CID fonts)
python-command: /opt/venv/bin/python3 # Python interpreter path
python-script: /scripts/convert_cff_to_ttf.py # Path to font wrapping script
fontforge-command: fontforge # Override if FontForge is installed under a different name/path
type3:
library:
enabled: true # Match common Type3 fonts against the built-in library of converted programs
index: classpath:/type3/library/index.json # Override to point at a custom index.json (supports http:, file:, classpath:)
@@ -1,10 +1,9 @@
package stirling.software.SPDF.controller.api.security; package stirling.software.SPDF.controller.api.security;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
@@ -108,8 +107,7 @@ class CertSignControllerTest {
derCertBytes = baos.toByteArray(); derCertBytes = baos.toByteArray();
} }
lenient() when(pdfDocumentFactory.load(any(MultipartFile.class)))
.when(pdfDocumentFactory.load(any(MultipartFile.class)))
.thenAnswer( .thenAnswer(
invocation -> { invocation -> {
MultipartFile file = invocation.getArgument(0); MultipartFile file = invocation.getArgument(0);
@@ -169,31 +167,6 @@ class CertSignControllerTest {
assertTrue(response.getBody().length > 0); assertTrue(response.getBody().length > 0);
} }
@Test
void testSignPdfWithMissingPkcs12FileThrowsError() {
MockMultipartFile pdfFile =
new MockMultipartFile(
"fileInput", "test.pdf", MediaType.APPLICATION_PDF_VALUE, pdfBytes);
SignPDFWithCertRequest request = new SignPDFWithCertRequest();
request.setFileInput(pdfFile);
request.setCertType("PFX");
request.setPassword("password");
request.setShowSignature(false);
request.setReason("test");
request.setLocation("test");
request.setName("tester");
request.setPageNumber(1);
request.setShowLogo(false);
IllegalArgumentException exception =
assertThrows(
IllegalArgumentException.class,
() -> certSignController.signPDFWithCert(request));
assertTrue(exception.getMessage().contains("PKCS12 keystore"));
}
@Test @Test
void testSignPdfWithJks() throws Exception { void testSignPdfWithJks() throws Exception {
MockMultipartFile pdfFile = MockMultipartFile pdfFile =
@@ -31,10 +31,12 @@ import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.JobOwnershipService; import stirling.software.common.service.JobOwnershipService;
import stirling.software.common.util.ExceptionUtils; import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.WebResponseUtils; import stirling.software.common.util.WebResponseUtils;
import stirling.software.proprietary.security.config.PremiumEndpoint;
@Slf4j @Slf4j
@ConvertApi @ConvertApi
@RequiredArgsConstructor @RequiredArgsConstructor
@PremiumEndpoint
public class ConvertPdfJsonController { public class ConvertPdfJsonController {
private final PdfJsonConversionService pdfJsonConversionService; private final PdfJsonConversionService pdfJsonConversionService;
@@ -86,6 +86,7 @@ import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition; import org.apache.pdfbox.text.TextPosition;
import org.apache.pdfbox.util.DateConverter; import org.apache.pdfbox.util.DateConverter;
import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Matrix;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@@ -143,23 +144,15 @@ public class PdfJsonConversionService {
private final PdfJsonFontService fontService; private final PdfJsonFontService fontService;
private final Type3FontConversionService type3FontConversionService; private final Type3FontConversionService type3FontConversionService;
private final Type3GlyphExtractor type3GlyphExtractor; private final Type3GlyphExtractor type3GlyphExtractor;
private final stirling.software.common.model.ApplicationProperties applicationProperties;
private final Map<String, PDFont> type3NormalizedFontCache = new ConcurrentHashMap<>(); private final Map<String, PDFont> type3NormalizedFontCache = new ConcurrentHashMap<>();
private final Map<String, Set<Integer>> type3GlyphCoverageCache = new ConcurrentHashMap<>(); private final Map<String, Set<Integer>> type3GlyphCoverageCache = new ConcurrentHashMap<>();
@Value("${stirling.pdf.json.font-normalization.enabled:true}")
private boolean fontNormalizationEnabled; private boolean fontNormalizationEnabled;
private long cacheMaxBytes;
private int cacheMaxPercent;
/** Cache for storing PDDocuments for lazy page loading. Key is jobId. */ /** Cache for storing PDDocuments for lazy page loading. Key is jobId. */
private final Map<String, CachedPdfDocument> documentCache = new ConcurrentHashMap<>(); private final Map<String, CachedPdfDocument> documentCache = new ConcurrentHashMap<>();
private final java.util.LinkedHashMap<String, CachedPdfDocument> lruCache =
new java.util.LinkedHashMap<>(16, 0.75f, true);
private final Object cacheLock = new Object();
private volatile long currentCacheBytes = 0L;
private volatile long cacheBudgetBytes = -1L;
private volatile boolean ghostscriptAvailable; private volatile boolean ghostscriptAvailable;
private static final float FLOAT_EPSILON = 0.0001f; private static final float FLOAT_EPSILON = 0.0001f;
@@ -168,23 +161,7 @@ public class PdfJsonConversionService {
@PostConstruct @PostConstruct
private void initializeToolAvailability() { private void initializeToolAvailability() {
loadConfigurationFromProperties();
initializeGhostscriptAvailability(); initializeGhostscriptAvailability();
initializeCacheBudget();
}
private void loadConfigurationFromProperties() {
stirling.software.common.model.ApplicationProperties.PdfEditor cfg =
applicationProperties.getPdfEditor();
if (cfg != null) {
fontNormalizationEnabled = cfg.getFontNormalization().isEnabled();
cacheMaxBytes = cfg.getCache().getMaxBytes();
cacheMaxPercent = cfg.getCache().getMaxPercent();
} else {
fontNormalizationEnabled = false;
cacheMaxBytes = -1;
cacheMaxPercent = 20;
}
} }
private void initializeGhostscriptAvailability() { private void initializeGhostscriptAvailability() {
@@ -225,25 +202,6 @@ public class PdfJsonConversionService {
} }
} }
private void initializeCacheBudget() {
long effective = -1L;
if (cacheMaxBytes > 0) {
effective = cacheMaxBytes;
} else if (cacheMaxPercent > 0) {
long maxMem = Runtime.getRuntime().maxMemory();
effective = Math.max(0L, (maxMem * cacheMaxPercent) / 100);
}
cacheBudgetBytes = effective;
if (cacheBudgetBytes > 0) {
log.info(
"PDF JSON cache budget configured: {} bytes (source: {})",
cacheBudgetBytes,
cacheMaxBytes > 0 ? "max-bytes" : "max-percent");
} else {
log.info("PDF JSON cache budget: unlimited");
}
}
public byte[] convertPdfToJson(MultipartFile file) throws IOException { public byte[] convertPdfToJson(MultipartFile file) throws IOException {
return convertPdfToJson(file, null, false); return convertPdfToJson(file, null, false);
} }
@@ -278,10 +236,7 @@ public class PdfJsonConversionService {
log.debug("Generated synthetic jobId for synchronous conversion: {}", jobId); log.debug("Generated synthetic jobId for synchronous conversion: {}", jobId);
} else { } else {
jobId = contextJobId; jobId = contextJobId;
log.info( log.debug("Starting PDF to JSON conversion, jobId from context: {}", jobId);
"Starting PDF to JSON conversion, jobId from context: {} (lightweight={})",
jobId,
lightweight);
} }
Consumer<PdfJsonConversionProgress> progress = Consumer<PdfJsonConversionProgress> progress =
@@ -363,9 +318,9 @@ public class PdfJsonConversionService {
try (PDDocument document = pdfDocumentFactory.load(workingPath, true)) { try (PDDocument document = pdfDocumentFactory.load(workingPath, true)) {
int totalPages = document.getNumberOfPages(); int totalPages = document.getNumberOfPages();
// Always enable lazy mode for real async jobs so cache is available regardless of // Only use lazy images for real async jobs where client can access the cache
// page count. Synchronous calls with synthetic jobId still do full extraction. // Synchronous calls with synthetic jobId should do full extraction
boolean useLazyImages = isRealJobId; boolean useLazyImages = totalPages > 5 && isRealJobId;
Map<COSBase, FontModelCacheEntry> fontCache = new IdentityHashMap<>(); Map<COSBase, FontModelCacheEntry> fontCache = new IdentityHashMap<>();
Map<COSBase, EncodedImage> imageCache = new IdentityHashMap<>(); Map<COSBase, EncodedImage> imageCache = new IdentityHashMap<>();
log.debug( log.debug(
@@ -448,11 +403,6 @@ public class PdfJsonConversionService {
// Only cache for real async jobIds, not synthetic synchronous ones // Only cache for real async jobIds, not synthetic synchronous ones
if (useLazyImages && isRealJobId) { if (useLazyImages && isRealJobId) {
log.info(
"Creating cache for jobId: {} (useLazyImages={}, isRealJobId={})",
jobId,
useLazyImages,
isRealJobId);
PdfJsonDocumentMetadata docMetadata = new PdfJsonDocumentMetadata(); PdfJsonDocumentMetadata docMetadata = new PdfJsonDocumentMetadata();
docMetadata.setMetadata(pdfJson.getMetadata()); docMetadata.setMetadata(pdfJson.getMetadata());
docMetadata.setXmpMetadata(pdfJson.getXmpMetadata()); docMetadata.setXmpMetadata(pdfJson.getXmpMetadata());
@@ -485,23 +435,16 @@ public class PdfJsonConversionService {
cachedPdfBytes = Files.readAllBytes(workingPath); cachedPdfBytes = Files.readAllBytes(workingPath);
} }
CachedPdfDocument cached = CachedPdfDocument cached =
buildCachedDocument( new CachedPdfDocument(
jobId, cachedPdfBytes, docMetadata, fonts, pageFontResources); cachedPdfBytes, docMetadata, fonts, pageFontResources);
putCachedDocument(jobId, cached); documentCache.put(jobId, cached);
log.info( log.debug(
"Successfully cached PDF ({} bytes, {} pages, {} fonts) for jobId: {} (diskBacked={})", "Cached PDF bytes ({} bytes, {} pages, {} fonts) for lazy images, jobId: {}",
cached.getPdfSize(), cachedPdfBytes.length,
totalPages, totalPages,
fonts.size(), fonts.size(),
jobId,
cached.isDiskBacked());
scheduleDocumentCleanup(jobId);
} else {
log.warn(
"Skipping cache creation: useLazyImages={}, isRealJobId={}, jobId={}",
useLazyImages,
isRealJobId,
jobId); jobId);
scheduleDocumentCleanup(jobId);
} }
if (lightweight) { if (lightweight) {
@@ -3030,139 +2973,6 @@ public class PdfJsonConversionService {
} }
} }
// Cache helpers
private CachedPdfDocument buildCachedDocument(
String jobId,
byte[] pdfBytes,
PdfJsonDocumentMetadata metadata,
Map<String, PdfJsonFont> fonts,
Map<Integer, Map<PDFont, String>> pageFontResources)
throws IOException {
if (pdfBytes == null) {
throw new IllegalArgumentException("pdfBytes must not be null");
}
long budget = cacheBudgetBytes;
// If single document is larger than budget, spill straight to disk
if (budget > 0 && pdfBytes.length > budget) {
TempFile tempFile = new TempFile(tempFileManager, ".pdfjsoncache");
Files.write(tempFile.getPath(), pdfBytes);
log.debug(
"Cached PDF spilled to disk ({} bytes exceeds budget {}) for jobId {}",
pdfBytes.length,
budget,
jobId);
return new CachedPdfDocument(
null, tempFile, pdfBytes.length, metadata, fonts, pageFontResources);
}
return new CachedPdfDocument(
pdfBytes, null, pdfBytes.length, metadata, fonts, pageFontResources);
}
private void putCachedDocument(String jobId, CachedPdfDocument cached) {
synchronized (cacheLock) {
CachedPdfDocument existing = documentCache.put(jobId, cached);
if (existing != null) {
lruCache.remove(jobId);
currentCacheBytes = Math.max(0L, currentCacheBytes - existing.getInMemorySize());
existing.close();
}
lruCache.put(jobId, cached);
currentCacheBytes += cached.getInMemorySize();
enforceCacheBudget();
}
}
private CachedPdfDocument getCachedDocument(String jobId) {
synchronized (cacheLock) {
CachedPdfDocument cached = documentCache.get(jobId);
if (cached != null) {
lruCache.remove(jobId);
lruCache.put(jobId, cached);
}
return cached;
}
}
private void enforceCacheBudget() {
if (cacheBudgetBytes <= 0) {
return;
}
// Must be called under cacheLock
java.util.Iterator<java.util.Map.Entry<String, CachedPdfDocument>> it =
lruCache.entrySet().iterator();
while (currentCacheBytes > cacheBudgetBytes && it.hasNext()) {
java.util.Map.Entry<String, CachedPdfDocument> entry = it.next();
it.remove();
CachedPdfDocument removed = entry.getValue();
documentCache.remove(entry.getKey(), removed);
currentCacheBytes = Math.max(0L, currentCacheBytes - removed.getInMemorySize());
removed.close();
log.warn(
"Evicted cached PDF for jobId {} to enforce cache budget (budget={} bytes, current={} bytes)",
entry.getKey(),
cacheBudgetBytes,
currentCacheBytes);
}
if (currentCacheBytes > cacheBudgetBytes && !lruCache.isEmpty()) {
// Spill the most recently used large entry to disk
String key =
lruCache.entrySet().stream()
.reduce((first, second) -> second)
.map(java.util.Map.Entry::getKey)
.orElse(null);
if (key != null) {
CachedPdfDocument doc = lruCache.get(key);
if (doc != null && doc.getInMemorySize() > 0) {
try {
CachedPdfDocument diskDoc =
buildCachedDocument(
key,
doc.getPdfBytes(),
doc.getMetadata(),
doc.getFonts(),
doc.getPageFontResources());
lruCache.put(key, diskDoc);
documentCache.put(key, diskDoc);
currentCacheBytes =
Math.max(0L, currentCacheBytes - doc.getInMemorySize())
+ diskDoc.getInMemorySize();
doc.close();
log.debug("Spilled cached PDF for jobId {} to disk to satisfy budget", key);
} catch (IOException ex) {
log.warn(
"Failed to spill cached PDF for jobId {} to disk: {}",
key,
ex.getMessage());
}
}
}
}
}
private void removeCachedDocument(String jobId) {
log.warn(
"removeCachedDocument called for jobId: {} [CALLER: {}]",
jobId,
Thread.currentThread().getStackTrace()[2].toString());
CachedPdfDocument removed = null;
synchronized (cacheLock) {
removed = documentCache.remove(jobId);
if (removed != null) {
lruCache.remove(jobId);
currentCacheBytes = Math.max(0L, currentCacheBytes - removed.getInMemorySize());
log.warn(
"Removed cached document for jobId: {} (size={} bytes)",
jobId,
removed.getInMemorySize());
} else {
log.warn("Attempted to remove jobId: {} but it was not in cache", jobId);
}
}
if (removed != null) {
removed.close();
}
}
private void applyTextState(PDPageContentStream contentStream, PdfJsonTextElement element) private void applyTextState(PDPageContentStream contentStream, PdfJsonTextElement element)
throws IOException { throws IOException {
if (element.getCharacterSpacing() != null) { if (element.getCharacterSpacing() != null) {
@@ -5501,8 +5311,6 @@ public class PdfJsonConversionService {
*/ */
private static class CachedPdfDocument { private static class CachedPdfDocument {
private final byte[] pdfBytes; private final byte[] pdfBytes;
private final TempFile pdfTempFile;
private final long pdfSize;
private final PdfJsonDocumentMetadata metadata; private final PdfJsonDocumentMetadata metadata;
private final Map<String, PdfJsonFont> fonts; // Font map with UIDs for consistency private final Map<String, PdfJsonFont> fonts; // Font map with UIDs for consistency
private final Map<Integer, Map<PDFont, String>> pageFontResources; // Page font resources private final Map<Integer, Map<PDFont, String>> pageFontResources; // Page font resources
@@ -5510,14 +5318,10 @@ public class PdfJsonConversionService {
public CachedPdfDocument( public CachedPdfDocument(
byte[] pdfBytes, byte[] pdfBytes,
TempFile pdfTempFile,
long pdfSize,
PdfJsonDocumentMetadata metadata, PdfJsonDocumentMetadata metadata,
Map<String, PdfJsonFont> fonts, Map<String, PdfJsonFont> fonts,
Map<Integer, Map<PDFont, String>> pageFontResources) { Map<Integer, Map<PDFont, String>> pageFontResources) {
this.pdfBytes = pdfBytes; this.pdfBytes = pdfBytes;
this.pdfTempFile = pdfTempFile;
this.pdfSize = pdfSize;
this.metadata = metadata; this.metadata = metadata;
// Create defensive copies to prevent mutation of shared maps // Create defensive copies to prevent mutation of shared maps
this.fonts = this.fonts =
@@ -5532,14 +5336,8 @@ public class PdfJsonConversionService {
} }
// Getters return defensive copies to prevent external mutation // Getters return defensive copies to prevent external mutation
public byte[] getPdfBytes() throws IOException { public byte[] getPdfBytes() {
if (pdfBytes != null) { return pdfBytes;
return pdfBytes;
}
if (pdfTempFile != null) {
return Files.readAllBytes(pdfTempFile.getPath());
}
throw new IOException("Cached PDF backing missing");
} }
public PdfJsonDocumentMetadata getMetadata() { public PdfJsonDocumentMetadata getMetadata() {
@@ -5554,18 +5352,6 @@ public class PdfJsonConversionService {
return new java.util.concurrent.ConcurrentHashMap<>(pageFontResources); return new java.util.concurrent.ConcurrentHashMap<>(pageFontResources);
} }
public long getPdfSize() {
return pdfSize;
}
public long getInMemorySize() {
return pdfBytes != null ? pdfBytes.length : 0L;
}
public boolean isDiskBacked() {
return pdfBytes == null && pdfTempFile != null;
}
public long getTimestamp() { public long getTimestamp() {
return timestamp; return timestamp;
} }
@@ -5577,19 +5363,7 @@ public class PdfJsonConversionService {
public CachedPdfDocument withUpdatedFonts( public CachedPdfDocument withUpdatedFonts(
byte[] nextBytes, Map<String, PdfJsonFont> nextFonts) { byte[] nextBytes, Map<String, PdfJsonFont> nextFonts) {
Map<String, PdfJsonFont> fontsToUse = nextFonts != null ? nextFonts : this.fonts; Map<String, PdfJsonFont> fontsToUse = nextFonts != null ? nextFonts : this.fonts;
return new CachedPdfDocument( return new CachedPdfDocument(nextBytes, metadata, fontsToUse, pageFontResources);
nextBytes,
null,
nextBytes != null ? nextBytes.length : 0,
metadata,
fontsToUse,
pageFontResources);
}
public void close() {
if (pdfTempFile != null) {
pdfTempFile.close();
}
} }
} }
@@ -5670,15 +5444,14 @@ public class PdfJsonConversionService {
// Cache PDF bytes, metadata, and fonts for lazy page loading // Cache PDF bytes, metadata, and fonts for lazy page loading
if (jobId != null) { if (jobId != null) {
CachedPdfDocument cached = CachedPdfDocument cached =
buildCachedDocument(jobId, pdfBytes, docMetadata, fonts, pageFontResources); new CachedPdfDocument(pdfBytes, docMetadata, fonts, pageFontResources);
putCachedDocument(jobId, cached); documentCache.put(jobId, cached);
log.debug( log.debug(
"Cached PDF bytes ({} bytes, {} pages, {} fonts) for lazy loading, jobId: {} (diskBacked={})", "Cached PDF bytes ({} bytes, {} pages, {} fonts) for lazy loading, jobId: {}",
cached.getPdfSize(), pdfBytes.length,
totalPages, totalPages,
fonts.size(), fonts.size(),
jobId, jobId);
cached.isDiskBacked());
// Schedule cleanup after 30 minutes // Schedule cleanup after 30 minutes
scheduleDocumentCleanup(jobId); scheduleDocumentCleanup(jobId);
@@ -5693,10 +5466,9 @@ public class PdfJsonConversionService {
/** Extracts a single page from cached PDF bytes. Re-loads the PDF for each request. */ /** Extracts a single page from cached PDF bytes. Re-loads the PDF for each request. */
public byte[] extractSinglePage(String jobId, int pageNumber) throws IOException { public byte[] extractSinglePage(String jobId, int pageNumber) throws IOException {
CachedPdfDocument cached = getCachedDocument(jobId); CachedPdfDocument cached = documentCache.get(jobId);
if (cached == null) { if (cached == null) {
throw new stirling.software.SPDF.exception.CacheUnavailableException( throw new IllegalArgumentException("No cached document found for jobId: " + jobId);
"No cached document found for jobId: " + jobId);
} }
int pageIndex = pageNumber - 1; int pageIndex = pageNumber - 1;
@@ -5708,8 +5480,8 @@ public class PdfJsonConversionService {
} }
log.debug( log.debug(
"Loading PDF from {} to extract page {} (jobId: {})", "Loading PDF from bytes ({} bytes) to extract page {} (jobId: {})",
cached.isDiskBacked() ? "disk cache" : "memory cache", cached.getPdfBytes().length,
pageNumber, pageNumber,
jobId); jobId);
@@ -5855,21 +5627,10 @@ public class PdfJsonConversionService {
if (jobId == null || jobId.isBlank()) { if (jobId == null || jobId.isBlank()) {
throw new IllegalArgumentException("jobId is required for incremental export"); throw new IllegalArgumentException("jobId is required for incremental export");
} }
log.info("Looking up cache for jobId: {}", jobId); CachedPdfDocument cached = documentCache.get(jobId);
CachedPdfDocument cached = getCachedDocument(jobId);
if (cached == null) { if (cached == null) {
log.error( throw new IllegalArgumentException("No cached document available for jobId: " + jobId);
"Cache not found for jobId: {}. Available cache keys: {}",
jobId,
documentCache.keySet());
throw new stirling.software.SPDF.exception.CacheUnavailableException(
"No cached document available for jobId: " + jobId);
} }
log.info(
"Found cached document for jobId: {} (size={}, diskBacked={})",
jobId,
cached.getPdfSize(),
cached.isDiskBacked());
if (updates == null || updates.getPages() == null || updates.getPages().isEmpty()) { if (updates == null || updates.getPages() == null || updates.getPages().isEmpty()) {
log.debug( log.debug(
"Incremental export requested with no page updates; returning cached PDF for jobId {}", "Incremental export requested with no page updates; returning cached PDF for jobId {}",
@@ -5948,14 +5709,7 @@ public class PdfJsonConversionService {
document.save(baos); document.save(baos);
byte[] updatedBytes = baos.toByteArray(); byte[] updatedBytes = baos.toByteArray();
CachedPdfDocument updated = documentCache.put(jobId, cached.withUpdatedFonts(updatedBytes, mergedFonts));
buildCachedDocument(
jobId,
updatedBytes,
cached.getMetadata(),
mergedFonts,
cached.getPageFontResources());
putCachedDocument(jobId, updated);
// Clear Type3 cache entries for this incremental update // Clear Type3 cache entries for this incremental update
clearType3CacheEntriesForJob(updateJobId); clearType3CacheEntriesForJob(updateJobId);
@@ -5970,13 +5724,11 @@ public class PdfJsonConversionService {
/** Clears a cached document. */ /** Clears a cached document. */
public void clearCachedDocument(String jobId) { public void clearCachedDocument(String jobId) {
CachedPdfDocument cached = getCachedDocument(jobId); CachedPdfDocument cached = documentCache.remove(jobId);
removeCachedDocument(jobId);
if (cached != null) { if (cached != null) {
log.debug( log.debug(
"Removed cached PDF ({} bytes, diskBacked={}) for jobId: {}", "Removed cached PDF bytes ({} bytes) for jobId: {}",
cached.getPdfSize(), cached.getPdfBytes().length,
cached.isDiskBacked(),
jobId); jobId);
} }
@@ -33,12 +33,8 @@ public class PdfJsonFallbackFontService {
public static final String FALLBACK_FONT_CJK_ID = "fallback-noto-cjk"; public static final String FALLBACK_FONT_CJK_ID = "fallback-noto-cjk";
public static final String FALLBACK_FONT_JP_ID = "fallback-noto-jp"; public static final String FALLBACK_FONT_JP_ID = "fallback-noto-jp";
public static final String FALLBACK_FONT_KR_ID = "fallback-noto-korean"; public static final String FALLBACK_FONT_KR_ID = "fallback-noto-korean";
public static final String FALLBACK_FONT_TC_ID = "fallback-noto-tc";
public static final String FALLBACK_FONT_AR_ID = "fallback-noto-arabic"; public static final String FALLBACK_FONT_AR_ID = "fallback-noto-arabic";
public static final String FALLBACK_FONT_TH_ID = "fallback-noto-thai"; public static final String FALLBACK_FONT_TH_ID = "fallback-noto-thai";
public static final String FALLBACK_FONT_DEVANAGARI_ID = "fallback-noto-devanagari";
public static final String FALLBACK_FONT_MALAYALAM_ID = "fallback-noto-malayalam";
public static final String FALLBACK_FONT_TIBETAN_ID = "fallback-noto-tibetan";
// Font name aliases map PDF font names to available fallback fonts // Font name aliases map PDF font names to available fallback fonts
// This provides better visual consistency when editing PDFs // This provides better visual consistency when editing PDFs
@@ -63,22 +59,6 @@ public class PdfJsonFallbackFontService {
Map.entry("dejavuserif", "fallback-dejavu-serif"), Map.entry("dejavuserif", "fallback-dejavu-serif"),
Map.entry("dejavumono", "fallback-dejavu-mono"), Map.entry("dejavumono", "fallback-dejavu-mono"),
Map.entry("dejavusansmono", "fallback-dejavu-mono"), Map.entry("dejavusansmono", "fallback-dejavu-mono"),
// Traditional Chinese fonts (Taiwan, Hong Kong, Macau)
Map.entry("mingliu", "fallback-noto-tc"),
Map.entry("pmingliu", "fallback-noto-tc"),
Map.entry("microsoftjhenghei", "fallback-noto-tc"),
Map.entry("jhenghei", "fallback-noto-tc"),
Map.entry("kaiti", "fallback-noto-tc"),
Map.entry("kaiu", "fallback-noto-tc"),
Map.entry("dfkaib5", "fallback-noto-tc"),
Map.entry("dfkai", "fallback-noto-tc"),
// Simplified Chinese fonts (Mainland China) - more common
Map.entry("simsun", "fallback-noto-cjk"),
Map.entry("simhei", "fallback-noto-cjk"),
Map.entry("microsoftyahei", "fallback-noto-cjk"),
Map.entry("yahei", "fallback-noto-cjk"),
Map.entry("songti", "fallback-noto-cjk"),
Map.entry("heiti", "fallback-noto-cjk"),
// Noto Sans - Google's universal font (use as last resort generic fallback) // Noto Sans - Google's universal font (use as last resort generic fallback)
Map.entry("noto", "fallback-noto-sans"), Map.entry("noto", "fallback-noto-sans"),
Map.entry("notosans", "fallback-noto-sans")); Map.entry("notosans", "fallback-noto-sans"));
@@ -103,12 +83,6 @@ public class PdfJsonFallbackFontService {
"classpath:/static/fonts/NotoSansKR-Regular.ttf", "classpath:/static/fonts/NotoSansKR-Regular.ttf",
"NotoSansKR-Regular", "NotoSansKR-Regular",
"ttf")), "ttf")),
Map.entry(
FALLBACK_FONT_TC_ID,
new FallbackFontSpec(
"classpath:/static/fonts/NotoSansTC-Regular.ttf",
"NotoSansTC-Regular",
"ttf")),
Map.entry( Map.entry(
FALLBACK_FONT_AR_ID, FALLBACK_FONT_AR_ID,
new FallbackFontSpec( new FallbackFontSpec(
@@ -121,24 +95,6 @@ public class PdfJsonFallbackFontService {
"classpath:/static/fonts/NotoSansThai-Regular.ttf", "classpath:/static/fonts/NotoSansThai-Regular.ttf",
"NotoSansThai-Regular", "NotoSansThai-Regular",
"ttf")), "ttf")),
Map.entry(
FALLBACK_FONT_DEVANAGARI_ID,
new FallbackFontSpec(
"classpath:/static/fonts/NotoSansDevanagari-Regular.ttf",
"NotoSansDevanagari-Regular",
"ttf")),
Map.entry(
FALLBACK_FONT_MALAYALAM_ID,
new FallbackFontSpec(
"classpath:/static/fonts/NotoSansMalayalam-Regular.ttf",
"NotoSansMalayalam-Regular",
"ttf")),
Map.entry(
FALLBACK_FONT_TIBETAN_ID,
new FallbackFontSpec(
"classpath:/static/fonts/NotoSerifTibetan-Regular.ttf",
"NotoSerifTibetan-Regular",
"ttf")),
// Liberation Sans family // Liberation Sans family
Map.entry( Map.entry(
"fallback-liberation-sans", "fallback-liberation-sans",
@@ -312,29 +268,12 @@ public class PdfJsonFallbackFontService {
"ttf"))); "ttf")));
private final ResourceLoader resourceLoader; private final ResourceLoader resourceLoader;
private final stirling.software.common.model.ApplicationProperties applicationProperties;
@Value("${stirling.pdf.fallback-font:" + DEFAULT_FALLBACK_FONT_LOCATION + "}") @Value("${stirling.pdf.fallback-font:" + DEFAULT_FALLBACK_FONT_LOCATION + "}")
private String legacyFallbackFontLocation;
private String fallbackFontLocation; private String fallbackFontLocation;
private final Map<String, byte[]> fallbackFontCache = new ConcurrentHashMap<>(); private final Map<String, byte[]> fallbackFontCache = new ConcurrentHashMap<>();
@jakarta.annotation.PostConstruct
private void loadConfig() {
String configured = null;
if (applicationProperties.getPdfEditor() != null) {
configured = applicationProperties.getPdfEditor().getFallbackFont();
}
if (configured != null && !configured.isBlank()) {
fallbackFontLocation = configured;
} else {
fallbackFontLocation = legacyFallbackFontLocation;
}
log.info("Using fallback font location: {}", fallbackFontLocation);
}
public PdfJsonFont buildFallbackFontModel() throws IOException { public PdfJsonFont buildFallbackFontModel() throws IOException {
return buildFallbackFontModel(FALLBACK_FONT_ID); return buildFallbackFontModel(FALLBACK_FONT_ID);
} }
@@ -545,20 +484,6 @@ public class PdfJsonFallbackFontService {
*/ */
public String resolveFallbackFontId(int codePoint) { public String resolveFallbackFontId(int codePoint) {
Character.UnicodeBlock block = Character.UnicodeBlock.of(codePoint); Character.UnicodeBlock block = Character.UnicodeBlock.of(codePoint);
// Bopomofo is primarily used in Taiwan for Traditional Chinese phonetic annotation
if (block == Character.UnicodeBlock.BOPOMOFO
|| block == Character.UnicodeBlock.BOPOMOFO_EXTENDED) {
return FALLBACK_FONT_TC_ID;
}
// Compatibility ideographs are primarily used by Traditional Chinese encodings (e.g., Big5,
// HKSCS) so prefer the Traditional Chinese fallback here.
if (block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT) {
return FALLBACK_FONT_TC_ID;
}
if (block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS if (block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
@@ -567,23 +492,19 @@ public class PdfJsonFallbackFontService {
|| block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E
|| block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_F || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_F
|| block == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || block == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| block == Character.UnicodeBlock.BOPOMOFO
|| block == Character.UnicodeBlock.BOPOMOFO_EXTENDED
|| block == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { || block == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return FALLBACK_FONT_CJK_ID; return FALLBACK_FONT_CJK_ID;
} }
Character.UnicodeScript script = Character.UnicodeScript.of(codePoint); Character.UnicodeScript script = Character.UnicodeScript.of(codePoint);
return switch (script) { return switch (script) {
// HAN script is used by both Simplified and Traditional Chinese
// Default to Simplified (mainland China, 1.4B speakers) as it's more common
// Traditional Chinese PDFs are detected via font name aliases (MingLiU, PMingLiU, etc.)
case HAN -> FALLBACK_FONT_CJK_ID; case HAN -> FALLBACK_FONT_CJK_ID;
case HIRAGANA, KATAKANA -> FALLBACK_FONT_JP_ID; case HIRAGANA, KATAKANA -> FALLBACK_FONT_JP_ID;
case HANGUL -> FALLBACK_FONT_KR_ID; case HANGUL -> FALLBACK_FONT_KR_ID;
case ARABIC -> FALLBACK_FONT_AR_ID; case ARABIC -> FALLBACK_FONT_AR_ID;
case THAI -> FALLBACK_FONT_TH_ID; case THAI -> FALLBACK_FONT_TH_ID;
case DEVANAGARI -> FALLBACK_FONT_DEVANAGARI_ID;
case MALAYALAM -> FALLBACK_FONT_MALAYALAM_ID;
case TIBETAN -> FALLBACK_FONT_TIBETAN_ID;
default -> FALLBACK_FONT_ID; default -> FALLBACK_FONT_ID;
}; };
} }
@@ -5,6 +5,7 @@ import java.nio.file.Files;
import java.util.Base64; import java.util.Base64;
import java.util.Locale; import java.util.Locale;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
@@ -24,16 +25,22 @@ import stirling.software.common.util.TempFileManager;
public class PdfJsonFontService { public class PdfJsonFontService {
private final TempFileManager tempFileManager; private final TempFileManager tempFileManager;
private final stirling.software.common.model.ApplicationProperties applicationProperties;
@Getter private boolean cffConversionEnabled; @Getter
@Value("${stirling.pdf.json.cff-converter.enabled:true}")
private boolean cffConversionEnabled;
@Getter private String cffConverterMethod; @Getter
@Value("${stirling.pdf.json.cff-converter.method:python}")
private String cffConverterMethod;
@Value("${stirling.pdf.json.cff-converter.python-command:/opt/venv/bin/python3}")
private String pythonCommand; private String pythonCommand;
@Value("${stirling.pdf.json.cff-converter.python-script:/scripts/convert_cff_to_ttf.py}")
private String pythonScript; private String pythonScript;
@Value("${stirling.pdf.json.cff-converter.fontforge-command:fontforge}")
private String fontforgeCommand; private String fontforgeCommand;
private volatile boolean pythonCffConverterAvailable; private volatile boolean pythonCffConverterAvailable;
@@ -41,7 +48,6 @@ public class PdfJsonFontService {
@PostConstruct @PostConstruct
private void initialiseCffConverterAvailability() { private void initialiseCffConverterAvailability() {
loadConfiguration();
if (!cffConversionEnabled) { if (!cffConversionEnabled) {
log.warn("[FONT-DEBUG] CFF conversion is DISABLED in configuration"); log.warn("[FONT-DEBUG] CFF conversion is DISABLED in configuration");
pythonCffConverterAvailable = false; pythonCffConverterAvailable = false;
@@ -71,22 +77,6 @@ public class PdfJsonFontService {
log.info("[FONT-DEBUG] Selected CFF converter method: {}", cffConverterMethod); log.info("[FONT-DEBUG] Selected CFF converter method: {}", cffConverterMethod);
} }
private void loadConfiguration() {
if (applicationProperties.getPdfEditor() != null
&& applicationProperties.getPdfEditor().getCffConverter() != null) {
var cfg = applicationProperties.getPdfEditor().getCffConverter();
this.cffConversionEnabled = cfg.isEnabled();
this.cffConverterMethod = cfg.getMethod();
this.pythonCommand = cfg.getPythonCommand();
this.pythonScript = cfg.getPythonScript();
this.fontforgeCommand = cfg.getFontforgeCommand();
} else {
// Use defaults when config is not available
this.cffConversionEnabled = false;
log.warn("[FONT-DEBUG] PdfEditor configuration not available, CFF conversion disabled");
}
}
public byte[] convertCffProgramToTrueType(byte[] fontBytes, String toUnicode) { public byte[] convertCffProgramToTrueType(byte[] fontBytes, String toUnicode) {
if (!cffConversionEnabled || fontBytes == null || fontBytes.length == 0) { if (!cffConversionEnabled || fontBytes == null || fontBytes.length == 0) {
log.warn( log.warn(
@@ -2,6 +2,7 @@ package stirling.software.SPDF.service.pdfjson.type3;
import java.io.IOException; import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -22,8 +23,8 @@ import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryPayl
public class Type3LibraryStrategy implements Type3ConversionStrategy { public class Type3LibraryStrategy implements Type3ConversionStrategy {
private final Type3FontLibrary fontLibrary; private final Type3FontLibrary fontLibrary;
private final stirling.software.common.model.ApplicationProperties applicationProperties;
@Value("${stirling.pdf.json.type3.library.enabled:true}")
private boolean enabled; private boolean enabled;
@Override @Override
@@ -41,19 +42,6 @@ public class Type3LibraryStrategy implements Type3ConversionStrategy {
return enabled && fontLibrary != null && fontLibrary.isLoaded(); return enabled && fontLibrary != null && fontLibrary.isLoaded();
} }
@jakarta.annotation.PostConstruct
private void loadConfiguration() {
if (applicationProperties.getPdfEditor() != null
&& applicationProperties.getPdfEditor().getType3() != null
&& applicationProperties.getPdfEditor().getType3().getLibrary() != null) {
var cfg = applicationProperties.getPdfEditor().getType3().getLibrary();
this.enabled = cfg.isEnabled();
} else {
this.enabled = false;
log.warn("PdfEditor Type3 library configuration not available, disabled");
}
}
@Override @Override
public PdfJsonFontConversionCandidate convert( public PdfJsonFontConversionCandidate convert(
Type3ConversionRequest request, Type3GlyphContext context) throws IOException { Type3ConversionRequest request, Type3GlyphContext context) throws IOException {
@@ -14,6 +14,7 @@ import java.util.stream.Collectors;
import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.font.PDType3Font; import org.apache.pdfbox.pdmodel.font.PDType3Font;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -33,8 +34,8 @@ public class Type3FontLibrary {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final ResourceLoader resourceLoader; private final ResourceLoader resourceLoader;
private final stirling.software.common.model.ApplicationProperties applicationProperties;
@Value("${stirling.pdf.json.type3.library.index:classpath:/type3/library/index.json}")
private String indexLocation; private String indexLocation;
private final Map<String, Type3FontLibraryEntry> signatureIndex = new ConcurrentHashMap<>(); private final Map<String, Type3FontLibraryEntry> signatureIndex = new ConcurrentHashMap<>();
@@ -43,17 +44,6 @@ public class Type3FontLibrary {
@jakarta.annotation.PostConstruct @jakarta.annotation.PostConstruct
void initialise() { void initialise() {
if (applicationProperties.getPdfEditor() != null
&& applicationProperties.getPdfEditor().getType3() != null
&& applicationProperties.getPdfEditor().getType3().getLibrary() != null) {
this.indexLocation =
applicationProperties.getPdfEditor().getType3().getLibrary().getIndex();
} else {
log.warn(
"[TYPE3] PdfEditor Type3 library configuration not available; Type3 library disabled");
entries = List.of();
return;
}
Resource resource = resourceLoader.getResource(indexLocation); Resource resource = resourceLoader.getResource(indexLocation);
if (!resource.exists()) { if (!resource.exists()) {
log.info("[TYPE3] Library index {} not found; Type3 library disabled", indexLocation); log.info("[TYPE3] Library index {} not found; Type3 library disabled", indexLocation);
@@ -94,22 +94,6 @@ public class ProprietaryUIDataController {
this.auditRepository = auditRepository; this.auditRepository = auditRepository;
} }
/**
* Get the backend base URL for SAML/OAuth redirects. Uses system.backendUrl from config if set,
* otherwise defaults to http://localhost:8080
*/
private String getBackendBaseUrl() {
String backendUrl = applicationProperties.getSystem().getBackendUrl();
// If backendUrl is configured, use it
if (backendUrl != null && !backendUrl.trim().isEmpty()) {
return backendUrl.trim();
}
// For development, default to localhost:8080 (backend port)
return "http://localhost:8080";
}
@GetMapping("/audit-dashboard") @GetMapping("/audit-dashboard")
@PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasRole('ADMIN')")
@EnterpriseEndpoint @EnterpriseEndpoint
@@ -201,17 +185,14 @@ public class ProprietaryUIDataController {
} }
SAML2 saml2 = securityProps.getSaml2(); SAML2 saml2 = securityProps.getSaml2();
if (securityProps.isSaml2Active() && applicationProperties.getPremium().isEnabled()) { if (securityProps.isSaml2Active()
&& applicationProperties.getSystem().getEnableAlphaFunctionality()
&& applicationProperties.getPremium().isEnabled()) {
String samlIdp = saml2.getProvider(); String samlIdp = saml2.getProvider();
String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId(); String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId();
// For SAML, we need to use the backend URL directly, not a relative path
// This ensures Spring Security generates the correct ACS URL
String backendUrl = getBackendBaseUrl();
String fullSamlPath = backendUrl + saml2AuthenticationPath;
if (!applicationProperties.getPremium().getProFeatures().isSsoAutoLogin()) { if (!applicationProperties.getPremium().getProFeatures().isSsoAutoLogin()) {
providerList.put(fullSamlPath, samlIdp + " (SAML 2)"); providerList.put(saml2AuthenticationPath, samlIdp + " (SAML 2)");
} }
} }
@@ -224,10 +205,6 @@ public class ProprietaryUIDataController {
data.setLoginMethod(securityProps.getLoginMethod()); data.setLoginMethod(securityProps.getLoginMethod());
data.setAltLogin(!providerList.isEmpty() && securityProps.isAltLogin()); data.setAltLogin(!providerList.isEmpty() && securityProps.isAltLogin());
// Add language configuration for login page
data.setLanguages(applicationProperties.getUi().getLanguages());
data.setDefaultLocale(applicationProperties.getSystem().getDefaultLocale());
return ResponseEntity.ok(data); return ResponseEntity.ok(data);
} }
@@ -351,7 +328,6 @@ public class ProprietaryUIDataController {
data.setGrandfatheredUserCount(grandfatheredCount); data.setGrandfatheredUserCount(grandfatheredCount);
data.setLicenseMaxUsers(licenseMaxUsers); data.setLicenseMaxUsers(licenseMaxUsers);
data.setPremiumEnabled(premiumEnabled); data.setPremiumEnabled(premiumEnabled);
data.setMailEnabled(applicationProperties.getMail().isEnabled());
return ResponseEntity.ok(data); return ResponseEntity.ok(data);
} }
@@ -400,7 +376,7 @@ public class ProprietaryUIDataController {
data.setUsername(username); data.setUsername(username);
data.setRole(user.get().getRolesAsString()); data.setRole(user.get().getRolesAsString());
data.setSettings(settingsJson); data.setSettings(settingsJson);
data.setChangeCredsFlag(user.get().isFirstLogin() || user.get().isForcePasswordChange()); data.setChangeCredsFlag(user.get().isFirstLogin());
data.setOAuth2Login(isOAuth2Login); data.setOAuth2Login(isOAuth2Login);
data.setSaml2Login(isSaml2Login); data.setSaml2Login(isSaml2Login);
@@ -515,8 +491,6 @@ public class ProprietaryUIDataController {
private boolean altLogin; private boolean altLogin;
private boolean firstTimeSetup; private boolean firstTimeSetup;
private boolean showDefaultCredentials; private boolean showDefaultCredentials;
private List<String> languages;
private String defaultLocale;
} }
@Data @Data
@@ -536,7 +510,6 @@ public class ProprietaryUIDataController {
private int grandfatheredUserCount; private int grandfatheredUserCount;
private int licenseMaxUsers; private int licenseMaxUsers;
private boolean premiumEnabled; private boolean premiumEnabled;
private boolean mailEnabled;
} }
@Data @Data
@@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.api.UserApi;
import stirling.software.common.configuration.InstallationPathConfig; import stirling.software.common.configuration.InstallationPathConfig;
import stirling.software.proprietary.model.api.signature.SavedSignatureRequest; import stirling.software.proprietary.model.api.signature.SavedSignatureRequest;
import stirling.software.proprietary.model.api.signature.SavedSignatureResponse; import stirling.software.proprietary.model.api.signature.SavedSignatureResponse;
@@ -33,6 +34,7 @@ import stirling.software.proprietary.service.SignatureService;
* authentication and enforces per-user storage limits. All endpoints require authentication * authentication and enforces per-user storage limits. All endpoints require authentication
* via @PreAuthorize("isAuthenticated()"). * via @PreAuthorize("isAuthenticated()").
*/ */
@UserApi
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("/api/v1/proprietary/signatures") @RequestMapping("/api/v1/proprietary/signatures")
@@ -120,7 +120,9 @@ public class AccountWebController {
SAML2 saml2 = securityProps.getSaml2(); SAML2 saml2 = securityProps.getSaml2();
if (securityProps.isSaml2Active() && applicationProperties.getPremium().isEnabled()) { if (securityProps.isSaml2Active()
&& applicationProperties.getSystem().getEnableAlphaFunctionality()
&& applicationProperties.getPremium().isEnabled()) {
String samlIdp = saml2.getProvider(); String samlIdp = saml2.getProvider();
String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId(); String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId();
@@ -33,8 +33,7 @@ public class MailConfig {
// Creates a new instance of JavaMailSenderImpl, which is a Spring implementation // Creates a new instance of JavaMailSenderImpl, which is a Spring implementation
JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
String host = mailProperties.getHost(); mailSender.setHost(mailProperties.getHost());
mailSender.setHost(host);
mailSender.setPort(mailProperties.getPort()); mailSender.setPort(mailProperties.getPort());
mailSender.setDefaultEncoding("UTF-8"); mailSender.setDefaultEncoding("UTF-8");
@@ -71,32 +70,8 @@ public class MailConfig {
log.info("SMTP authentication disabled - no credentials provided"); log.info("SMTP authentication disabled - no credentials provided");
} }
boolean startTlsEnabled =
mailProperties.getStartTlsEnable() == null || mailProperties.getStartTlsEnable();
// Enables STARTTLS to encrypt the connection if supported by the SMTP server // Enables STARTTLS to encrypt the connection if supported by the SMTP server
props.put("mail.smtp.starttls.enable", Boolean.toString(startTlsEnabled)); props.put("mail.smtp.starttls.enable", "true");
if (mailProperties.getStartTlsRequired() != null) {
props.put(
"mail.smtp.starttls.required", mailProperties.getStartTlsRequired().toString());
}
if (mailProperties.getSslEnable() != null) {
props.put("mail.smtp.ssl.enable", mailProperties.getSslEnable().toString());
}
// Trust the configured host to allow STARTTLS with self-signed certificates
String sslTrust = mailProperties.getSslTrust();
if (sslTrust == null || sslTrust.trim().isEmpty()) {
sslTrust = "*";
}
if (sslTrust != null && !sslTrust.trim().isEmpty()) {
props.put("mail.smtp.ssl.trust", sslTrust);
}
if (mailProperties.getSslCheckServerIdentity() != null) {
props.put(
"mail.smtp.ssl.checkserveridentity",
mailProperties.getSslCheckServerIdentity().toString());
}
// Returns the configured mail sender, ready to send emails // Returns the configured mail sender, ready to send emails
return mailSender; return mailSender;
@@ -1,6 +1,7 @@
package stirling.software.proprietary.security.configuration; package stirling.software.proprietary.security.configuration;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
@@ -24,6 +25,8 @@ import org.springframework.security.saml2.provider.service.web.authentication.Op
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
import org.springframework.security.web.savedrequest.NullRequestCache; import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfiguration;
@@ -44,6 +47,7 @@ import stirling.software.proprietary.security.database.repository.PersistentLogi
import stirling.software.proprietary.security.filter.IPRateLimitingFilter; import stirling.software.proprietary.security.filter.IPRateLimitingFilter;
import stirling.software.proprietary.security.filter.JwtAuthenticationFilter; import stirling.software.proprietary.security.filter.JwtAuthenticationFilter;
import stirling.software.proprietary.security.filter.UserAuthenticationFilter; import stirling.software.proprietary.security.filter.UserAuthenticationFilter;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.oauth2.CustomOAuth2AuthenticationFailureHandler; import stirling.software.proprietary.security.oauth2.CustomOAuth2AuthenticationFailureHandler;
import stirling.software.proprietary.security.oauth2.CustomOAuth2AuthenticationSuccessHandler; import stirling.software.proprietary.security.oauth2.CustomOAuth2AuthenticationSuccessHandler;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationFailureHandler; import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationFailureHandler;
@@ -194,19 +198,74 @@ public class SecurityConfiguration {
http.cors(cors -> cors.disable()); http.cors(cors -> cors.disable());
} }
http.csrf(CsrfConfigurer::disable); if (securityProperties.getCsrfDisabled() || !loginEnabledValue) {
http.csrf(CsrfConfigurer::disable);
}
if (loginEnabledValue) { if (loginEnabledValue) {
boolean v2Enabled = appConfig.v2Enabled();
http.addFilterBefore( http.addFilterBefore(
userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(rateLimitingFilter, UsernamePasswordAuthenticationFilter.class) .addFilterBefore(rateLimitingFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UserAuthenticationFilter.class); .addFilterBefore(jwtAuthenticationFilter, UserAuthenticationFilter.class);
if (!securityProperties.getCsrfDisabled()) {
CookieCsrfTokenRepository cookieRepo =
CookieCsrfTokenRepository.withHttpOnlyFalse();
CsrfTokenRequestAttributeHandler requestHandler =
new CsrfTokenRequestAttributeHandler();
requestHandler.setCsrfRequestAttributeName(null);
http.csrf(
csrf ->
csrf.ignoringRequestMatchers(
request -> {
String uri = request.getRequestURI();
// Ignore CSRF for auth endpoints
if (uri.startsWith("/api/v1/auth/")) {
return true;
}
String apiKey = request.getHeader("X-API-KEY");
// If there's no API key, don't ignore CSRF
// (return false)
if (apiKey == null || apiKey.trim().isEmpty()) {
return false;
}
// Validate API key using existing UserService
try {
Optional<User> user =
userService.getUserByApiKey(apiKey);
// If API key is valid, ignore CSRF (return
// true)
// If API key is invalid, don't ignore CSRF
// (return false)
return user.isPresent();
} catch (Exception e) {
// If there's any error validating the API
// key, don't ignore CSRF
return false;
}
})
.csrfTokenRepository(cookieRepo)
.csrfTokenRequestHandler(requestHandler));
}
http.sessionManagement( http.sessionManagement(
sessionManagement -> sessionManagement -> {
if (v2Enabled) {
sessionManagement.sessionCreationPolicy( sessionManagement.sessionCreationPolicy(
SessionCreationPolicy.STATELESS)); SessionCreationPolicy.STATELESS);
} else {
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(10)
.maxSessionsPreventsLogin(false)
.sessionRegistry(sessionRegistry)
.expiredUrl("/login?logout=true");
}
});
http.authenticationProvider(daoAuthenticationProvider()); http.authenticationProvider(daoAuthenticationProvider());
http.requestCache(requestCache -> requestCache.requestCache(new NullRequestCache())); http.requestCache(requestCache -> requestCache.requestCache(new NullRequestCache()));
@@ -272,9 +331,7 @@ public class SecurityConfiguration {
formLogin -> formLogin ->
formLogin formLogin
.loginPage("/login") // Redirect here when unauthenticated .loginPage("/login") // Redirect here when unauthenticated
.loginProcessingUrl( .loginProcessingUrl("/perform_login") // Process form posts here (not /login)
"/perform_login") // Process form posts here (not
// /login)
.successHandler( .successHandler(
new CustomAuthenticationSuccessHandler( new CustomAuthenticationSuccessHandler(
loginAttemptService, loginAttemptService,
@@ -289,7 +346,18 @@ public class SecurityConfiguration {
if (securityProperties.isOauth2Active()) { if (securityProperties.isOauth2Active()) {
http.oauth2Login( http.oauth2Login(
oauth2 -> { oauth2 -> {
oauth2.loginPage("/login") // v1: Use /oauth2 as login page for Thymeleaf templates
if (!v2Enabled) {
oauth2.loginPage("/oauth2");
}
// v2: Don't set loginPage, let default OAuth2 flow handle it
oauth2
/*
This Custom handler is used to check if the OAUTH2 user trying to log in, already exists in the database.
If user exists, login proceeds as usual. If user does not exist, then it is auto-created but only if 'OAUTH2AutoCreateUser'
is set as true, else login fails with an error message advising the same.
*/
.successHandler( .successHandler(
new CustomOAuth2AuthenticationSuccessHandler( new CustomOAuth2AuthenticationSuccessHandler(
loginAttemptService, loginAttemptService,
@@ -323,8 +391,12 @@ public class SecurityConfiguration {
.saml2Login( .saml2Login(
saml2 -> { saml2 -> {
try { try {
saml2.loginPage("/login") // Only set login page for v1/Thymeleaf mode
.relyingPartyRegistrationRepository( if (!v2Enabled) {
saml2.loginPage("/saml2");
}
saml2.relyingPartyRegistrationRepository(
saml2RelyingPartyRegistrations) saml2RelyingPartyRegistrations)
.authenticationManager( .authenticationManager(
new ProviderManager(authenticationProvider)) new ProviderManager(authenticationProvider))
@@ -334,8 +406,7 @@ public class SecurityConfiguration {
securityProperties.getSaml2(), securityProperties.getSaml2(),
userService, userService,
jwtService, jwtService,
licenseSettingsService, licenseSettingsService))
applicationProperties))
.failureHandler( .failureHandler(
new CustomSaml2AuthenticationFailureHandler()) new CustomSaml2AuthenticationFailureHandler())
.authenticationRequestResolver( .authenticationRequestResolver(
@@ -244,13 +244,10 @@ public class AuthController {
userMap.put("username", user.getUsername()); userMap.put("username", user.getUsername());
userMap.put("role", user.getRolesAsString()); userMap.put("role", user.getRolesAsString());
userMap.put("enabled", user.isEnabled()); userMap.put("enabled", user.isEnabled());
userMap.put(
"authenticationType",
user.getAuthenticationType()); // Expose authentication type for SSO detection
// Add metadata for OAuth compatibility // Add metadata for OAuth compatibility
Map<String, Object> appMetadata = new HashMap<>(); Map<String, Object> appMetadata = new HashMap<>();
appMetadata.put("provider", user.getAuthenticationType()); appMetadata.put("provider", user.getAuthenticationType()); // Default to email provider
userMap.put("app_metadata", appMetadata); userMap.put("app_metadata", appMetadata);
return userMap; return userMap;
@@ -7,7 +7,6 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -19,7 +18,6 @@ import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import jakarta.transaction.Transactional; import jakarta.transaction.Transactional;
@@ -238,8 +236,6 @@ public class UserController {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED) return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", "incorrectPassword", "message", "Incorrect password")); .body(Map.of("error", "incorrectPassword", "message", "Incorrect password"));
} }
// Set flags before changing password so they're saved together
user.setForcePasswordChange(false);
userService.changePassword(user, newPassword); userService.changePassword(user, newPassword);
userService.changeFirstUse(user, false); userService.changeFirstUse(user, false);
// Logout using Spring's utility // Logout using Spring's utility
@@ -588,79 +584,6 @@ public class UserController {
return ResponseEntity.ok(Map.of("message", "User role updated successfully")); return ResponseEntity.ok(Map.of("message", "User role updated successfully"));
} }
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/changePasswordForUser")
public ResponseEntity<?> changePasswordForUser(
@RequestParam(name = "username") String username,
@RequestParam(name = "newPassword", required = false) String newPassword,
@RequestParam(name = "generateRandom", defaultValue = "false") boolean generateRandom,
@RequestParam(name = "sendEmail", defaultValue = "false") boolean sendEmail,
@RequestParam(name = "includePassword", defaultValue = "false") boolean includePassword,
@RequestParam(name = "forcePasswordChange", defaultValue = "false")
boolean forcePasswordChange,
HttpServletRequest request,
Authentication authentication)
throws SQLException, UnsupportedProviderException, MessagingException {
Optional<User> userOpt = userService.findByUsernameIgnoreCase(username);
if (userOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(Map.of("error", "User not found."));
}
String currentUsername = authentication.getName();
if (currentUsername.equalsIgnoreCase(username)) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Cannot change your own password."));
}
User user = userOpt.get();
String finalPassword = newPassword;
if (generateRandom) {
finalPassword = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
}
if (finalPassword == null || finalPassword.trim().isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "New password is required."));
}
// Set force password change flag before changing password so both are saved together
user.setForcePasswordChange(forcePasswordChange);
userService.changePassword(user, finalPassword);
// Invalidate all active sessions to force reauthentication
userService.invalidateUserSessions(username);
if (sendEmail) {
if (emailService.isEmpty() || !applicationProperties.getMail().isEnabled()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "Email is not configured."));
}
String userEmail = user.getUsername();
// Check if username is a valid email format
if (userEmail == null || userEmail.isBlank() || !userEmail.contains("@")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(
Map.of(
"error",
"User's email is not a valid email address. Notifications are disabled."));
}
String loginUrl = buildLoginUrl(request);
emailService
.get()
.sendPasswordChangedNotification(
userEmail,
user.getUsername(),
includePassword ? finalPassword : null,
loginUrl);
}
return ResponseEntity.ok(Map.of("message", "User password updated successfully"));
}
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/changeUserEnabled/{username}") @PostMapping("/admin/changeUserEnabled/{username}")
public ResponseEntity<?> changeUserEnabled( public ResponseEntity<?> changeUserEnabled(
@@ -26,7 +26,6 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties; import stirling.software.common.model.ApplicationProperties;
@@ -40,7 +39,6 @@ import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.UserService; import stirling.software.proprietary.security.service.UserService;
@Slf4j @Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter { public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtServiceInterface jwtService; private final JwtServiceInterface jwtService;
@@ -49,6 +47,19 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final AuthenticationEntryPoint authenticationEntryPoint; private final AuthenticationEntryPoint authenticationEntryPoint;
private final ApplicationProperties.Security securityProperties; private final ApplicationProperties.Security securityProperties;
public JwtAuthenticationFilter(
JwtServiceInterface jwtService,
UserService userService,
CustomUserDetailsService userDetailsService,
AuthenticationEntryPoint authenticationEntryPoint,
ApplicationProperties.Security securityProperties) {
this.jwtService = jwtService;
this.userService = userService;
this.userDetailsService = userDetailsService;
this.authenticationEntryPoint = authenticationEntryPoint;
this.securityProperties = securityProperties;
}
@Override @Override
protected void doFilterInternal( protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
@@ -57,11 +68,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
return; return;
} }
if (isStaticResource(request.getContextPath(), request.getRequestURI())) {
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
if (isStaticResource(contextPath, requestURI)) {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
return; return;
} }
@@ -70,7 +77,10 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
String jwtToken = jwtService.extractToken(request); String jwtToken = jwtService.extractToken(request);
if (jwtToken == null) { if (jwtToken == null) {
// Allow auth endpoints to pass through without JWT // Allow specific auth endpoints to pass through without JWT
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
if (!isPublicAuthEndpoint(requestURI, contextPath)) { if (!isPublicAuthEndpoint(requestURI, contextPath)) {
// For API requests, return 401 JSON // For API requests, return 401 JSON
String acceptHeader = request.getHeader("Accept"); String acceptHeader = request.getHeader("Accept");
@@ -241,6 +241,24 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
} }
private static boolean isPublicAuthEndpoint(String requestURI, String contextPath) {
// Remove context path from URI to normalize path matching
String trimmedUri =
requestURI.startsWith(contextPath)
? requestURI.substring(contextPath.length())
: requestURI;
// Public auth endpoints that don't require authentication
return trimmedUri.startsWith("/login")
|| trimmedUri.startsWith("/auth/")
|| trimmedUri.startsWith("/oauth2")
|| trimmedUri.startsWith("/saml2")
|| trimmedUri.startsWith("/api/v1/auth/login")
|| trimmedUri.startsWith("/api/v1/auth/refresh")
|| trimmedUri.startsWith("/api/v1/auth/logout")
|| trimmedUri.startsWith("/api/v1/proprietary/ui-data/login");
}
private enum UserLoginType { private enum UserLoginType {
USERDETAILS("UserDetails"), USERDETAILS("UserDetails"),
OAUTH2USER("OAuth2User"), OAUTH2USER("OAuth2User"),
@@ -59,9 +59,6 @@ public class User implements UserDetails, Serializable {
@Column(name = "hasCompletedInitialSetup") @Column(name = "hasCompletedInitialSetup")
private Boolean hasCompletedInitialSetup = false; private Boolean hasCompletedInitialSetup = false;
@Column(name = "forcePasswordChange")
private Boolean forcePasswordChange = false;
@Column(name = "roleName") @Column(name = "roleName")
private String roleName; private String roleName;
@@ -120,14 +117,6 @@ public class User implements UserDetails, Serializable {
this.hasCompletedInitialSetup = hasCompletedInitialSetup; this.hasCompletedInitialSetup = hasCompletedInitialSetup;
} }
public boolean isForcePasswordChange() {
return forcePasswordChange != null && forcePasswordChange;
}
public void setForcePasswordChange(boolean forcePasswordChange) {
this.forcePasswordChange = forcePasswordChange;
}
public void setAuthenticationType(AuthenticationType authenticationType) { public void setAuthenticationType(AuthenticationType authenticationType) {
this.authenticationType = authenticationType.toString().toLowerCase(); this.authenticationType = authenticationType.toString().toLowerCase();
} }
@@ -27,7 +27,6 @@ import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties; import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.exception.UnsupportedProviderException; import stirling.software.common.model.exception.UnsupportedProviderException;
@@ -40,7 +39,6 @@ import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.LoginAttemptService; import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.UserService; import stirling.software.proprietary.security.service.UserService;
@Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
public class CustomOAuth2AuthenticationSuccessHandler public class CustomOAuth2AuthenticationSuccessHandler
extends SavedRequestAwareAuthenticationSuccessHandler { extends SavedRequestAwareAuthenticationSuccessHandler {
@@ -79,18 +77,12 @@ public class CustomOAuth2AuthenticationSuccessHandler
if (user != null && !licenseSettingsService.isOAuthEligible(user)) { if (user != null && !licenseSettingsService.isOAuthEligible(user)) {
// User is not grandfathered and no paid license - block OAuth login // User is not grandfathered and no paid license - block OAuth login
log.warn(
"OAuth login blocked for existing user '{}' - not eligible (not grandfathered and no paid license)",
username);
response.sendRedirect( response.sendRedirect(
request.getContextPath() + "/logout?oAuth2RequiresLicense=true"); request.getContextPath() + "/logout?oAuth2RequiresLicense=true");
return; return;
} }
} else if (!licenseSettingsService.isOAuthEligible(null)) { } else if (!licenseSettingsService.isOAuthEligible(null)) {
// No existing user and no paid license -> block auto creation // No existing user and no paid license -> block auto creation
log.warn(
"OAuth login blocked for new user '{}' - not eligible (no paid license for auto-creation)",
username);
response.sendRedirect(request.getContextPath() + "/logout?oAuth2RequiresLicense=true"); response.sendRedirect(request.getContextPath() + "/logout?oAuth2RequiresLicense=true");
return; return;
} }
@@ -67,15 +67,10 @@ public class OAuth2Configuration {
keycloakClientRegistration().ifPresent(registrations::add); keycloakClientRegistration().ifPresent(registrations::add);
if (registrations.isEmpty()) { if (registrations.isEmpty()) {
log.error("No OAuth2 provider registered - check your OAuth2 configuration"); log.error("No OAuth2 provider registered");
throw new NoProviderFoundException("At least one OAuth2 provider must be configured."); throw new NoProviderFoundException("At least one OAuth2 provider must be configured.");
} }
log.info(
"OAuth2 ClientRegistrationRepository created with {} provider(s): {}",
registrations.size(),
registrations.stream().map(ClientRegistration::getRegistrationId).toList());
return new InMemoryClientRegistrationRepository(registrations); return new InMemoryClientRegistrationRepository(registrations);
} }
@@ -170,6 +165,7 @@ public class OAuth2Configuration {
githubClient.getUseAsUsername()); githubClient.getUseAsUsername());
boolean isValid = validateProvider(github); boolean isValid = validateProvider(github);
log.info("Initialised GitHub OAuth2 provider");
return isValid return isValid
? Optional.of( ? Optional.of(
@@ -212,19 +208,7 @@ public class OAuth2Configuration {
null, null,
null); null);
boolean isValid = return !isStringEmpty(oidcProvider.getIssuer()) || validateProvider(oidcProvider)
!isStringEmpty(oidcProvider.getIssuer()) || validateProvider(oidcProvider);
if (isValid) {
log.info(
"Initialised OIDC OAuth2 provider: registrationId='{}', issuer='{}', redirectUri='{}'",
name,
oauth.getIssuer(),
REDIRECT_URI_PATH + name);
} else {
log.warn("OIDC OAuth2 provider validation failed - provider will not be registered");
}
return isValid
? Optional.of( ? Optional.of(
ClientRegistrations.fromIssuerLocation(oauth.getIssuer()) ClientRegistrations.fromIssuerLocation(oauth.getIssuer())
.registrationId(name) .registrationId(name)
@@ -233,7 +217,7 @@ public class OAuth2Configuration {
.scope(oidcProvider.getScopes()) .scope(oidcProvider.getScopes())
.userNameAttributeName(oidcProvider.getUseAsUsername().getName()) .userNameAttributeName(oidcProvider.getUseAsUsername().getName())
.clientName(clientName) .clientName(clientName)
.redirectUri(REDIRECT_URI_PATH + name) .redirectUri(REDIRECT_URI_PATH + "oidc")
.authorizationGrantType(AUTHORIZATION_CODE) .authorizationGrantType(AUTHORIZATION_CODE)
.build()) .build())
: Optional.empty(); : Optional.empty();
@@ -51,7 +51,6 @@ public class CustomSaml2AuthenticationSuccessHandler
private final JwtServiceInterface jwtService; private final JwtServiceInterface jwtService;
private final stirling.software.proprietary.service.UserLicenseSettingsService private final stirling.software.proprietary.service.UserLicenseSettingsService
licenseSettingsService; licenseSettingsService;
private final ApplicationProperties applicationProperties;
@Override @Override
@Audited(type = AuditEventType.USER_LOGIN, level = AuditLevel.BASIC) @Audited(type = AuditEventType.USER_LOGIN, level = AuditLevel.BASIC)
@@ -75,20 +74,14 @@ public class CustomSaml2AuthenticationSuccessHandler
if (user != null && !licenseSettingsService.isSamlEligible(user)) { if (user != null && !licenseSettingsService.isSamlEligible(user)) {
// User is not grandfathered and no ENTERPRISE license - block SAML login // User is not grandfathered and no ENTERPRISE license - block SAML login
log.warn( response.sendRedirect(
"SAML2 login blocked for existing user '{}' - not eligible (not grandfathered and no ENTERPRISE license)", request.getContextPath() + "/logout?saml2RequiresLicense=true");
username);
String origin = resolveOrigin(request);
response.sendRedirect(origin + "/logout?saml2RequiresLicense=true");
return; return;
} }
} else if (!licenseSettingsService.isSamlEligible(null)) { } else if (!licenseSettingsService.isSamlEligible(null)) {
// No existing user and no ENTERPRISE license -> block auto creation // No existing user and no ENTERPRISE license -> block auto creation
log.warn( response.sendRedirect(
"SAML2 login blocked for new user '{}' - not eligible (no ENTERPRISE license for auto-creation)", request.getContextPath() + "/logout?saml2RequiresLicense=true");
username);
String origin = resolveOrigin(request);
response.sendRedirect(origin + "/logout?saml2RequiresLicense=true");
return; return;
} }
@@ -145,28 +138,20 @@ public class CustomSaml2AuthenticationSuccessHandler
log.debug( log.debug(
"User {} exists with password but is not SSO user, redirecting to logout", "User {} exists with password but is not SSO user, redirecting to logout",
username); username);
String origin = resolveOrigin(request); response.sendRedirect(
response.sendRedirect(origin + "/logout?oAuth2AuthenticationErrorWeb=true"); contextPath + "/logout?oAuth2AuthenticationErrorWeb=true");
return; return;
} }
try { try {
// Block new users only if: blockRegistration is true OR autoCreateUser is false if (!userExists || saml2Properties.getBlockRegistration()) {
if (!userExists log.debug("Registration blocked for new user: {}", username);
&& (saml2Properties.getBlockRegistration() response.sendRedirect(
|| !saml2Properties.getAutoCreateUser())) { contextPath + "/login?errorOAuth=oAuth2AdminBlockedUser");
log.debug(
"Registration blocked for new user '{}' (blockRegistration: {}, autoCreateUser: {})",
username,
saml2Properties.getBlockRegistration(),
saml2Properties.getAutoCreateUser());
String origin = resolveOrigin(request);
response.sendRedirect(origin + "/login?errorOAuth=oAuth2AdminBlockedUser");
return; return;
} }
if (!userExists && licenseSettingsService.wouldExceedLimit(1)) { if (!userExists && licenseSettingsService.wouldExceedLimit(1)) {
String origin = resolveOrigin(request); response.sendRedirect(contextPath + "/logout?maxUsersReached=true");
response.sendRedirect(origin + "/logout?maxUsersReached=true");
return; return;
} }
@@ -231,30 +216,16 @@ public class CustomSaml2AuthenticationSuccessHandler
String contextPath, String contextPath,
String jwt) { String jwt) {
String redirectPath = resolveRedirectPath(request, contextPath); String redirectPath = resolveRedirectPath(request, contextPath);
String origin = resolveOrigin(request); String origin =
resolveForwardedOrigin(request)
.orElseGet(
() ->
resolveOriginFromReferer(request)
.orElseGet(() -> buildOriginFromRequest(request)));
clearRedirectCookie(response); clearRedirectCookie(response);
return origin + redirectPath + "#access_token=" + jwt; return origin + redirectPath + "#access_token=" + jwt;
} }
/**
* Resolve the origin (frontend URL) for redirects. First checks system.frontendUrl from config,
* then falls back to detecting from request headers.
*/
private String resolveOrigin(HttpServletRequest request) {
// First check if frontendUrl is configured
String configuredFrontendUrl = applicationProperties.getSystem().getFrontendUrl();
if (configuredFrontendUrl != null && !configuredFrontendUrl.trim().isEmpty()) {
return configuredFrontendUrl.trim();
}
// Fall back to auto-detection from request headers
return resolveForwardedOrigin(request)
.orElseGet(
() ->
resolveOriginFromReferer(request)
.orElseGet(() -> buildOriginFromRequest(request)));
}
private String resolveRedirectPath(HttpServletRequest request, String contextPath) { private String resolveRedirectPath(HttpServletRequest request, String contextPath) {
return extractRedirectPathFromCookie(request) return extractRedirectPathFromCookie(request)
.filter(path -> path.startsWith("/")) .filter(path -> path.startsWith("/"))
@@ -41,74 +41,22 @@ public class Saml2Configuration {
@ConditionalOnProperty(name = "security.saml2.enabled", havingValue = "true") @ConditionalOnProperty(name = "security.saml2.enabled", havingValue = "true")
public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception { public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
SAML2 samlConf = applicationProperties.getSecurity().getSaml2(); SAML2 samlConf = applicationProperties.getSecurity().getSaml2();
X509Certificate idpCert = CertificateUtils.readCertificate(samlConf.getIdpCert());
log.info(
"Initializing SAML2 configuration with registration ID: {}",
samlConf.getRegistrationId());
// Load IdP certificate
X509Certificate idpCert;
try {
Resource idpCertResource = samlConf.getIdpCert();
log.info("Loading IdP certificate from: {}", idpCertResource.getDescription());
if (!idpCertResource.exists()) {
log.error(
"SAML2 IdP certificate not found at: {}", idpCertResource.getDescription());
throw new IllegalStateException(
"SAML2 IdP certificate file does not exist: "
+ idpCertResource.getDescription());
}
idpCert = CertificateUtils.readCertificate(idpCertResource);
log.info(
"Successfully loaded IdP certificate. Subject: {}",
idpCert.getSubjectX500Principal().getName());
} catch (Exception e) {
log.error("Failed to load SAML2 IdP certificate: {}", e.getMessage(), e);
throw new IllegalStateException("Failed to load SAML2 IdP certificate", e);
}
Saml2X509Credential verificationCredential = Saml2X509Credential.verification(idpCert); Saml2X509Credential verificationCredential = Saml2X509Credential.verification(idpCert);
// Load SP private key and certificate
Resource privateKeyResource = samlConf.getPrivateKey(); Resource privateKeyResource = samlConf.getPrivateKey();
Resource certificateResource = samlConf.getSpCert(); Resource certificateResource = samlConf.getSpCert();
Saml2X509Credential signingCredential =
log.info("Loading SP private key from: {}", privateKeyResource.getDescription()); new Saml2X509Credential(
if (!privateKeyResource.exists()) { CertificateUtils.readPrivateKey(privateKeyResource),
log.error("SAML2 SP private key not found at: {}", privateKeyResource.getDescription()); CertificateUtils.readCertificate(certificateResource),
throw new IllegalStateException( Saml2X509CredentialType.SIGNING);
"SAML2 SP private key file does not exist: "
+ privateKeyResource.getDescription());
}
log.info("Loading SP certificate from: {}", certificateResource.getDescription());
if (!certificateResource.exists()) {
log.error(
"SAML2 SP certificate not found at: {}", certificateResource.getDescription());
throw new IllegalStateException(
"SAML2 SP certificate file does not exist: "
+ certificateResource.getDescription());
}
Saml2X509Credential signingCredential;
try {
signingCredential =
new Saml2X509Credential(
CertificateUtils.readPrivateKey(privateKeyResource),
CertificateUtils.readCertificate(certificateResource),
Saml2X509CredentialType.SIGNING);
log.info("Successfully loaded SP credentials");
} catch (Exception e) {
log.error("Failed to load SAML2 SP credentials: {}", e.getMessage(), e);
throw new IllegalStateException("Failed to load SAML2 SP credentials", e);
}
RelyingPartyRegistration rp = RelyingPartyRegistration rp =
RelyingPartyRegistration.withRegistrationId(samlConf.getRegistrationId()) RelyingPartyRegistration.withRegistrationId(samlConf.getRegistrationId())
.signingX509Credentials(c -> c.add(signingCredential)) .signingX509Credentials(c -> c.add(signingCredential))
.entityId(samlConf.getIdpIssuer()) .entityId(samlConf.getIdpIssuer())
.singleLogoutServiceBinding(Saml2MessageBinding.POST) .singleLogoutServiceBinding(Saml2MessageBinding.POST)
.singleLogoutServiceLocation(samlConf.getIdpSingleLogoutUrl()) .singleLogoutServiceLocation(samlConf.getIdpSingleLogoutUrl())
.singleLogoutServiceResponseLocation("{baseUrl}/login") .singleLogoutServiceResponseLocation("http://localhost:8080/login")
.assertionConsumerServiceBinding(Saml2MessageBinding.POST) .assertionConsumerServiceBinding(Saml2MessageBinding.POST)
.assertionConsumerServiceLocation( .assertionConsumerServiceLocation(
"{baseUrl}/login/saml2/sso/{registrationId}") "{baseUrl}/login/saml2/sso/{registrationId}")
@@ -127,14 +75,9 @@ public class Saml2Configuration {
.singleLogoutServiceLocation( .singleLogoutServiceLocation(
samlConf.getIdpSingleLogoutUrl()) samlConf.getIdpSingleLogoutUrl())
.singleLogoutServiceResponseLocation( .singleLogoutServiceResponseLocation(
"{baseUrl}/login") "http://localhost:8080/login")
.wantAuthnRequestsSigned(true)) .wantAuthnRequestsSigned(true))
.build(); .build();
log.info(
"SAML2 configuration initialized successfully. Registration ID: {}, IdP: {}",
samlConf.getRegistrationId(),
samlConf.getIdpIssuer());
return new InMemoryRelyingPartyRegistrationRepository(rp); return new InMemoryRelyingPartyRegistrationRepository(rp);
} }
@@ -223,54 +223,4 @@ public class EmailService {
sendPlainEmail(to, subject, body, true); sendPlainEmail(to, subject, body, true);
} }
@Async
public void sendPasswordChangedNotification(
String to, String username, String newPassword, String loginUrl)
throws MessagingException {
String subject = "Your Stirling PDF password has been updated";
String passwordSection =
newPassword == null
? ""
: """
<div style=\"background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; border-radius: 4px;\">
<p style=\"margin: 0;\"><strong>Temporary Password:</strong> %s</p>
</div>
"""
.formatted(newPassword);
String body =
"""
<html><body style=\"margin: 0; padding: 0;\">
<div style=\"font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;\">
<div style=\"max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;\">
<div style=\"text-align: center; padding: 20px; background-color: #222;\">
<img src=\"https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/main/docs/stirling-transparent.svg\" alt=\"Stirling PDF\" style=\"max-height: 60px;\">
</div>
<div style=\"padding: 30px; color: #333;\">
<h2 style=\"color: #222; margin-top: 0;\">Your password was changed</h2>
<p>Hello %s,</p>
<p>An administrator has updated the password for your Stirling PDF account.</p>
%s
<p>If you did not expect this change, please contact your administrator immediately.</p>
<div style=\"text-align: center; margin: 30px 0;\">
<a href=\"%s\" style=\"display: inline-block; background-color: #007bff; color: #ffffff; padding: 14px 28px; text-decoration: none; border-radius: 5px; font-weight: bold;\">Go to Stirling PDF</a>
</div>
<p style=\"font-size: 14px; color: #666;\">Or copy and paste this link in your browser:</p>
<div style=\"background-color: #f8f9fa; padding: 12px; margin: 15px 0; border-radius: 4px; word-break: break-all; font-size: 13px; color: #555;\">
%s
</div>
</div>
<div style=\"text-align: center; padding: 15px; font-size: 12px; color: #777; background-color: #f0f0f0;\">
&copy; 2025 Stirling PDF. All rights reserved.
</div>
</div>
</div>
</body></html>
"""
.formatted(username, passwordSection, loginUrl, loginUrl);
sendPlainEmail(to, subject, body, true);
}
} }
@@ -1,81 +0,0 @@
package stirling.software.proprietary.service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.service.LineArtConversionService;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
@Slf4j
@Service
public class ImageMagickLineArtConversionService implements LineArtConversionService {
@Override
public PDImageXObject convertImageToLineArt(
PDDocument doc, PDImageXObject originalImage, double threshold, int edgeLevel)
throws IOException {
Path inputImage = Files.createTempFile("lineart_image_input_", ".png");
Path outputImage = Files.createTempFile("lineart_image_output_", ".tiff");
try {
ImageIO.write(originalImage.getImage(), "png", inputImage.toFile());
List<String> command = new ArrayList<>();
command.add("magick");
command.add(inputImage.toString());
command.add("-colorspace");
command.add("Gray");
// Edge-aware line art conversion using ImageMagick's built-in operators.
// -edge/-negate/-normalize are standard convert options (IM v6+/v7) that
// accentuate outlines before thresholding to a bilevel image.
command.add("-edge");
command.add(String.valueOf(edgeLevel));
command.add("-negate");
command.add("-normalize");
command.add("-type");
command.add("Bilevel");
command.add("-threshold");
command.add(String.format(Locale.ROOT, "%.1f%%", threshold));
command.add("-compress");
command.add("Group4");
command.add(outputImage.toString());
ProcessExecutorResult result =
ProcessExecutor.getInstance(ProcessExecutor.Processes.IMAGEMAGICK)
.runCommandWithOutputHandling(command);
if (result.getRc() != 0) {
log.warn(
"ImageMagick line art conversion failed with return code: {}",
result.getRc());
throw new IOException("ImageMagick line art conversion failed");
}
byte[] convertedBytes = Files.readAllBytes(outputImage);
return PDImageXObject.createFromByteArray(
doc, convertedBytes, originalImage.getCOSObject().toString());
} catch (Exception e) {
log.warn("ImageMagick line art conversion failed", e);
throw new IOException("ImageMagick line art conversion failed", e);
} finally {
Files.deleteIfExists(inputImage);
Files.deleteIfExists(outputImage);
}
}
}
@@ -21,7 +21,6 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.model.UserLicenseSettings; import stirling.software.proprietary.model.UserLicenseSettings;
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License; import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker; import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.UserLicenseSettingsRepository; import stirling.software.proprietary.security.repository.UserLicenseSettingsRepository;
import stirling.software.proprietary.security.service.UserService; import stirling.software.proprietary.security.service.UserService;
@@ -177,13 +176,6 @@ public class UserLicenseSettingsService {
*/ */
@Transactional @Transactional
public void grandfatherExistingOAuthUsers() { public void grandfatherExistingOAuthUsers() {
// Only grandfather users if this is a V1→V2 upgrade, not a fresh V2 install
Boolean isNewServer = applicationProperties.getAutomaticallyGenerated().getIsNewServer();
if (Boolean.TRUE.equals(isNewServer)) {
log.info("Fresh V2 installation detected - skipping OAuth user grandfathering");
return;
}
UserLicenseSettings settings = getOrCreateSettings(); UserLicenseSettings settings = getOrCreateSettings();
// Check if we've already run this migration // Check if we've already run this migration
@@ -339,38 +331,29 @@ public class UserLicenseSettingsService {
} }
/** /**
* Checks if a user is eligible to use OAuth/SAML authentication. * Checks if a user is eligible to use OAuth authentication.
* *
* <p>A user is eligible if: * <p>A user is eligible if:
* *
* <ul> * <ul>
* <li>They are grandfathered for OAuth (existing user before policy change), OR * <li>They are grandfathered for OAuth (existing user before policy change), OR
* <li>The system has an ENTERPRISE license (SSO is enterprise-only) * <li>The system has a paid license (SERVER or ENTERPRISE)
* </ul> * </ul>
* *
* @param user The user to check * @param user The user to check
* @return true if the user can use OAuth/SAML * @return true if the user can use OAuth
*/ */
public boolean isOAuthEligible(User user) { public boolean isOAuthEligible(stirling.software.proprietary.security.model.User user) {
String username = (user != null) ? user.getUsername() : "<new user>"; // Grandfathered users always have OAuth access
log.info("OAuth eligibility check for user: {}", username);
// Check license first - if paying, they're eligible (no need to check grandfathering)
boolean hasPaid = hasPaidLicense();
if (hasPaid) {
log.debug("User {} eligible for OAuth via paid license", username);
return true;
}
// No license - check if grandfathered (fallback for V1 users)
if (user != null && user.isOauthGrandfathered()) { if (user != null && user.isOauthGrandfathered()) {
log.info("User {} eligible for OAuth via grandfathering (no paid license)", username); log.debug("User {} is grandfathered for OAuth", user.getUsername());
return true; return true;
} }
// Not grandfathered and no license // Users can use OAuth with SERVER or ENTERPRISE license
log.info("User {} NOT eligible for OAuth: no paid license and not grandfathered", username); boolean hasPaid = hasPaidLicense();
return false; log.debug("OAuth eligibility check: hasPaidLicense={}", hasPaid);
return hasPaid;
} }
/** /**
@@ -386,30 +369,17 @@ public class UserLicenseSettingsService {
* @param user The user to check * @param user The user to check
* @return true if the user can use SAML * @return true if the user can use SAML
*/ */
public boolean isSamlEligible(User user) { public boolean isSamlEligible(stirling.software.proprietary.security.model.User user) {
String username = (user != null) ? user.getUsername() : "<new user>"; // Grandfathered users always have SAML access
log.info("SAML2 eligibility check for user: {}", username);
// Check license first - if paying, they're eligible (no need to check grandfathering)
boolean hasEnterprise = hasEnterpriseLicense();
if (hasEnterprise) {
log.debug("User {} eligible for SAML2 via ENTERPRISE license", username);
return true;
}
// No license - check if grandfathered (fallback for V1 users)
if (user != null && user.isOauthGrandfathered()) { if (user != null && user.isOauthGrandfathered()) {
log.info( log.debug("User {} is grandfathered for SAML", user.getUsername());
"User {} eligible for SAML2 via grandfathering (no ENTERPRISE license)",
username);
return true; return true;
} }
// Not grandfathered and no license // Users can use SAML only with ENTERPRISE license
log.info( boolean hasEnterprise = hasEnterpriseLicense();
"User {} NOT eligible for SAML2: no ENTERPRISE license and not grandfathered", log.debug("SAML eligibility check: hasEnterpriseLicense={}", hasEnterprise);
username); return hasEnterprise;
return false;
} }
/** /**
@@ -551,17 +521,12 @@ public class UserLicenseSettingsService {
if (checker == null) { if (checker == null) {
return false; return false;
} }
License license = checker.getPremiumLicenseEnabledResult(); License license = checker.getPremiumLicenseEnabledResult();
boolean hasPaid = (license == License.SERVER || license == License.ENTERPRISE); return license == License.SERVER || license == License.ENTERPRISE;
log.info("License check result: type={}, requiresPaid=true, hasPaid={}", license, hasPaid);
return hasPaid;
} }
/** /**
* Checks if the system has an ENTERPRISE license. Used for enterprise-only features like SSO * Checks if the system has an ENTERPRISE license. Used for enterprise-only features like SAML.
* (OAuth/SAML).
* *
* @return true if ENTERPRISE license is active * @return true if ENTERPRISE license is active
*/ */
@@ -570,19 +535,7 @@ public class UserLicenseSettingsService {
if (checker == null) { if (checker == null) {
return false; return false;
} }
License license = checker.getPremiumLicenseEnabledResult(); License license = checker.getPremiumLicenseEnabledResult();
log.info(
"License check result: type={}, requiresEnterprise=true, hasEnterprise={}",
license,
(license == License.ENTERPRISE));
if (license != License.ENTERPRISE) {
log.warn(
"SAML2 requires ENTERPRISE license but found: {}. SAML2 login will be blocked.",
license);
}
return license == License.ENTERPRISE; return license == License.ENTERPRISE;
} }
} }
@@ -1,162 +0,0 @@
package stirling.software.proprietary.security.oauth2;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
/**
* Unit tests for OAuth2Configuration redirect URI logic.
*
* <p>These tests validate the critical fix for GitHub issue #5141: The redirect URI path segment
* MUST match the registration ID. Previously, the redirect URI was hardcoded to 'oidc', causing
* InvalidClientRegistrationIdException when custom provider names were used.
*
* <p>Note: These are conceptual tests documenting the expected behavior. Full integration testing
* with actual OIDC discovery would require: 1. Mock HTTP server for OIDC discovery endpoints 2.
* Valid OIDC configuration responses 3. Network mocking infrastructure
*/
class OAuth2ConfigurationTest {
/**
* Tests the redirect URI pattern for OIDC provider configurations.
*
* <p>Critical behavior (GitHub issue #5141 fix): The redirect URI path segment MUST match the
* registration ID. For example: - Provider name: "authentik" → Redirect URI:
* "/login/oauth2/code/authentik" - Provider name: "mycompany" → Redirect URI:
* "/login/oauth2/code/mycompany" - Provider name: "oidc" → Redirect URI:
* "/login/oauth2/code/oidc"
*
* <p>Previously, the redirect URI was hardcoded to 'oidc', causing Spring Security to look for
* a registration with ID 'oidc' when the provider redirected back. This caused
* InvalidClientRegistrationIdException when custom provider names were used.
*/
@Test
void testRedirectUriPattern_usesProviderNameNotHardcodedOidc() {
// Verify the redirect URI pattern constant
String redirectUriBase = "{baseUrl}/login/oauth2/code/";
// Test cases: provider name → expected redirect URI
String[][] testCases = {
{"authentik", redirectUriBase + "authentik"},
{"mycompany", redirectUriBase + "mycompany"},
{"oidc", redirectUriBase + "oidc"},
{"okta", redirectUriBase + "okta"},
{"auth0", redirectUriBase + "auth0"}
};
for (String[] testCase : testCases) {
String providerName = testCase[0];
String expectedRedirectUri = testCase[1];
// The fix ensures: .redirectUri(REDIRECT_URI_PATH + name)
// instead of: .redirectUri(REDIRECT_URI_PATH + "oidc")
String actualRedirectUri = redirectUriBase + providerName;
assertEquals(
expectedRedirectUri,
actualRedirectUri,
String.format(
"Redirect URI for provider '%s' must use provider name, not hardcoded 'oidc'",
providerName));
}
}
/**
* Documents the critical fix for OAuth2 redirect URI mismatch.
*
* <p>This test validates the logic that was changed in OAuth2Configuration.java line 220:
*
* <pre>
* // BEFORE (bug):
* .redirectUri(REDIRECT_URI_PATH + "oidc") // Always "oidc"
*
* // AFTER (fix):
* .redirectUri(REDIRECT_URI_PATH + name) // Dynamic provider name
* </pre>
*/
@Test
void testCriticalFix_redirectUriMatchesRegistrationId() {
// The redirect URI path segment extraction by Spring Security
String callbackUrl = "http://localhost:8080/login/oauth2/code/authentik?code=abc123";
// Spring extracts the path segment between "code/" and "?"
String extractedRegistrationId = extractRegistrationIdFromCallback(callbackUrl);
// The extracted ID MUST match an actual registration ID
assertEquals("authentik", extractedRegistrationId);
// If we had used hardcoded "oidc", the callback would be:
String buggyCallbackUrl = "http://localhost:8080/login/oauth2/code/oidc?code=abc123";
String buggyExtractedId = extractRegistrationIdFromCallback(buggyCallbackUrl);
// This would look for registration with ID "oidc" but we registered "authentik"
assertEquals("oidc", buggyExtractedId);
// The mismatch: registrationId="authentik", but Spring looks for "oidc"
// Result: InvalidClientRegistrationIdException
assertNotNull(buggyExtractedId, "This demonstrates the bug that was fixed");
}
/** Helper method simulating Spring's extraction of registration ID from callback URL */
private String extractRegistrationIdFromCallback(String callbackUrl) {
// Simplified version of what Spring Security does
// Actual: OAuth2AuthorizationRequestRedirectFilter extracts from path
String path = callbackUrl.split("\\?")[0];
String[] parts = path.split("/");
return parts[parts.length - 1]; // Last path segment
}
/**
* Validates the frontend-backend flow for custom provider names.
*
* <p>Complete flow: 1. Backend: Provider configured as "authentik" in settings.yml 2. Backend:
* ClientRegistration created with registrationId="authentik" 3. Backend: Redirect URI set to
* "{baseUrl}/login/oauth2/code/authentik" 4. Backend: Login endpoint returns providerList with
* "/oauth2/authorization/authentik" 5. Frontend: Extracts "authentik" from path and uses it for
* OAuth login 6. Frontend: Redirects to "/oauth2/authorization/authentik" 7. Backend: Spring
* Security redirects to provider with redirect_uri containing "authentik" 8. Provider:
* Redirects back to "/login/oauth2/code/authentik?code=..." 9. Backend: Spring Security
* extracts "authentik" from callback URL 10. Backend: Looks up ClientRegistration with ID
* "authentik" ✅ SUCCESS
*
* <p>If redirect URI was hardcoded to "oidc" (the bug): Step 7: Provider redirects to
* "/login/oauth2/code/oidc?code=..." Step 9: Spring Security looks for registration ID "oidc"
* Step 10: FAIL - No registration found with ID "oidc" (we registered "authentik") Result:
* InvalidClientRegistrationIdException
*/
@Test
void testEndToEndFlow_registrationIdConsistency() {
String providerName = "authentik";
// Step 2: Registration ID
String registrationId = providerName;
assertEquals("authentik", registrationId);
// Step 3: Redirect URI (MUST use same name)
String redirectUri = "{baseUrl}/login/oauth2/code/" + providerName;
assertEquals("{baseUrl}/login/oauth2/code/authentik", redirectUri);
// Step 4: Provider list endpoint
String authorizationPath = "/oauth2/authorization/" + providerName;
assertEquals("/oauth2/authorization/authentik", authorizationPath);
// Step 5: Frontend extracts provider ID
String frontendProviderId =
authorizationPath.substring(authorizationPath.lastIndexOf('/') + 1);
assertEquals("authentik", frontendProviderId);
// Step 6-8: OAuth flow (external)
// Step 9: Callback URL from provider
String callbackUrl =
"http://localhost:8080/login/oauth2/code/" + providerName + "?code=abc123";
String extractedId = extractRegistrationIdFromCallback(callbackUrl);
// Step 10: Registration lookup
assertEquals(
registrationId,
extractedId,
"Registration ID from callback MUST match original registration ID");
}
}
@@ -27,11 +27,6 @@ class MailConfigTest {
when(mailProps.getPort()).thenReturn(587); when(mailProps.getPort()).thenReturn(587);
when(mailProps.getUsername()).thenReturn("user@example.com"); when(mailProps.getUsername()).thenReturn("user@example.com");
when(mailProps.getPassword()).thenReturn("password"); when(mailProps.getPassword()).thenReturn("password");
when(mailProps.getStartTlsEnable()).thenReturn(null);
when(mailProps.getStartTlsRequired()).thenReturn(null);
when(mailProps.getSslEnable()).thenReturn(null);
when(mailProps.getSslTrust()).thenReturn(null);
when(mailProps.getSslCheckServerIdentity()).thenReturn(null);
} }
@Test @Test
@@ -55,32 +50,6 @@ class MailConfigTest {
() -> assertEquals("password", impl.getPassword()), () -> assertEquals("password", impl.getPassword()),
() -> assertEquals("UTF-8", impl.getDefaultEncoding()), () -> assertEquals("UTF-8", impl.getDefaultEncoding()),
() -> assertEquals("true", props.getProperty("mail.smtp.auth")), () -> assertEquals("true", props.getProperty("mail.smtp.auth")),
() -> assertEquals("true", props.getProperty("mail.smtp.starttls.enable")), () -> assertEquals("true", props.getProperty("mail.smtp.starttls.enable")));
() -> assertEquals(null, props.getProperty("mail.smtp.starttls.required")),
() -> assertEquals(null, props.getProperty("mail.smtp.ssl.enable")),
() -> assertEquals("*", props.getProperty("mail.smtp.ssl.trust")));
}
@Test
void shouldRespectExplicitTlsOverrides() {
ApplicationProperties appProps = mock(ApplicationProperties.class);
when(mailProps.getStartTlsEnable()).thenReturn(false);
when(mailProps.getStartTlsRequired()).thenReturn(true);
when(mailProps.getSslEnable()).thenReturn(true);
when(mailProps.getSslTrust()).thenReturn("*");
when(mailProps.getSslCheckServerIdentity()).thenReturn(true);
when(appProps.getMail()).thenReturn(mailProps);
MailConfig config = new MailConfig(appProps);
JavaMailSenderImpl impl = (JavaMailSenderImpl) config.javaMailSender();
Properties props = impl.getJavaMailProperties();
assertAll(
() -> assertEquals("false", props.getProperty("mail.smtp.starttls.enable")),
() -> assertEquals("true", props.getProperty("mail.smtp.starttls.required")),
() -> assertEquals("true", props.getProperty("mail.smtp.ssl.enable")),
() -> assertEquals("*", props.getProperty("mail.smtp.ssl.trust")),
() -> assertEquals("true", props.getProperty("mail.smtp.ssl.checkserveridentity")));
} }
} }
@@ -33,7 +33,6 @@ class UserLicenseSettingsServiceTest {
@Mock private UserService userService; @Mock private UserService userService;
@Mock private ApplicationProperties applicationProperties; @Mock private ApplicationProperties applicationProperties;
@Mock private ApplicationProperties.Premium premium; @Mock private ApplicationProperties.Premium premium;
@Mock private ApplicationProperties.AutomaticallyGenerated automaticallyGenerated;
@Mock private LicenseKeyChecker licenseKeyChecker; @Mock private LicenseKeyChecker licenseKeyChecker;
@Mock private ObjectProvider<LicenseKeyChecker> licenseKeyCheckerProvider; @Mock private ObjectProvider<LicenseKeyChecker> licenseKeyCheckerProvider;
@@ -50,8 +49,6 @@ class UserLicenseSettingsServiceTest {
mockSettings.setGrandfatheredUserSignature("80:test-signature"); mockSettings.setGrandfatheredUserSignature("80:test-signature");
when(applicationProperties.getPremium()).thenReturn(premium); when(applicationProperties.getPremium()).thenReturn(premium);
when(applicationProperties.getAutomaticallyGenerated()).thenReturn(automaticallyGenerated);
when(automaticallyGenerated.getIsNewServer()).thenReturn(false); // Default: not a new server
when(settingsRepository.findSettings()).thenReturn(Optional.of(mockSettings)); when(settingsRepository.findSettings()).thenReturn(Optional.of(mockSettings));
when(userService.getTotalUsersCount()).thenReturn(80L); when(userService.getTotalUsersCount()).thenReturn(80L);
when(settingsRepository.save(any(UserLicenseSettings.class))) when(settingsRepository.save(any(UserLicenseSettings.class)))
@@ -270,222 +267,4 @@ class UserLicenseSettingsServiceTest {
verify(userService, times(1)).grandfatherAllOAuthUsers(); verify(userService, times(1)).grandfatherAllOAuthUsers();
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession(); verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
} }
// ===== OAuth Eligibility Tests =====
@Test
void isOAuthEligible_grandfatheredUser_returnsTrue() {
// Grandfathered user should be eligible regardless of license
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("grandfathered-user");
user.setOauthGrandfathered(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
boolean result = service.isOAuthEligible(user);
assertEquals(true, result, "Grandfathered user should be eligible for OAuth");
}
@Test
void isOAuthEligible_nonGrandfatheredUserWithServerLicense_returnsTrue() {
// Non-grandfathered user with SERVER license should be eligible
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);
boolean result = service.isOAuthEligible(user);
assertEquals(true, result, "Non-grandfathered user with SERVER license should be eligible");
}
@Test
void isOAuthEligible_nonGrandfatheredUserWithEnterpriseLicense_returnsTrue() {
// Non-grandfathered user with ENTERPRISE license should be eligible
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
boolean result = service.isOAuthEligible(user);
assertEquals(
true, result, "Non-grandfathered user with ENTERPRISE license should be eligible");
}
@Test
void isOAuthEligible_nonGrandfatheredUserWithNoLicense_returnsFalse() {
// Non-grandfathered user without license should NOT be eligible
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
boolean result = service.isOAuthEligible(user);
assertEquals(
false,
result,
"Non-grandfathered user without paid license should NOT be eligible");
}
@Test
void isOAuthEligible_newUserWithServerLicense_returnsTrue() {
// New user (null) with SERVER license should be eligible for auto-creation
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);
boolean result = service.isOAuthEligible(null);
assertEquals(
true, result, "New user with SERVER license should be eligible for auto-creation");
}
@Test
void isOAuthEligible_newUserWithNoLicense_returnsFalse() {
// New user (null) without license should NOT be eligible
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
boolean result = service.isOAuthEligible(null);
assertEquals(
false,
result,
"New user without paid license should NOT be eligible for auto-creation");
}
@Test
void isOAuthEligible_licenseCheckerUnavailable_returnsFalse() {
// If LicenseKeyChecker is unavailable, OAuth should be blocked
when(licenseKeyCheckerProvider.getIfAvailable()).thenReturn(null);
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
boolean result = service.isOAuthEligible(user);
assertEquals(
false, result, "OAuth should be blocked when LicenseKeyChecker is unavailable");
}
// ===== SAML Eligibility Tests =====
@Test
void isSamlEligible_grandfatheredUser_returnsTrue() {
// Grandfathered user should be eligible for SAML regardless of license
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("grandfathered-user");
user.setOauthGrandfathered(true);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
boolean result = service.isSamlEligible(user);
assertEquals(true, result, "Grandfathered user should be eligible for SAML");
}
@Test
void isSamlEligible_nonGrandfatheredUserWithEnterpriseLicense_returnsTrue() {
// Non-grandfathered user with ENTERPRISE license should be eligible
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
boolean result = service.isSamlEligible(user);
assertEquals(
true,
result,
"Non-grandfathered user with ENTERPRISE license should be eligible for SAML");
}
@Test
void isSamlEligible_nonGrandfatheredUserWithServerLicense_returnsFalse() {
// Non-grandfathered user with SERVER license should NOT be eligible for SAML
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);
boolean result = service.isSamlEligible(user);
assertEquals(
false,
result,
"Non-grandfathered user with SERVER license should NOT be eligible for SAML");
}
@Test
void isSamlEligible_nonGrandfatheredUserWithNoLicense_returnsFalse() {
// Non-grandfathered user without license should NOT be eligible
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.NORMAL);
boolean result = service.isSamlEligible(user);
assertEquals(
false,
result,
"Non-grandfathered user without ENTERPRISE license should NOT be eligible for SAML");
}
@Test
void isSamlEligible_newUserWithEnterpriseLicense_returnsTrue() {
// New user (null) with ENTERPRISE license should be eligible for auto-creation
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
boolean result = service.isSamlEligible(null);
assertEquals(
true,
result,
"New user with ENTERPRISE license should be eligible for SAML auto-creation");
}
@Test
void isSamlEligible_newUserWithServerLicense_returnsFalse() {
// New user (null) with SERVER license should NOT be eligible for SAML
when(licenseKeyChecker.getPremiumLicenseEnabledResult()).thenReturn(License.SERVER);
boolean result = service.isSamlEligible(null);
assertEquals(
false,
result,
"New user with SERVER license should NOT be eligible for SAML (requires ENTERPRISE)");
}
@Test
void isSamlEligible_licenseCheckerUnavailable_returnsFalse() {
// If LicenseKeyChecker is unavailable, SAML should be blocked
when(licenseKeyCheckerProvider.getIfAvailable()).thenReturn(null);
stirling.software.proprietary.security.model.User user =
new stirling.software.proprietary.security.model.User();
user.setUsername("test-user");
user.setOauthGrandfathered(false);
boolean result = service.isSamlEligible(user);
assertEquals(false, result, "SAML should be blocked when LicenseKeyChecker is unavailable");
}
} }
+2 -49
View File
@@ -12,8 +12,6 @@ plugins {
} }
import com.github.jk1.license.render.* import com.github.jk1.license.render.*
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
ext { ext {
springBootVersion = "3.5.6" springBootVersion = "3.5.6"
@@ -59,7 +57,7 @@ repositories {
allprojects { allprojects {
group = 'stirling.software' group = 'stirling.software'
version = '2.1.4' version = '2.0.3'
configurations.configureEach { configurations.configureEach {
exclude group: 'commons-logging', module: 'commons-logging' exclude group: 'commons-logging', module: 'commons-logging'
@@ -67,51 +65,6 @@ allprojects {
} }
} }
def writeIfChanged(File targetFile, String newContent) {
if (targetFile.getText('UTF-8') != newContent) {
targetFile.write(newContent, 'UTF-8')
}
}
def updateTauriConfigVersion(String version) {
File tauriConfig = file('frontend/src-tauri/tauri.conf.json')
def parsed = new JsonSlurper().parse(tauriConfig)
parsed.version = version
def formatted = JsonOutput.prettyPrint(JsonOutput.toJson(parsed)) + System.lineSeparator()
writeIfChanged(tauriConfig, formatted)
}
def updateSimulationVersion(File fileToUpdate, String version) {
def content = fileToUpdate.getText('UTF-8')
def matcher = content =~ /(appVersion:\s*')([^']*)(')/
if (!matcher.find()) {
throw new GradleException("Could not locate appVersion in ${fileToUpdate} for synchronization")
}
def updatedContent = matcher.replaceFirst("${matcher.group(1)}${version}${matcher.group(3)}")
writeIfChanged(fileToUpdate, updatedContent)
}
tasks.register('syncAppVersion') {
group = 'versioning'
description = 'Synchronizes app version across desktop and simulation configs.'
doLast {
def appVersion = project.version.toString()
println "Synchronizing application version to ${appVersion}"
updateTauriConfigVersion(appVersion)
[
'frontend/src/core/testing/serverExperienceSimulations.ts',
'frontend/src/proprietary/testing/serverExperienceSimulations.ts'
].each { path ->
updateSimulationVersion(file(path), appVersion)
}
}
}
tasks.register('writeVersion', WriteProperties) { tasks.register('writeVersion', WriteProperties) {
destinationFile = layout.projectDirectory.file('app/common/src/main/resources/version.properties') destinationFile = layout.projectDirectory.file('app/common/src/main/resources/version.properties')
println "Writing version.properties to ${destinationFile.get().asFile.path}" println "Writing version.properties to ${destinationFile.get().asFile.path}"
@@ -361,7 +314,7 @@ tasks.named('bootRun') {
tasks.named('build') { tasks.named('build') {
group = 'build' group = 'build'
description = 'Delegates to :stirling-pdf:bootJar' description = 'Delegates to :stirling-pdf:bootJar'
dependsOn ':stirling-pdf:bootJar', 'buildRestartHelper', 'syncAppVersion' dependsOn ':stirling-pdf:bootJar', 'buildRestartHelper'
doFirst { doFirst {
println "Delegating to :stirling-pdf:bootJar" println "Delegating to :stirling-pdf:bootJar"

Some files were not shown because too many files have changed in this diff Show More