Compare commits

...
27 Commits
Author SHA1 Message Date
Dario Ghunney WareandGitHub eaafa21842 Merge branch 'main' into fix/saml-login 2026-01-30 16:16:32 +00:00
James BruntonandGitHub 1cc562a6b1 Stop type checking TypeScript files that won't be run (#5607)
# Description of Changes
This PR fixes false-positive TypeScript errors in our layered build
setup (core → proprietary → desktop) by ensuring each build’s typecheck
only evaluates files that are actually part of that build’s reachable
module graph. This prevents overridden core implementations from being
typechecked in higher-layer builds where they are effectively
unreachable due to alias-based overrides.

## Background

We maintain multiple build targets from a layered source tree:

- core: open source baseline
- proprietary: core + proprietary additions/overrides
- desktop: proprietary + desktop-specific additions/overrides

We implement overrides via paths/aliases such that placing a file in a
higher layer at the same relative path supersedes the lower-layer file
at runtime.

For safety, we run TypeScript typechecking independently per build
target to ensure all builds remain valid.

## Problem

Our existing tsconfig setup often typechecked files that are not
actually reachable in a given build. Specifically:

- When a file in core is overridden by a file in proprietary or desktop,
the overridden core file can still be included in the TypeScript Program
for the higher-layer build (typically due to broad include globs).
- This produces false-positive type errors in higher-layer typecheck
runs, even though those core files are effectively unreachable in the
build.

This created friction and noise, and meant we had to make unnecessary
changes to `core` to make the other builds happy, reducing type safety
in the process.

## Solution

This PR adjusts the tsconfig strategy so each build target's typecheck
is driven by reachable entrypoints rather than blanket inclusion of all
layer source trees. Concretely:

- Each build’s tsconfig now includes only:
- that build’s entrypoints and layer sources that are intended to be
compiled for the target
  - any shared/top-level sources required by the target
- Lower layers (e.g., core) are not globally included in higher-layer
builds; they are instead pulled in through module resolution only when
actually referenced (with paths ordering ensuring the correct override
wins).
- This means that we still check all the files that will actually be run
with whatever the overridden logic is, but avoid wasting time and
introducing false-positives by not checking files which have been
overridden.

## Notes
Unfortunately, the config we use for the type checking can't be the same
as the one we use for Vite in this strategy. Vite needs to know about
the entire source tree, so it can't only include the subfolders because
it causes build errors. Because of this, I've duplicated the existing
(valid) tsconfig files and use them for Vite. This is a little clunky
but it does the job. Some day hopefully I'll come back to it and be able
to figure out a nicer way to do it, but for now at least, this solves
the type checking issues without impacting the runtime builds.

Also, I noticed that `@desktop` is defined as an alias, which was
presumably missed when I was removing the self-aliases from the files. I
don't see why you'd ever need to have a desktop file reference
`@desktop` to say "import this but make it impossible for something else
to override the import". I've removed the `@desktop` alias in this PR
while I was in there.
2026-01-30 15:27:35 +00:00
stirlingbot[bot]GitHubstirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>Anthony Stirling
d90e51233d 🤖 format everything with pre-commit by stirlingbot (#5538)
Auto-generated by [create-pull-request][1] with **stirlingbot**

[1]: https://github.com/peter-evans/create-pull-request

---------

Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
2026-01-29 23:07:59 +00:00
1cd3e2846e feat(stamp): add dynamic variables and templates for stamp text customization (#5546)
# Description of Changes

This pull request improves the PDF stamping feature, particularly the
text stamping functionality, by introducing dynamic variables, improving
formatting flexibility, and refining positioning logic. The changes
include backend support for dynamic stamp variables (such as date, time,
filename, and metadata), improvements to text layout and positioning,
updates to the API and frontend for usability, and localization
enhancements for user guidance.

**Dynamic Stamp Variables and Text Processing:**

* Added support for dynamic variables in stamp text (e.g., `@date`,
`@time`, `@page_number`, `@filename`, `@uuid`, and metadata fields),
including custom date formats and escaping for literal `@` symbols. This
is handled by the new `processStampText` method in
`StampController.java`.
* Implemented validation and formatting for custom date variables,
ensuring only safe formats are accepted and providing user-friendly
error messages for invalid formats.

**Text Layout and Positioning Improvements:**

* Refactored text and image stamp positioning: now calculates line
heights, block heights, and widths for multi-line stamps, and adjusts
placement logic for more accurate alignment (top, center, bottom) and
margins.
* Updated the default font size for stamps to 40pt and improved font
size handling in both backend and frontend, including validation for
positive values

**API and Method Signature Updates:**

* Extended method signatures to include additional context (such as page
index and filename) for more powerful variable substitution in stamps
**Frontend and Localization Enhancements:**

* Added comprehensive help text, variable descriptions, and template
examples to the UI, making it easier for users to understand and use
dynamic stamp variables.
* Improved accessibility and clarity in the stamp formatting UI by
disabling controls appropriately and providing clearer descriptions.



<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Co-authored-by: ConnorYoh <40631091+ConnorYoh@users.noreply.github.com>
Co-authored-by: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
2026-01-29 21:16:14 +00:00
BitTobyandGitHub 080faf9353 fix: PDF Text Editor file open (#5572)
# Description of Changes

## Content
This pull requests fix the problem when opening the file in the ALPHA
feature PDF Text Editor.

## Page Where the Problem Occurred
http://localhost/pdf-text-editor

## Problem
convert_cff_to_ttf.py does not support named CLI arguments.

But Java is calling it like this:
convert_cff_to_ttf.py --input file.cff --output file.otf --to-unicode
file.tounicode

## Solved
convert_cff_to_ttf.py support named CLI arguments.

Closes #5518
---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [x] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [x] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [x] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-29 16:52:21 +00:00
Dario Ghunney WareandGitHub d486bb4939 Fix Audit & Usage Analytics Sections (#5586)
Fixed issue where @lob annotation on audit column was casing
`org.postgresql.util.PSQLException: Large Objects may not be used in
auto-commit mode.` data retrieval issues with Postgres
2026-01-29 16:51:52 +00:00
Anthony StirlingandGitHub 41f9929fd2 Fix tool disabling (#5585)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-29 14:36:10 +00:00
Dario Ghunney Ware 1a62680dcc cleanup 2026-01-26 11:07:39 +00:00
DarioGii 789642a824 pr comments 2026-01-26 11:07:39 +00:00
DarioGii e1199a1fd3 updated deprecated version 2026-01-26 11:07:39 +00:00
DarioGii c0f9c9570e added missing check 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware a8c4a0bfb1 Testing saml login/logout
# Conflicts:
#	app/proprietary/src/main/java/stirling/software/proprietary/security/CustomLogoutSuccessHandler.java

# Conflicts:
#	frontend/src/proprietary/routes/AuthCallback.tsx

# Conflicts:
#	app/core/src/main/java/stirling/software/SPDF/controller/api/SettingsController.java
#	app/proprietary/src/main/java/stirling/software/proprietary/security/config/AccountWebController.java
2026-01-26 11:07:38 +00:00
LudyandDario Ghunney Ware 99d728d815 refactor(security): clean up SSO handling, harden URL parsing, and bump dependencies (#5523)
# Description of Changes

This PR performs a broad cleanup and refactor across the security, SSO,
and dependency layers to improve correctness, maintainability, and
robustness.

### What was changed

- **SSO / Authentication cleanup**
- Removed deprecated and ambiguous `SSO` authentication handling in
favor of explicit `OAUTH2` and `SAML2`.
- Introduced a centralized helper (`isSsoAuthenticationTypeByUsername`)
to consistently detect SSO-backed users.
- Hardened user creation logic to strictly validate authentication types
and reject invalid values.
- Updated OAuth2 and SAML2 authentication success handlers to use
unified SSO detection logic and clearer control flow.
  - Adjusted tests to reflect the new canonical authentication types.

- **Security & robustness improvements**
- Replaced direct `new URL(...)` usage with `URI.create(...).toURL()` to
avoid malformed URL edge cases.
- Hardened `Referer` parsing logic to safely handle invalid or host-less
URIs.
- Improved string comparison patterns (`"literal".equals(x)`) to avoid
potential `NullPointerException`s.

- **Controller and API cleanup**
- Removed large blocks of unused and legacy admin settings endpoints
from `SettingsController`.
- Updated OpenAPI annotations to use `requiredMode` instead of
deprecated `required`.

- **Dependency and build maintenance**
  - Updated Spring Boot from `3.5.7` to `3.5.9`.
- Updated multiple dependencies (Spring Security, Jackson, Micrometer,
Jetty, Hibernate, SnakeYAML, Springdoc, Swagger UI, etc.).
- Synced dependency versions in `3rdPartyLicenses.json` and removed
duplicate or obsolete entries.
- Modernized Gradle DSL usage (`url =`, `username =`,
`allowInsecureProtocol = true`).
- Ensured Spotless disabling applies consistently across all
subprojects.
  - Added `.build-cache` to `.gitignore`.

### Why the change was made

- To eliminate legacy and ambiguous SSO handling that could lead to
incorrect authentication decisions.
- To improve security and stability when dealing with user-controlled
URLs and headers.
- To reduce technical debt by removing unused controllers and deprecated
patterns.
- To keep dependencies up to date and aligned with the current Spring
Boot release.
- To improve overall code clarity, consistency, and long-term
maintainability.

---

This pull request contains dependency updates, minor code cleanups, and
some refactoring to improve maintainability and correctness. The most
significant change is the removal of all admin settings endpoints
(GET/POST) from the `SettingsController`, which impacts how application
settings can be managed via the API. Additionally, there are dependency
version bumps, minor improvements to static resource checks, and small
refactors in certificate download logic and Telegram bot service.

**Major API changes:**

* Removed all admin settings endpoints (general, security, connections,
privacy, advanced) from `SettingsController`, including both GET and
POST handlers for updating and retrieving settings. This eliminates the
ability to manage these settings via the API.

**Dependency updates:**

* Upgraded `snakeyaml-engine` from 2.10 to 3.0.1 and
`springdoc-openapi-starter-webmvc-ui` from 2.8.14 to 2.8.15 in
`build.gradle`.

**Refactoring and bug fixes:**

* Refactored static resource check in `RequestUriUtils.isStaticResource`
to use constant-first string comparison for better null safety and
clarity.
* Updated certificate download logic in `CertificateValidationService`
to use `URI.create(urlStr).toURL()` instead of `new URL(urlStr)` for
improved URL parsing and error handling.
[[1]](diffhunk://#diff-d2646f37bfd3e0963cbce16ab13edb52f2092795f54203b999dd82651154f26dL513-R514)
[[2]](diffhunk://#diff-d2646f37bfd3e0963cbce16ab13edb52f2092795f54203b999dd82651154f26dL703-R704)
* Refactored `TelegramPipelineBot` to consistently use
`telegramProperties.getBotToken()` instead of `getBotToken()`, and
removed the `getBotToken()` method override.
[[1]](diffhunk://#diff-a2466b92f58750ea37960cd1533e3194d9ecc3b4ef5ad7b64a017ee0e636ad93L85-R85)
[[2]](diffhunk://#diff-a2466b92f58750ea37960cd1533e3194d9ecc3b4ef5ad7b64a017ee0e636ad93L395-R395)
[[3]](diffhunk://#diff-a2466b92f58750ea37960cd1533e3194d9ecc3b4ef5ad7b64a017ee0e636ad93L519-L523)

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-26 11:07:38 +00:00
LudyandDario Ghunney Ware 3317babe5c Add sync-versions job to GitHub Actions workflow (#5228)
# Description of Changes

This pull request updates the `.github/workflows/build.yml` file to
improve automation and consistency in the build process. The most
significant change is the addition of a new `sync-versions` job that
automatically checks for and synchronizes version differences across key
files, and posts a comment on the pull request if mismatches are
detected. Additionally, there are minor formatting updates for
consistency.

**Automation and version synchronization:**

* Added a new `sync-versions` job that runs after the build, checks for
version mismatches between `build.gradle` and several frontend files,
and posts or updates a comment on the pull request to notify
contributors if differences are found. This job uses a GitHub App bot
for authentication and ensures that versioning remains consistent across
the project.

**Formatting consistency:**

* Updated the YAML formatting for `node-version`, `cache`, and
`python-version` fields to use double quotes for consistency in the
`build.yml` workflow.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721L150-R151)
[[2]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721L244-R338)


<img width="1127" height="401" alt="image"
src="https://github.com/user-attachments/assets/6930a72d-f72b-4909-97e2-51f0e0f61613"
/>


---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-26 11:07:38 +00:00
LudyandDario Ghunney Ware 5ad5d851b1 chore(ci): enable Gradle dependency caching across GitHub workflows (#5400)
# Description of Changes

This pull request updates the CI/CD workflows and Gradle configuration
to improve build reproducibility, security, and external dependency
management. The main changes include standardizing Gradle setup across
workflows, securely injecting Maven credentials, and enabling Gradle
build caching. There are also minor improvements to dependency version
management and plugin repository configuration.

**CI/CD Workflow Improvements:**

- Standardized Gradle setup across all GitHub Actions workflows by
explicitly adding a `Setup Gradle` step using
`gradle/actions/setup-gradle@v5.0.0` and specifying Gradle version 8.14.
This replaces previous usages and ensures consistency.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R71-R81)
[[2]](diffhunk://#diff-8d23782ae5caff72d55828bb25814854f5f2523f299d7dbcda4a3537dd84c5c3L157-R176)
[[3]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R134-R144)
[[4]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R206-R216)
[[5]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R260-R264)
[[6]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R331-R341)
[[7]](diffhunk://#diff-3c0f521958c53ad27c967692b4d5480ead136acb33622ee97d39df814b1b202eR339-R351)
[[8]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL53-R54)
[[9]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL121-R127)
[[10]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR206-R217)
[[11]](diffhunk://#diff-6a2e9fb077e57351f4a7e10d03b114e256298babdf06e7e7ae666781a5cf36a1R60-R70)
[[12]](diffhunk://#diff-62dcbe64a950b4efb54d691e1e87451a8cd535400aa9ea1e40893de5b57cd73bL45-R46)
[[13]](diffhunk://#diff-76056236de05155107f6a660f1e3956059e37338011b8f0e72188afcb9b17b6fL46-R56)
[[14]](diffhunk://#diff-fd60dc2adec58c1005c4e4164e9c24362fd6082fd3ab0403e54d276d9835fa6eL42-R65)
[[15]](diffhunk://#diff-b34ab107dd4bc92075b2e89b6f16e4a2813e267ca7c2afebdb1931a0a3900d5aR102-R114)
[[16]](diffhunk://#diff-98b618771a57e1758961359ecacbac2cff7cfef29aa021c3bc294ae926c4ce5bL47-R51)

- Enabled Gradle build cache (`--build-cache`) for all build-related
commands in workflows, improving build performance and consistency. Also
removed unnecessary `clean` commands before builds to further optimize
workflow times.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R71-R81)
[[2]](diffhunk://#diff-8d23782ae5caff72d55828bb25814854f5f2523f299d7dbcda4a3537dd84c5c3L157-R176)
[[3]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R134-R144)
[[4]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R206-R216)
[[5]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R331-R341)
[[6]](diffhunk://#diff-3c0f521958c53ad27c967692b4d5480ead136acb33622ee97d39df814b1b202eR339-R351)
[[7]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL134-R144)
[[8]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR206-R217)
[[9]](diffhunk://#diff-6a2e9fb077e57351f4a7e10d03b114e256298babdf06e7e7ae666781a5cf36a1R60-R70)
[[10]](diffhunk://#diff-76056236de05155107f6a660f1e3956059e37338011b8f0e72188afcb9b17b6fL46-R56)
[[11]](diffhunk://#diff-fd60dc2adec58c1005c4e4164e9c24362fd6082fd3ab0403e54d276d9835fa6eL42-R65)
[[12]](diffhunk://#diff-b34ab107dd4bc92075b2e89b6f16e4a2813e267ca7c2afebdb1931a0a3900d5aR102-R114)
[[13]](diffhunk://#diff-98b618771a57e1758961359ecacbac2cff7cfef29aa021c3bc294ae926c4ce5bL47-R51)

**Security and Dependency Management:**

- Injected Maven credentials (`MAVEN_USER`, `MAVEN_PASSWORD`,
`MAVEN_PUBLIC_URL`) as environment variables in all relevant workflow
steps, supporting secure access to private or custom Maven repositories.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R71-R81)
[[2]](diffhunk://#diff-8d23782ae5caff72d55828bb25814854f5f2523f299d7dbcda4a3537dd84c5c3L157-R176)
[[3]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R134-R144)
[[4]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R206-R216)
[[5]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R290-R293)
[[6]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R331-R341)
[[7]](diffhunk://#diff-3c0f521958c53ad27c967692b4d5480ead136acb33622ee97d39df814b1b202eR339-R351)
[[8]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR66-R69)
[[9]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL134-R144)
[[10]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR281-R283)
[[11]](diffhunk://#diff-62dcbe64a950b4efb54d691e1e87451a8cd535400aa9ea1e40893de5b57cd73bR57-R60)
[[12]](diffhunk://#diff-76056236de05155107f6a660f1e3956059e37338011b8f0e72188afcb9b17b6fR73-R76)
[[13]](diffhunk://#diff-fd60dc2adec58c1005c4e4164e9c24362fd6082fd3ab0403e54d276d9835fa6eL42-R65)
[[14]](diffhunk://#diff-b34ab107dd4bc92075b2e89b6f16e4a2813e267ca7c2afebdb1931a0a3900d5aR178-R180)
[[15]](diffhunk://#diff-98b618771a57e1758961359ecacbac2cff7cfef29aa021c3bc294ae926c4ce5bL47-R51)

- Added a `pluginManagement` block in `settings.gradle` to allow Gradle
plugins to be resolved from a custom Maven repository if specified by
environment variables, increasing flexibility for plugin sourcing.

**Build and Dependency Versioning:**

- Updated `app/proprietary/build.gradle` to use the
`bouncycastleVersion` variable for the Bouncy Castle dependency version,
improving maintainability and consistency of dependency versioning.

**Workflow Trigger Improvements:**

- Expanded the file path triggers in
`.github/workflows/sync_files_v2.yml` to include additional Gradle build
files, ensuring the workflow runs when any core build files are changed.

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-26 11:07:38 +00:00
Anthony StirlingandDario Ghunney Ware 6cedc8c994 Libre threads (#5303)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-26 11:07:38 +00:00
Dario Ghunney Ware eba24b4d6c resolving conflicts 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware 68e95c2652 eslint fix 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware de23752b44 clean up 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware b44bb7c50c Improved SAML config settings 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware 537aee3ab6 Streamlined config with metadata uri 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware a6ae74e794 Addressing XML vulnerability 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware 50ec2d82d4 Hardening 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware f95e2fdaa3 Fixing tests 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware 70c9cb36c3 Implemented SP-initiated SLO enabled with flag
# Conflicts:
#	frontend/src/proprietary/routes/Login.tsx
2026-01-26 11:07:38 +00:00
Dario Ghunney Ware 1b737cbce5 Fixing SAML logout 2026-01-26 11:07:38 +00:00
Dario Ghunney Ware 4492fa39be Testing saml login/logout
# Conflicts:
#	app/proprietary/src/main/java/stirling/software/proprietary/security/CustomLogoutSuccessHandler.java

# Conflicts:
#	frontend/src/proprietary/routes/AuthCallback.tsx

# Conflicts:
#	app/core/src/main/java/stirling/software/SPDF/controller/api/SettingsController.java
#	app/proprietary/src/main/java/stirling/software/proprietary/security/config/AccountWebController.java
2026-01-26 11:07:38 +00:00
72 changed files with 2816 additions and 763 deletions
@@ -303,22 +303,23 @@ public class EndpointConfiguration {
// Adding endpoints to "PageOps" group
addEndpointToGroup("PageOps", "remove-pages");
addEndpointToGroup("PageOps", "merge-pdfs");
addEndpointToGroup("PageOps", "split-pdfs");
addEndpointToGroup("PageOps", "pdf-organizer");
addEndpointToGroup("PageOps", "split-pages");
addEndpointToGroup("PageOps", "rearrange-pages");
addEndpointToGroup("PageOps", "rotate-pdf");
addEndpointToGroup("PageOps", "multi-page-layout");
addEndpointToGroup("PageOps", "booklet-imposition");
addEndpointToGroup("PageOps", "scale-pages");
addEndpointToGroup("PageOps", "crop");
addEndpointToGroup("PageOps", "extract-page");
addEndpointToGroup("PageOps", "pdf-to-single-page");
addEndpointToGroup("PageOps", "auto-split-pdf");
addEndpointToGroup("PageOps", "split-by-size-or-count");
addEndpointToGroup("PageOps", "overlay-pdf");
addEndpointToGroup("PageOps", "split-pdf-by-sections");
addEndpointToGroup("PageOps", "split-pdf-by-chapters");
addEndpointToGroup("PageOps", "add-page-numbers");
addEndpointToGroup("PageOps", "extract-pages");
// Adding endpoints to "Convert" group
// Adding endpoints to "Convert" group (Frontend has 15 convert endpoints)
addEndpointToGroup("Convert", "pdf-to-img");
addEndpointToGroup("Convert", "img-to-pdf");
addEndpointToGroup("Convert", "pdf-to-pdfa");
@@ -334,6 +335,8 @@ public class EndpointConfiguration {
addEndpointToGroup("Convert", "pdf-to-csv");
addEndpointToGroup("Convert", "pdf-to-markdown");
addEndpointToGroup("Convert", "eml-to-pdf");
addEndpointToGroup("Convert", "pdf-to-epub");
// Backend-only endpoints (not in frontend tool registry)
addEndpointToGroup("Convert", "pdf-to-vector");
addEndpointToGroup("Convert", "vector-to-pdf");
addEndpointToGroup("Convert", "pdf-to-video");
@@ -341,6 +344,7 @@ public class EndpointConfiguration {
addEndpointToGroup("Convert", "pdf-to-cbz");
addEndpointToGroup("Convert", "pdf-to-json");
addEndpointToGroup("Convert", "json-to-pdf");
addEndpointToGroup("Convert", "pdf-to-rtf");
// Adding endpoints to "Security" group
addEndpointToGroup("Security", "add-password");
@@ -351,51 +355,49 @@ public class EndpointConfiguration {
addEndpointToGroup("Security", "remove-cert-sign");
addEndpointToGroup("Security", "sanitize-pdf");
addEndpointToGroup("Security", "auto-redact");
addEndpointToGroup("Security", "redact");
addEndpointToGroup("Security", "validate-signature");
addEndpointToGroup("Security", "add-stamp");
addEndpointToGroup("Security", "unlock-pdf-forms");
// Backend-only endpoints (not in frontend tool registry endpoints)
addEndpointToGroup("Security", "redact");
addEndpointToGroup("Security", "verify-pdf");
addEndpointToGroup("Security", "stamp");
addEndpointToGroup("Security", "sign");
// Adding endpoints to "Other" group
addEndpointToGroup("Other", "ocr-pdf");
addEndpointToGroup("Other", "add-image");
addEndpointToGroup("Other", "extract-images");
addEndpointToGroup("Other", "change-metadata");
addEndpointToGroup("Other", "update-metadata");
addEndpointToGroup("Other", "flatten");
addEndpointToGroup("Other", "unlock-pdf-forms");
addEndpointToGroup("Other", REMOVE_BLANKS);
addEndpointToGroup("Other", "remove-annotations");
addEndpointToGroup("Other", "compare");
addEndpointToGroup("Other", "add-page-numbers");
addEndpointToGroup("Other", "get-info-on-pdf");
addEndpointToGroup("Other", "remove-image-pdf");
addEndpointToGroup("Other", "add-attachments");
addEndpointToGroup("Other", "replace-invert-pdf");
addEndpointToGroup("Other", "edit-table-of-contents");
addEndpointToGroup("Other", "text-editor-pdf");
// Backend-only endpoints (not in frontend tool registry endpoints)
addEndpointToGroup("Other", "add-image");
addEndpointToGroup("Other", "compare");
addEndpointToGroup("Other", "view-pdf");
addEndpointToGroup("Other", "replace-and-invert-color-pdf");
addEndpointToGroup("Other", "multi-tool");
// Adding form-related endpoints to "Other" group
addEndpointToGroup("Other", "fields");
addEndpointToGroup("Other", "modify-fields");
addEndpointToGroup("Other", "delete-fields");
addEndpointToGroup("Other", "fill");
// Adding endpoints to "Advance" group
addEndpointToGroup("Advance", "adjust-contrast");
addEndpointToGroup("Advance", "compress-pdf");
addEndpointToGroup("Advance", "extract-image-scans");
addEndpointToGroup("Advance", "repair");
addEndpointToGroup("Advance", "auto-rename");
addEndpointToGroup("Advance", "pipeline");
addEndpointToGroup("Advance", "handleData");
addEndpointToGroup("Advance", "scanner-effect");
addEndpointToGroup("Advance", "auto-split-pdf");
addEndpointToGroup("Advance", "show-javascript");
addEndpointToGroup("Advance", "split-by-size-or-count");
addEndpointToGroup("Advance", "overlay-pdf");
addEndpointToGroup("Advance", "split-pdf-by-sections");
addEndpointToGroup("Advance", "edit-table-of-contents");
addEndpointToGroup("Advance", "split-pdf-by-chapters");
// Backend-only endpoints
addEndpointToGroup("Advance", "adjust-contrast");
addEndpointToGroup("Advance", "pipeline");
// CLI
addEndpointToGroup("CLI", "compress-pdf");
@@ -436,8 +438,8 @@ public class EndpointConfiguration {
// Java
addEndpointToGroup("Java", "merge-pdfs");
addEndpointToGroup("Java", "remove-pages");
addEndpointToGroup("Java", "split-pdfs");
addEndpointToGroup("Java", "pdf-organizer");
addEndpointToGroup("Java", "split-pages");
addEndpointToGroup("Java", "rearrange-pages");
addEndpointToGroup("Java", "rotate-pdf");
addEndpointToGroup("Java", "pdf-to-img");
addEndpointToGroup("Java", "img-to-pdf");
@@ -445,9 +447,10 @@ public class EndpointConfiguration {
addEndpointToGroup("Java", "remove-password");
addEndpointToGroup("Java", "change-permissions");
addEndpointToGroup("Java", "add-watermark");
addEndpointToGroup("Java", "add-stamp");
addEndpointToGroup("Java", "add-image");
addEndpointToGroup("Java", "extract-images");
addEndpointToGroup("Java", "change-metadata");
addEndpointToGroup("Java", "update-metadata");
addEndpointToGroup("Java", "cert-sign");
addEndpointToGroup("Java", "remove-cert-sign");
addEndpointToGroup("Java", "multi-page-layout");
@@ -459,7 +462,6 @@ public class EndpointConfiguration {
addEndpointToGroup("Java", "sanitize-pdf");
addEndpointToGroup("Java", "crop");
addEndpointToGroup("Java", "get-info-on-pdf");
addEndpointToGroup("Java", "extract-page");
addEndpointToGroup("Java", "pdf-to-single-page");
addEndpointToGroup("Java", "markdown-to-pdf");
addEndpointToGroup("Java", "show-javascript");
@@ -469,7 +471,9 @@ public class EndpointConfiguration {
addEndpointToGroup("Java", "split-by-size-or-count");
addEndpointToGroup("Java", "overlay-pdf");
addEndpointToGroup("Java", "split-pdf-by-sections");
addEndpointToGroup("Java", "split-pdf-by-chapters");
addEndpointToGroup("Java", REMOVE_BLANKS);
addEndpointToGroup("Java", "remove-annotations");
addEndpointToGroup("Java", "pdf-to-text");
addEndpointToGroup("Java", "remove-image-pdf");
addEndpointToGroup("Java", "pdf-to-markdown");
@@ -479,15 +483,24 @@ public class EndpointConfiguration {
addEndpointToGroup("Java", "pdf-to-cbz");
addEndpointToGroup("Java", "pdf-to-json");
addEndpointToGroup("Java", "json-to-pdf");
addEndpointToGroup("rar", "pdf-to-cbr");
addEndpointToGroup("Java", "pdf-to-video");
addEndpointToGroup("Java", "verify-pdf");
addEndpointToGroup("Java", "flatten");
addEndpointToGroup("Java", "unlock-pdf-forms");
addEndpointToGroup("Java", "validate-signature");
addEndpointToGroup("Java", "text-editor-pdf");
addEndpointToGroup("Java", "edit-table-of-contents");
addEndpointToGroup("Java", "pdf-to-epub");
addEndpointToGroup("Java", "eml-to-pdf");
addEndpointToGroup("Java", "handleData");
addEndpointToGroup("rar", "pdf-to-cbr");
// Javascript
addEndpointToGroup("Javascript", "pdf-organizer");
addEndpointToGroup("Javascript", "rearrange-pages");
addEndpointToGroup("Javascript", "sign");
addEndpointToGroup("Javascript", "compare");
addEndpointToGroup("Javascript", "adjust-contrast");
addEndpointToGroup("Javascript", "text-editor-pdf");
/* qpdf */
addEndpointToGroup("qpdf", "repair");
@@ -498,6 +511,7 @@ public class EndpointConfiguration {
addEndpointToGroup("Ghostscript", "compress-pdf");
addEndpointToGroup("Ghostscript", "crop");
addEndpointToGroup("Ghostscript", "replace-invert-pdf");
addEndpointToGroup("Ghostscript", "scanner-effect");
addEndpointToGroup("Ghostscript", "pdf-to-vector");
addEndpointToGroup("Ghostscript", "vector-to-pdf");
@@ -546,6 +560,9 @@ public class EndpointConfiguration {
// Pdftohtml dependent endpoints
addEndpointToGroup("Pdftohtml", "pdf-to-html");
addEndpointToGroup("Pdftohtml", "pdf-to-markdown");
// Calibre dependent endpoints
addEndpointToGroup("Calibre", "pdf-to-epub");
}
private void processEnvironmentConfigs() {
@@ -215,75 +215,182 @@ public class ApplicationProperties {
@Setter
@ToString
public static class SAML2 {
private String provider;
private Boolean enabled = false;
private Boolean autoCreateUser = false;
private Boolean blockRegistration = false;
private String registrationId = "stirling";
private Boolean enableSingleLogout = false;
@ToString.Exclude
@JsonProperty("idpMetadataUri")
@ToString.Exclude private String metadataUri;
private Provider provider = new Provider();
private SP sp = new SP();
// Legacy field mappings for backward compatibility
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String idpMetadataUri;
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String idpSingleLogoutUrl;
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String idpSingleLoginUrl;
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String idpIssuer;
@JsonProperty("idpCert")
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String idpEntityId;
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String idpCert;
@ToString.Exclude
@JsonProperty("privateKey")
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String privateKey;
@ToString.Exclude
@JsonProperty("spCert")
@Deprecated(since = "2.3.1", forRemoval = true)
@JsonIgnore
private String spCert;
/** Migrate legacy flat properties to new nested structure on set. */
public void setIdpMetadataUri(String value) {
this.idpMetadataUri = value;
if (value != null
&& !value.isBlank()
&& (metadataUri == null || metadataUri.isBlank())) {
this.metadataUri = value;
}
}
public void setIdpSingleLoginUrl(String value) {
this.idpSingleLoginUrl = value;
if (value != null && !value.isBlank()) {
this.provider.setSingleLoginUrl(value);
}
}
public void setIdpSingleLogoutUrl(String value) {
this.idpSingleLogoutUrl = value;
if (value != null && !value.isBlank()) {
this.provider.setSingleLogoutUrl(value);
}
}
public void setIdpIssuer(String value) {
this.idpIssuer = value;
if (value != null && !value.isBlank()) {
this.provider.setEntityId(value);
}
}
public void setIdpEntityId(String value) {
this.idpEntityId = value;
if (value != null && !value.isBlank()) {
this.provider.setEntityId(value);
}
}
public void setIdpCert(String value) {
this.idpCert = value;
if (value != null && !value.isBlank()) {
this.provider.setCert(value);
}
}
public void setPrivateKey(String value) {
this.privateKey = value;
if (value != null && !value.isBlank()) {
this.sp.setPrivateKey(value);
}
}
public void setSpCert(String value) {
this.spCert = value;
if (value != null && !value.isBlank()) {
this.sp.setCert(value);
}
}
@JsonIgnore
public InputStream getIdpMetadataUri() throws IOException {
if (idpMetadataUri.startsWith("classpath:")) {
return new ClassPathResource(idpMetadataUri.substring("classpath:".length()))
public InputStream getMetadataUriAsStream() throws IOException {
String uri = getEffectiveMetadataUri();
if (uri == null || uri.isBlank()) {
throw new IOException("security.saml2.metadataUri is not configured");
}
if (uri.startsWith("classpath:")) {
return new ClassPathResource(uri.substring("classpath:".length()))
.getInputStream();
}
try {
URI uri = new URI(idpMetadataUri);
URL url = uri.toURL();
URI parsedUri = new URI(uri);
URL url = parsedUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
return connection.getInputStream();
} catch (URISyntaxException e) {
throw new IOException("Invalid URI format: " + idpMetadataUri, e);
throw new IOException("Invalid URI format: " + uri, e);
}
}
@JsonIgnore
public Resource getSpCert() {
if (spCert == null) return null;
if (spCert.startsWith("classpath:")) {
return new ClassPathResource(spCert.substring("classpath:".length()));
} else {
return new FileSystemResource(spCert);
public String getEffectiveMetadataUri() {
if (metadataUri != null && !metadataUri.isBlank()) {
return metadataUri;
}
return idpMetadataUri; // Legacy fallback
}
/** IdP configuration - manual fallback when metadata is unavailable. */
@Data
public static class Provider {
private String name = ""; // Display name only
private String singleLoginUrl;
private String singleLogoutUrl;
private String entityId;
@ToString.Exclude private String cert;
@JsonIgnore
public Resource getCertResource() {
if (cert == null) return null;
if (cert.startsWith("classpath:")) {
return new ClassPathResource(cert.substring("classpath:".length()));
} else {
return new FileSystemResource(cert);
}
}
}
@JsonIgnore
public Resource getIdpCert() {
if (idpCert == null) return null;
if (idpCert.startsWith("classpath:")) {
return new ClassPathResource(idpCert.substring("classpath:".length()));
} else {
return new FileSystemResource(idpCert);
}
}
/** Service Provider (SP) credentials for signing SAML requests. */
@Data
public static class SP {
@ToString.Exclude private String privateKey;
@ToString.Exclude private String cert;
@JsonIgnore
public Resource getPrivateKey() {
if (privateKey == null) return null;
if (privateKey.startsWith("classpath:")) {
return new ClassPathResource(privateKey.substring("classpath:".length()));
} else {
return new FileSystemResource(privateKey);
@JsonIgnore
public Resource getPrivateKeyResource() {
if (privateKey == null) return null;
if (privateKey.startsWith("classpath:")) {
return new ClassPathResource(privateKey.substring("classpath:".length()));
} else {
return new FileSystemResource(privateKey);
}
}
@JsonIgnore
public Resource getCertResource() {
if (cert == null) return null;
if (cert.startsWith("classpath:")) {
return new ClassPathResource(cert.substring("classpath:".length()));
} else {
return new FileSystemResource(cert);
}
}
}
}
@@ -29,7 +29,7 @@ public class RequestUriUtils {
|| normalizedUri.startsWith("/pdfium/")
|| normalizedUri.startsWith("/assets/")
|| normalizedUri.startsWith("/locales/")
|| normalizedUri.startsWith("/Login/")
|| normalizedUri.startsWith("/login/")
|| normalizedUri.startsWith("/samples/")
|| normalizedUri.startsWith("/classic-logo/")
|| normalizedUri.startsWith("/modern-logo/")
@@ -165,9 +165,9 @@ public class RequestUriUtils {
|| trimmedUri.contains("/oauth2/authorization/") // OAuth2 authorization endpoint
|| trimmedUri.startsWith("/api/v1/auth/login")
|| trimmedUri.startsWith("/api/v1/auth/refresh")
|| trimmedUri.startsWith("/api/v1/auth/logout")
|| trimmedUri.startsWith("/logout")
|| trimmedUri.startsWith(
"/api/v1/proprietary/ui-data/login") // Login page config (SSO providers +
"/api/v1/proprietary/ui-data/login") // Login page config (SSO providers
// enableLogin)
|| trimmedUri.startsWith(
"/api/v1/ui-data/footer-info") // Public footer configuration
@@ -31,9 +31,9 @@ class ApplicationPropertiesSaml2HttpTest {
String url = server.url("/meta").toString();
var s = new ApplicationProperties.Security.SAML2();
s.setIdpMetadataUri(url);
s.setMetadataUri(url);
try (InputStream in = s.getIdpMetadataUri()) {
try (InputStream in = s.getMetadataUriAsStream()) {
String body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
assertTrue(body.contains("EntityDescriptor"));
}
@@ -44,9 +44,9 @@ class ApplicationPropertiesSaml2HttpTest {
void idpMetadataUri_invalidUri_triggers_catch_and_throwsIOException() {
// Ungültige URI -> new URI(...) wirft URISyntaxException -> catch -> IOException
var s = new ApplicationProperties.Security.SAML2();
s.setIdpMetadataUri("http:##invalid uri"); // absichtlich kaputt (Leerzeichen + ##)
s.setMetadataUri("http:##invalid uri"); // absichtlich kaputt (Leerzeichen + ##)
assertThrows(IOException.class, s::getIdpMetadataUri);
assertThrows(IOException.class, s::getMetadataUriAsStream);
}
@Test
@@ -57,8 +57,8 @@ class ApplicationPropertiesSaml2HttpTest {
Path tmp = Files.createTempFile("spdf-spcert-", ".crt");
Files.writeString(tmp, "CERT");
s.setSpCert(tmp.toString());
Resource r = s.getSpCert();
s.getSp().setCert(tmp.toString());
Resource r = s.getSp().getCertResource();
assertNotNull(r);
assertInstanceOf(FileSystemResource.class, r, "Expected FileSystemResource for FS path");
@@ -71,8 +71,8 @@ class ApplicationPropertiesSaml2HttpTest {
// bewusst nicht existierender Pfad -> else-Zweig wird trotzdem genommen
String missing = "/this/path/does/not/exist/idp.crt";
s.setIdpCert(missing);
Resource r = s.getIdpCert();
s.getProvider().setCert(missing);
Resource r = s.getProvider().getCertResource();
assertNotNull(r);
assertInstanceOf(FileSystemResource.class, r, "Expected FileSystemResource for FS path");
@@ -15,9 +15,9 @@ class ApplicationPropertiesSaml2ResourceTest {
@Test
void idpMetadataUri_classpath_is_resolved() throws Exception {
var s = new ApplicationProperties.Security.SAML2();
s.setIdpMetadataUri("classpath:saml/dummy.txt");
s.setMetadataUri("classpath:saml/dummy.txt");
try (InputStream in = s.getIdpMetadataUri()) {
try (InputStream in = s.getMetadataUriAsStream()) {
assertNotNull(in, "Classpath InputStream should not be null");
String txt = new String(in.readAllBytes(), StandardCharsets.UTF_8);
assertTrue(txt.contains("ok"));
@@ -28,27 +28,26 @@ class ApplicationPropertiesSaml2ResourceTest {
void spCert_idpCert_privateKey_null_classpath_and_filesystem() throws Exception {
var s = new ApplicationProperties.Security.SAML2();
s.setSpCert(null);
s.setIdpCert(null);
s.setPrivateKey(null);
assertNull(s.getSpCert());
assertNull(s.getIdpCert());
assertNull(s.getPrivateKey());
// Test null values via the nested structure
assertNull(s.getSp().getCertResource());
assertNull(s.getProvider().getCertResource());
assertNull(s.getSp().getPrivateKeyResource());
s.setSpCert("classpath:saml/dummy.txt");
s.setIdpCert("classpath:saml/dummy.txt");
s.setPrivateKey("classpath:saml/dummy.txt");
Resource sp = s.getSpCert();
Resource idp = s.getIdpCert();
Resource pk = s.getPrivateKey();
// Set classpath resources via the nested structure
s.getSp().setCert("classpath:saml/dummy.txt");
s.getProvider().setCert("classpath:saml/dummy.txt");
s.getSp().setPrivateKey("classpath:saml/dummy.txt");
Resource sp = s.getSp().getCertResource();
Resource idp = s.getProvider().getCertResource();
Resource pk = s.getSp().getPrivateKeyResource();
assertTrue(sp.exists());
assertTrue(idp.exists());
assertTrue(pk.exists());
Path tmp = Files.createTempFile("spdf-key-", ".pem");
Files.writeString(tmp, "KEY");
s.setPrivateKey(tmp.toString());
Resource pkFs = s.getPrivateKey();
s.getSp().setPrivateKey(tmp.toString());
Resource pkFs = s.getSp().getPrivateKeyResource();
assertNotNull(pkFs);
assertTrue(pkFs.exists());
}
@@ -118,7 +118,8 @@ public class ExternalAppDepConfig {
for (String group : affectedGroups) {
List<String> affectedFeatures = getAffectedFeatures(group);
endpointConfiguration.disableGroup(group);
endpointConfiguration.disableGroup(
group, EndpointConfiguration.DisableReason.DEPENDENCY);
log.warn(
"Missing dependency: {} - Disabling group: {} (Affected features: {})",
command,
@@ -143,7 +144,8 @@ public class ExternalAppDepConfig {
commandToGroupMapping.getOrDefault(
command, List.of("Weasyprint"));
for (String group : affectedGroups) {
endpointConfiguration.disableGroup(group);
endpointConfiguration.disableGroup(
group, EndpointConfiguration.DisableReason.DEPENDENCY);
}
log.warn(
"WeasyPrint version {} is below required {} - disabling"
@@ -172,7 +174,8 @@ public class ExternalAppDepConfig {
List<String> affectedGroups =
commandToGroupMapping.getOrDefault(command, List.of("qpdf"));
for (String group : affectedGroups) {
endpointConfiguration.disableGroup(group);
endpointConfiguration.disableGroup(
group, EndpointConfiguration.DisableReason.DEPENDENCY);
}
log.warn(
"qpdf version {} is below required {} - disabling group(s): {}",
@@ -226,7 +229,8 @@ public class ExternalAppDepConfig {
int ec = runAndWait(List.of(python, "-c", "import cv2"), DEFAULT_TIMEOUT).exitCode();
if (ec != 0) {
List<String> openCVFeatures = getAffectedFeatures("OpenCV");
endpointConfiguration.disableGroup("OpenCV");
endpointConfiguration.disableGroup(
"OpenCV", EndpointConfiguration.DisableReason.DEPENDENCY);
log.warn(
"OpenCV not available in Python - Disabling OpenCV features: {}",
String.join(", ", openCVFeatures));
@@ -236,8 +240,10 @@ public class ExternalAppDepConfig {
private void disablePythonAndOpenCV(String reason) {
List<String> pythonFeatures = getAffectedFeatures("Python");
List<String> openCVFeatures = getAffectedFeatures("OpenCV");
endpointConfiguration.disableGroup("Python");
endpointConfiguration.disableGroup("OpenCV");
endpointConfiguration.disableGroup(
"Python", EndpointConfiguration.DisableReason.DEPENDENCY);
endpointConfiguration.disableGroup(
"OpenCV", EndpointConfiguration.DisableReason.DEPENDENCY);
log.warn(
"Missing dependency: Python (reason: {}) - Disabling Python features: {} and OpenCV"
+ " features: {}",
@@ -7,11 +7,13 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
@@ -58,6 +60,13 @@ public class StampController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
private static final int MAX_DATE_FORMAT_LENGTH = 50;
private static final Pattern SAFE_DATE_FORMAT_PATTERN =
Pattern.compile("^[yMdHhmsS/\\-:\\s.,'+EGuwWDFzZXa]+$");
private static final Pattern CUSTOM_DATE_PATTERN = Pattern.compile("@date\\{([^}]{1,50})\\}");
// Placeholder for escaped @ symbol (using Unicode private use area)
private static final String ESCAPED_AT_PLACEHOLDER = "\uE000ESCAPED_AT\uE000";
/**
* Initialize data binder for multipart file uploads. This method registers a custom editor for
* MultipartFile to handle file uploads. It sets the MultipartFile to null if the uploaded file
@@ -166,7 +175,9 @@ public class StampController {
overrideX,
overrideY,
margin,
customColor);
customColor,
pageIndex,
pdfFileName);
} else if ("image".equalsIgnoreCase(stampType)) {
addImageStamp(
contentStream,
@@ -201,9 +212,11 @@ public class StampController {
float fontSize,
String alphabet,
float overrideX, // X override
float overrideY,
float overrideY, // Y override
float margin,
String colorString) // Y override
String colorString,
int currentPageNumber,
String filename)
throws IOException {
String resourceDir;
PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
@@ -231,8 +244,6 @@ public class StampController {
}
}
contentStream.setFont(font, fontSize);
Color redactColor;
try {
if (!colorString.startsWith("#")) {
@@ -240,47 +251,54 @@ public class StampController {
}
redactColor = Color.decode(colorString);
} catch (NumberFormatException e) {
redactColor = Color.LIGHT_GRAY;
}
contentStream.setNonStrokingColor(redactColor);
PDRectangle pageSize = page.getMediaBox();
float x, y;
if (overrideX >= 0 && overrideY >= 0) {
// Use override values if provided
x = overrideX;
y = overrideY;
} else {
x = calculatePositionX(pageSize, position, fontSize, font, fontSize, stampText, margin);
y =
calculatePositionY(
pageSize, position, calculateTextCapHeight(font, fontSize), margin);
}
String currentDate = LocalDate.now().toString();
String currentTime = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
int pageCount = document.getNumberOfPages();
String processedStampText =
stampText
.replace("@date", currentDate)
.replace("@time", currentTime)
.replace("@page_count", String.valueOf(pageCount));
processStampText(stampText, currentPageNumber, pageCount, filename, document);
// Split the stampText into multiple lines
String[] lines =
String normalizedText =
RegexPatternUtils.getInstance()
.getEscapedNewlinePattern()
.split(processedStampText);
.matcher(processedStampText)
.replaceAll("\n");
String[] lines = normalizedText.split("\\r?\\n");
PDRectangle pageSize = page.getMediaBox();
// Use fontSize directly (default 40 if not specified)
float effectiveFontSize = fontSize > 0 ? fontSize : 40f;
contentStream.setFont(font, effectiveFontSize);
// Calculate dynamic line height based on font ascent and descent
float ascent = font.getFontDescriptor().getAscent();
float descent = font.getFontDescriptor().getDescent();
float lineHeight = ((ascent - descent) / 1000) * fontSize;
float lineHeight = ((ascent - descent) / 1000) * effectiveFontSize;
float maxLineWidth = 0;
for (String line : lines) {
float lineWidth = calculateTextWidth(line, font, effectiveFontSize);
if (lineWidth > maxLineWidth) {
maxLineWidth = lineWidth;
}
}
float totalTextHeight = lines.length * lineHeight;
float x, y;
if (overrideX >= 0 && overrideY >= 0) {
x = overrideX;
y = overrideY;
} else {
x = calculatePositionX(pageSize, position, maxLineWidth, margin);
y = calculatePositionY(pageSize, position, totalTextHeight, margin);
}
contentStream.beginText();
for (int i = 0; i < lines.length; i++) {
@@ -293,6 +311,140 @@ public class StampController {
contentStream.endText();
}
/**
* Process stamp text by replacing all @commands with their actual values. Supported commands:
*
* <p>Date & Time:
*
* <ul>
* <li>@date - Current date (YYYY-MM-DD)
* <li>@time - Current time (HH:mm:ss)
* <li>@datetime - Current date and time (YYYY-MM-DD HH:mm:ss)
* <li>@date{format} - Custom date/time format (e.g., @date{dd/MM/yyyy})
* <li>@year - Current year (4 digits)
* <li>@month - Current month (01-12)
* <li>@day - Current day of month (01-31)
* </ul>
*
* <p>Page Information:
*
* <ul>
* <li>@page_number or @page - Current page number
* <li>@total_pages or @page_count - Total number of pages
* </ul>
*
* <p>File Information:
*
* <ul>
* <li>@filename - Original filename (without extension)
* <li>@filename_full - Original filename (with extension)
* </ul>
*
* <p>Document Metadata:
*
* <ul>
* <li>@author - Document author (from PDF metadata)
* <li>@title - Document title (from PDF metadata)
* <li>@subject - Document subject (from PDF metadata)
* </ul>
*
* <p>Other:
*
* <ul>
* <li>@uuid - Short unique identifier (8 characters)
* </ul>
*/
private String processStampText(
String stampText,
int currentPageNumber,
int totalPages,
String filename,
PDDocument document) {
if (stampText == null || stampText.isEmpty()) {
return "";
}
// Handle escaped @@ sequences first - replace with placeholder to preserve literal @
String result = stampText.replace("@@", ESCAPED_AT_PLACEHOLDER);
LocalDateTime now = LocalDateTime.now();
String currentDate = now.toLocalDate().toString();
String currentTime = now.toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
String currentDateTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String filenameWithoutExt = filename != null ? filename : "";
if (filename != null && filename.contains(".")) {
int lastDot = filename.lastIndexOf('.');
if (lastDot > 0) { // Ensure there's actually a name before the dot
filenameWithoutExt = filename.substring(0, lastDot);
}
}
String author = "";
String title = "";
String subject = "";
if (document != null && document.getDocumentInformation() != null) {
var info = document.getDocumentInformation();
author = info.getAuthor() != null ? info.getAuthor() : "";
title = info.getTitle() != null ? info.getTitle() : "";
subject = info.getSubject() != null ? info.getSubject() : "";
}
String uuid = UUID.randomUUID().toString().substring(0, 8);
// Process @date{format} with custom format first (must be before simple @date)
Matcher matcher = CUSTOM_DATE_PATTERN.matcher(result);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
String format = matcher.group(1);
String replacement = processCustomDateFormat(format, now);
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(sb);
result = sb.toString();
result =
result.replace("@datetime", currentDateTime)
.replace("@date", currentDate)
.replace("@time", currentTime)
.replace("@year", String.valueOf(now.getYear()))
.replace("@month", String.format("%02d", now.getMonthValue()))
.replace("@day", String.format("%02d", now.getDayOfMonth()))
.replace("@page_number", String.valueOf(currentPageNumber))
.replace(
"@page_count", String.valueOf(totalPages)) // Must come before @page
.replace("@total_pages", String.valueOf(totalPages))
.replace(
"@page",
String.valueOf(currentPageNumber)) // Must come after @page_count
.replace("@filename_full", filename != null ? filename : "")
.replace("@filename", filenameWithoutExt)
.replace("@author", author)
.replace("@title", title)
.replace("@subject", subject)
.replace("@uuid", uuid);
result = result.replace(ESCAPED_AT_PLACEHOLDER, "@");
return result;
}
private String processCustomDateFormat(String format, LocalDateTime now) {
if (format == null || format.length() > MAX_DATE_FORMAT_LENGTH) {
return "[invalid format: too long]";
}
if (!SAFE_DATE_FORMAT_PATTERN.matcher(format).matches()) {
return "[invalid format]";
}
try {
return now.format(DateTimeFormatter.ofPattern(format));
} catch (IllegalArgumentException e) {
return "[invalid format: " + format + "]";
}
}
private void addImageStamp(
PDPageContentStream contentStream,
MultipartFile stampImage,
@@ -329,8 +481,8 @@ public class StampController {
x = overrideX;
y = overrideY;
} else {
x = calculatePositionX(pageSize, position, desiredPhysicalWidth, null, 0, null, margin);
y = calculatePositionY(pageSize, position, fontSize, margin);
x = calculatePositionX(pageSize, position, desiredPhysicalWidth, margin);
y = calculatePositionY(pageSize, position, desiredPhysicalHeight, margin);
}
contentStream.saveGraphicsState();
@@ -341,23 +493,14 @@ public class StampController {
}
private float calculatePositionX(
PDRectangle pageSize,
int position,
float contentWidth,
PDFont font,
float fontSize,
String text,
float margin)
throws IOException {
float actualWidth =
(text != null) ? calculateTextWidth(text, font, fontSize) : contentWidth;
PDRectangle pageSize, int position, float contentWidth, float margin) {
return switch (position % 3) {
case 1: // Left
yield pageSize.getLowerLeftX() + margin;
case 2: // Center
yield (pageSize.getWidth() - actualWidth) / 2;
yield (pageSize.getWidth() - contentWidth) / 2;
case 0: // Right
yield pageSize.getUpperRightX() - actualWidth - margin;
yield pageSize.getUpperRightX() - contentWidth - margin;
default:
yield 0;
};
@@ -366,12 +509,12 @@ public class StampController {
private float calculatePositionY(
PDRectangle pageSize, int position, float height, float margin) {
return switch ((position - 1) / 3) {
case 0: // Top
yield pageSize.getUpperRightY() - height - margin;
case 1: // Middle
yield (pageSize.getHeight() - height) / 2;
case 2: // Bottom
yield pageSize.getLowerLeftY() + margin;
case 0: // Top - first line near the top
yield pageSize.getUpperRightY() - margin;
case 1: // Middle - center of text block at page center
yield (pageSize.getHeight() + height) / 2;
case 2: // Bottom - first line positioned so last line is at bottom margin
yield pageSize.getLowerLeftY() + margin + height;
default:
yield 0;
};
@@ -380,8 +523,4 @@ public class StampController {
private float calculateTextWidth(String text, PDFont font, float fontSize) throws IOException {
return font.getStringWidth(text) / 1000 * fontSize;
}
private float calculateTextCapHeight(PDFont font, float fontSize) {
return font.getFontDescriptor().getCapHeight() / 1000 * fontSize;
}
}
@@ -32,8 +32,8 @@ public class AddStampRequest extends PDFWithPageNums {
private String alphabet = "roman";
@Schema(
description = "The font size of the stamp text and image",
defaultValue = "30",
description = "The font size of the stamp text and image in points.",
defaultValue = "40",
requiredMode = Schema.RequiredMode.REQUIRED)
private float fontSize;
@@ -1,10 +1,9 @@
multipart.enabled=true
logging.level.org.springframework=WARN
logging.level.org.springframework.security=WARN
logging.level.org.hibernate=WARN
logging.level.org.eclipse.jetty=WARN
#logging.level.org.springframework.security.oauth2=DEBUG
#logging.level.org.springframework.security=DEBUG
#logging.level.org.springframework.security.oauth2=DEBUG
#logging.level.org.opensaml=DEBUG
#logging.level.stirling.software.proprietary.security=DEBUG
logging.level.com.zaxxer.hikari=WARN
@@ -47,20 +47,23 @@ security:
provider: google # set this to your OAuth Provider's name, e.g., 'google' or 'keycloak'
saml2:
enabled: false # Only enabled for paid enterprise clients (enterpriseEdition.enabled must be true)
provider: "" # The name of your Provider
enableSingleLogout: false # set to 'true' to enable Single Logout (SP-initiated SLO). Logs the user out from the IdP
autoCreateUser: true # set to 'true' to allow auto-creation of non-existing users
blockRegistration: false # set to 'true' to deny login with SSO without prior registration by an admin
registrationId: stirling # The name of your Service Provider (SP) app name. Should match the name in the path for your SSO & SLO URLs
idpMetadataUri: https://dev-XXXXXXXX.okta.com/app/externalKey/sso/saml/metadata # The uri for your Provider's metadata
idpSingleLoginUrl: https://dev-XXXXXXXX.okta.com/app/dev-XXXXXXXX_stirlingpdf_1/externalKey/sso/saml # The URL for initiating SSO. Provided by your Provider
idpSingleLogoutUrl: https://dev-XXXXXXXX.okta.com/app/dev-XXXXXXXX_stirlingpdf_1/externalKey/slo/saml # The URL for initiating SLO. Provided by your Provider
idpIssuer: "" # The ID of 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
spCert: classpath:saml-public-cert.crt # Your signing certificate. Generated from your keypair
metadataUri: https://dev-XXXXXXXX.okta.com/app/externalKey/sso/saml/metadata # RECOMMENDED: Your IdP's metadata URI. When provided, IdP config is auto-discovered.
provider: # IdP manual configuration - use if metadataUri is not available
name: "" # Display name for your IdP (optional)
singleLoginUrl: "" # SSO URL
singleLogoutUrl: "" # SLO URL
entityId: "" # IdP Entity ID
cert: classpath:okta.cert # IdP signing certificate
sp: # Service Provider (your app) credentials for signing SAML requests. Generated from your keypair
privateKey: classpath:saml-private-key.key # Your private key.
cert: classpath:saml-public-cert.crt # Your signing certificate.
# 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:
persistence: true # Set to 'true' to enable JWT key store
enableKeyRotation: true # Set to 'true' to enable key pair rotation
enableKeyCleanup: true # Set to 'true' to enable key pair cleanup
@@ -0,0 +1,567 @@
package stirling.software.SPDF.controller.api.misc;
import static org.junit.jupiter.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFileManager;
@ExtendWith(MockitoExtension.class)
class StampControllerTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@InjectMocks private StampController stampController;
private Method processStampTextMethod;
private Method processCustomDateFormatMethod;
@BeforeEach
void setUp() throws NoSuchMethodException {
processStampTextMethod =
StampController.class.getDeclaredMethod(
"processStampText",
String.class,
int.class,
int.class,
String.class,
PDDocument.class);
processStampTextMethod.setAccessible(true);
processCustomDateFormatMethod =
StampController.class.getDeclaredMethod(
"processCustomDateFormat", String.class, LocalDateTime.class);
processCustomDateFormatMethod.setAccessible(true);
}
private String invokeProcessStampText(
String stampText, int pageNumber, int totalPages, String filename, PDDocument document)
throws Exception {
try {
return (String)
processStampTextMethod.invoke(
stampController, stampText, pageNumber, totalPages, filename, document);
} catch (InvocationTargetException e) {
throw (Exception) e.getCause();
}
}
private String invokeProcessCustomDateFormat(String format, LocalDateTime now)
throws Exception {
try {
return (String) processCustomDateFormatMethod.invoke(stampController, format, now);
} catch (InvocationTargetException e) {
throw (Exception) e.getCause();
}
}
@Nested
@DisplayName("Basic Variable Substitution Tests")
class BasicVariableTests {
@Test
@DisplayName("Should replace @page_number with current page")
void testPageNumberReplacement() throws Exception {
String result = invokeProcessStampText("Page @page_number", 5, 20, "test.pdf", null);
assertEquals("Page 5", result);
}
@Test
@DisplayName("Should replace @total_pages with total page count")
void testTotalPagesReplacement() throws Exception {
String result =
invokeProcessStampText("of @total_pages pages", 1, 100, "test.pdf", null);
assertEquals("of 100 pages", result);
}
@Test
@DisplayName("Should replace combined page variables")
void testCombinedPageVariables() throws Exception {
String result =
invokeProcessStampText(
"Page @page_number of @total_pages", 5, 20, "test.pdf", null);
assertEquals("Page 5 of 20", result);
}
@Test
@DisplayName("Should replace @page alias")
void testPageAlias() throws Exception {
String result = invokeProcessStampText("Page @page", 7, 10, "test.pdf", null);
assertEquals("Page 7", result);
}
@Test
@DisplayName("Should replace @page_count alias for total pages")
void testPageCountAlias() throws Exception {
String result = invokeProcessStampText("Total: @page_count", 1, 50, "test.pdf", null);
assertEquals("Total: 50", result);
}
}
@Nested
@DisplayName("Filename Variable Tests")
class FilenameTests {
@Test
@DisplayName("Should replace @filename with filename without extension")
void testFilenameWithoutExtension() throws Exception {
String result = invokeProcessStampText("File: @filename", 1, 1, "document.pdf", null);
assertEquals("File: document", result);
}
@Test
@DisplayName("Should replace @filename_full with full filename")
void testFilenameWithExtension() throws Exception {
String result =
invokeProcessStampText("File: @filename_full", 1, 1, "document.pdf", null);
assertEquals("File: document.pdf", result);
}
@Test
@DisplayName("Should handle filename without extension")
void testFilenameWithoutDot() throws Exception {
String result = invokeProcessStampText("@filename", 1, 1, "document", null);
assertEquals("document", result);
}
@Test
@DisplayName("Should handle null filename")
void testNullFilename() throws Exception {
String result = invokeProcessStampText("File: @filename", 1, 1, null, null);
assertEquals("File: ", result);
}
@Test
@DisplayName("Should handle filename with multiple dots")
void testFilenameMultipleDots() throws Exception {
String result = invokeProcessStampText("@filename", 1, 1, "my.document.v2.pdf", null);
assertEquals("my.document.v2", result);
}
@Test
@DisplayName("Should handle hidden file (starts with dot)")
void testHiddenFile() throws Exception {
String result = invokeProcessStampText("@filename", 1, 1, ".hidden.pdf", null);
assertEquals(".hidden", result);
}
}
@Nested
@DisplayName("Date/Time Variable Tests")
class DateTimeTests {
@Test
@DisplayName("Should replace @date with current date")
void testDateReplacement() throws Exception {
String result = invokeProcessStampText("Date: @date", 1, 1, "test.pdf", null);
assertTrue(
result.matches("Date: \\d{4}-\\d{2}-\\d{2}"),
"Date should match YYYY-MM-DD format");
}
@Test
@DisplayName("Should replace @time with current time")
void testTimeReplacement() throws Exception {
String result = invokeProcessStampText("Time: @time", 1, 1, "test.pdf", null);
assertTrue(
result.matches("Time: \\d{2}:\\d{2}:\\d{2}"),
"Time should match HH:mm:ss format");
}
@Test
@DisplayName("Should replace @datetime with combined date and time")
void testDateTimeReplacement() throws Exception {
String result = invokeProcessStampText("@datetime", 1, 1, "test.pdf", null);
// DateTime format: YYYY-MM-DD HH:mm:ss
assertTrue(
result.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"),
"DateTime should match YYYY-MM-DD HH:mm:ss format");
}
@Test
@DisplayName("Should replace @year with current year")
void testYearReplacement() throws Exception {
String result = invokeProcessStampText("© @year", 1, 1, "test.pdf", null);
int currentYear = LocalDateTime.now().getYear();
assertEquals("© " + currentYear, result);
}
@Test
@DisplayName("Should replace @month with zero-padded month")
void testMonthReplacement() throws Exception {
String result = invokeProcessStampText("Month: @month", 1, 1, "test.pdf", null);
assertTrue(result.matches("Month: \\d{2}"), "Month should be zero-padded");
}
@Test
@DisplayName("Should replace @day with zero-padded day")
void testDayReplacement() throws Exception {
String result = invokeProcessStampText("Day: @day", 1, 1, "test.pdf", null);
assertTrue(result.matches("Day: \\d{2}"), "Day should be zero-padded");
}
}
@Nested
@DisplayName("Custom Date Format Tests")
class CustomDateFormatTests {
@Test
@DisplayName("Should handle custom date format dd/MM/yyyy")
void testCustomDateFormatSlash() throws Exception {
String result = invokeProcessStampText("@date{dd/MM/yyyy}", 1, 1, "test.pdf", null);
assertTrue(
result.matches("\\d{2}/\\d{2}/\\d{4}"),
"Should match dd/MM/yyyy format: " + result);
}
@Test
@DisplayName("Should handle custom date format with time")
void testCustomDateFormatWithTime() throws Exception {
String result =
invokeProcessStampText("@date{yyyy-MM-dd HH:mm}", 1, 1, "test.pdf", null);
assertTrue(
result.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}"),
"Should match yyyy-MM-dd HH:mm format: " + result);
}
@Test
@DisplayName("Should handle multiple custom date formats in same text")
void testMultipleCustomDateFormats() throws Exception {
String result =
invokeProcessStampText(
"Start: @date{dd/MM/yyyy} End: @date{yyyy}", 1, 1, "test.pdf", null);
assertTrue(result.contains("/"), "Should contain slash from first format");
// Should have year twice (once with slashes, once alone)
}
}
@Nested
@DisplayName("Custom Date Format Security Tests")
class CustomDateFormatSecurityTests {
@Test
@DisplayName("Should not match format that is too long - regex won't capture it")
void testFormatTooLong() throws Exception {
String longFormat = "y".repeat(51); // 51 chars, over the 50 char regex limit
String result =
invokeProcessStampText("@date{" + longFormat + "}", 1, 1, "test.pdf", null);
// The CUSTOM_DATE_PATTERN only captures up to 50 chars, so this won't match
// The @date part will be replaced by simple replacement, leaving {yyy...}
assertTrue(
result.contains("{"), "Should contain { because regex didn't match: " + result);
}
@Test
@DisplayName("Should reject format with unsafe characters - shell injection attempt")
void testShellInjectionAttempt() throws Exception {
String result =
invokeProcessStampText("@date{yyyy-MM-dd$(rm -rf /)}", 1, 1, "test.pdf", null);
assertEquals("[invalid format]", result);
}
@Test
@DisplayName("Should reject format with unsafe characters - semicolon")
void testSemicolonInjection() throws Exception {
String result = invokeProcessStampText("@date{yyyy;rm}", 1, 1, "test.pdf", null);
assertEquals("[invalid format]", result);
}
@Test
@DisplayName("Should reject format with unsafe characters - backticks")
void testBacktickInjection() throws Exception {
String result = invokeProcessStampText("@date{`whoami`}", 1, 1, "test.pdf", null);
assertEquals("[invalid format]", result);
}
@ParameterizedTest
@ValueSource(strings = {"$(cmd)", "`cmd`", ";cmd", "|cmd", "&cmd", "<cmd", ">cmd"})
@DisplayName("Should reject various injection attempts")
void testVariousInjectionAttempts(String injection) throws Exception {
String result =
invokeProcessStampText("@date{yyyy" + injection + "}", 1, 1, "test.pdf", null);
assertEquals("[invalid format]", result);
}
@Test
@DisplayName("Should accept valid format characters")
void testValidFormatCharacters() throws Exception {
// All these should be valid based on SAFE_DATE_FORMAT_PATTERN: yMdHhmsS/-:.,
// '+EGuwWDFzZXa and space
String result =
invokeProcessStampText("@date{yyyy-MM-dd HH:mm:ss}", 1, 1, "test.pdf", null);
assertFalse(
result.startsWith("[invalid"), "Valid format should be accepted: " + result);
}
@Test
@DisplayName("Should handle invalid DateTimeFormatter pattern gracefully")
void testInvalidFormatterPattern() throws Exception {
LocalDateTime now = LocalDateTime.now();
// Use 'sssss' - too many seconds digits will throw IllegalArgumentException from
// DateTimeFormatter
// Note: The pattern 'sssss' passes the SAFE_DATE_FORMAT_PATTERN but fails
// DateTimeFormatter.ofPattern()
String result = invokeProcessCustomDateFormat("sssss", now);
assertTrue(
result.startsWith("[invalid format:"),
"Invalid pattern should return error message: " + result);
}
}
@Nested
@DisplayName("Escape Sequence Tests")
class EscapeSequenceTests {
@Test
@DisplayName("Should convert @@ to literal @")
void testDoubleAtEscape() throws Exception {
String result =
invokeProcessStampText("Email: test@@example.com", 1, 1, "test.pdf", null);
assertEquals("Email: test@example.com", result);
}
@Test
@DisplayName("Should preserve @@ before variable")
void testEscapeBeforeVariable() throws Exception {
String result = invokeProcessStampText("@@date is @date", 1, 1, "test.pdf", null);
// @@date should become @date, and @date should be replaced with actual date
assertTrue(result.startsWith("@date is "), "Should start with literal @date");
assertTrue(
result.matches("@date is \\d{4}-\\d{2}-\\d{2}"),
"Should have date after: " + result);
}
@Test
@DisplayName("Should handle multiple escape sequences")
void testMultipleEscapes() throws Exception {
String result = invokeProcessStampText("@@one @@two @@three", 1, 1, "test.pdf", null);
assertEquals("@one @two @three", result);
}
@Test
@DisplayName("Should handle escape at end of string")
void testEscapeAtEnd() throws Exception {
String result = invokeProcessStampText("Contact: user@@", 1, 1, "test.pdf", null);
assertEquals("Contact: user@", result);
}
}
@Nested
@DisplayName("Document Metadata Tests")
class DocumentMetadataTests {
@Test
@DisplayName("Should replace @author with document author")
void testAuthorReplacement() throws Exception {
PDDocument doc = new PDDocument();
PDDocumentInformation info = new PDDocumentInformation();
info.setAuthor("John Doe");
doc.setDocumentInformation(info);
try {
String result = invokeProcessStampText("Author: @author", 1, 1, "test.pdf", doc);
assertEquals("Author: John Doe", result);
} finally {
doc.close();
}
}
@Test
@DisplayName("Should replace @title with document title")
void testTitleReplacement() throws Exception {
PDDocument doc = new PDDocument();
PDDocumentInformation info = new PDDocumentInformation();
info.setTitle("My Document Title");
doc.setDocumentInformation(info);
try {
String result = invokeProcessStampText("Title: @title", 1, 1, "test.pdf", doc);
assertEquals("Title: My Document Title", result);
} finally {
doc.close();
}
}
@Test
@DisplayName("Should replace @subject with document subject")
void testSubjectReplacement() throws Exception {
PDDocument doc = new PDDocument();
PDDocumentInformation info = new PDDocumentInformation();
info.setSubject("Important Subject");
doc.setDocumentInformation(info);
try {
String result = invokeProcessStampText("Subject: @subject", 1, 1, "test.pdf", doc);
assertEquals("Subject: Important Subject", result);
} finally {
doc.close();
}
}
@Test
@DisplayName("Should handle null metadata gracefully")
void testNullMetadata() throws Exception {
PDDocument doc = new PDDocument();
// Don't set any document information
try {
String result =
invokeProcessStampText("@author @title @subject", 1, 1, "test.pdf", doc);
assertEquals(" ", result); // All should be empty strings
} finally {
doc.close();
}
}
@Test
@DisplayName("Should handle null document gracefully")
void testNullDocument() throws Exception {
String result = invokeProcessStampText("Author: @author", 1, 1, "test.pdf", null);
assertEquals("Author: ", result);
}
}
@Nested
@DisplayName("UUID Variable Tests")
class UuidTests {
@Test
@DisplayName("Should generate 8-character UUID")
void testUuidLength() throws Exception {
String result = invokeProcessStampText("ID: @uuid", 1, 1, "test.pdf", null);
// UUID format: "ID: " + 8 chars
assertEquals(12, result.length(), "Should be 'ID: ' + 8 char UUID");
}
@Test
@DisplayName("Should generate different UUIDs for each call")
void testUuidUniqueness() throws Exception {
String result1 = invokeProcessStampText("@uuid", 1, 1, "test.pdf", null);
String result2 = invokeProcessStampText("@uuid", 1, 1, "test.pdf", null);
assertNotEquals(result1, result2, "UUIDs should be unique");
}
@Test
@DisplayName("UUID should contain only hex characters")
void testUuidFormat() throws Exception {
String result = invokeProcessStampText("@uuid", 1, 1, "test.pdf", null);
assertTrue(result.matches("[0-9a-f]{8}"), "UUID should be 8 hex characters: " + result);
}
}
@Nested
@DisplayName("Edge Cases and Error Handling")
class EdgeCaseTests {
@Test
@DisplayName("Should handle null stamp text")
void testNullStampText() throws Exception {
String result = invokeProcessStampText(null, 1, 1, "test.pdf", null);
assertEquals("", result);
}
@Test
@DisplayName("Should handle empty stamp text")
void testEmptyStampText() throws Exception {
String result = invokeProcessStampText("", 1, 1, "test.pdf", null);
assertEquals("", result);
}
@Test
@DisplayName("Should handle text with no variables")
void testNoVariables() throws Exception {
String result = invokeProcessStampText("Just plain text", 1, 1, "test.pdf", null);
assertEquals("Just plain text", result);
}
@Test
@DisplayName("Should handle unknown variables")
void testUnknownVariable() throws Exception {
String result = invokeProcessStampText("@unknown_var", 1, 1, "test.pdf", null);
assertEquals("@unknown_var", result);
}
@Test
@DisplayName("Should preserve text around variables")
void testPreservesSurroundingText() throws Exception {
String result =
invokeProcessStampText("Before @page_number After", 5, 10, "test.pdf", null);
assertEquals("Before 5 After", result);
}
@Test
@DisplayName("Should handle multiple same variables")
void testMultipleSameVariables() throws Exception {
String result =
invokeProcessStampText("@page_number / @page_number", 3, 10, "test.pdf", null);
assertEquals("3 / 3", result);
}
@Test
@DisplayName("Should handle variables adjacent to each other")
void testAdjacentVariables() throws Exception {
String result = invokeProcessStampText("@page@page_number", 5, 10, "test.pdf", null);
// @page should be replaced first (it's in the order), then @page_number
// Since @page_number is longer and comes first in replace chain, should work
assertEquals("55", result);
}
}
@Nested
@DisplayName("Complex Scenario Tests")
class ComplexScenarioTests {
@Test
@DisplayName("Should handle legal footer template")
void testLegalFooterTemplate() throws Exception {
String template = "© @year - All Rights Reserved\\n@filename - Page @page_number";
String result = invokeProcessStampText(template, 3, 15, "contract.pdf", null);
int year = LocalDateTime.now().getYear();
String expected = "© " + year + " - All Rights Reserved\\ncontract - Page 3";
assertEquals(expected, result);
}
@Test
@DisplayName("Should handle Brazilian date format template")
void testBrazilianDateFormat() throws Exception {
String template = "Documento criado em @date{dd/MM/yyyy} às @time";
String result = invokeProcessStampText(template, 1, 1, "doc.pdf", null);
assertTrue(result.startsWith("Documento criado em "));
assertTrue(result.contains("/"));
assertTrue(result.contains(":"));
}
@ParameterizedTest
@CsvSource({
"'Page @page_number of @total_pages', 1, 10, 'Page 1 of 10'",
"'Page @page_number of @total_pages', 5, 20, 'Page 5 of 20'",
"'Page @page_number of @total_pages', 100, 1000, 'Page 100 of 1000'"
})
@DisplayName("Should handle page number template with various values")
void testPageNumberTemplates(String template, int page, int total, String expected)
throws Exception {
String result = invokeProcessStampText(template, page, total, "test.pdf", null);
assertEquals(expected, result);
}
}
}
@@ -210,7 +210,10 @@ public class ProprietaryUIDataController {
SAML2 saml2 = securityProps.getSaml2();
// Only add SAML2 providers if loginMethod allows it
if (securityProps.isSaml2Active() && applicationProperties.getPremium().isEnabled()) {
String samlIdp = saml2.getProvider();
String samlIdp =
saml2.getProvider().getEntityId() != null
? saml2.getProvider().getEntityId()
: saml2.getIdpIssuer(); // legacy fallback
String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId();
// For SAML, we need to use the backend URL directly, not a relative path
@@ -33,7 +33,8 @@ public class PersistentAuditEvent {
private String principal;
private String type;
@Lob private String data; // JSON blob
@Column(columnDefinition = "text")
private String data; // JSON blob
private Instant timestamp;
}
@@ -1,53 +1,58 @@
package stirling.software.proprietary.security;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import org.springframework.core.io.Resource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import com.coveo.saml.SamlClient;
import com.coveo.saml.SamlException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.configuration.AppConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.ApplicationProperties.Security.OAUTH2;
import stirling.software.common.model.ApplicationProperties.Security.SAML2;
import stirling.software.common.model.oauth2.KeycloakProvider;
import stirling.software.common.util.RegexPatternUtils;
import stirling.software.common.util.UrlUtils;
import stirling.software.proprietary.audit.AuditEventType;
import stirling.software.proprietary.audit.AuditLevel;
import stirling.software.proprietary.audit.Audited;
import stirling.software.proprietary.security.saml2.CertificateUtils;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.JwtServiceInterface;
@Slf4j
@RequiredArgsConstructor
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
public static final String LOGOUT_PATH = "/login?logout=true";
private final ApplicationProperties.Security securityProperties;
private final AppConfig appConfig;
private final JwtServiceInterface jwtService;
private final LogoutSuccessHandler samlLogoutHandler;
public CustomLogoutSuccessHandler(
ApplicationProperties.Security securityProperties, JwtServiceInterface jwtService) {
this(securityProperties, jwtService, null);
}
public CustomLogoutSuccessHandler(
ApplicationProperties.Security securityProperties,
JwtServiceInterface jwtService,
LogoutSuccessHandler samlLogoutHandler) {
this.securityProperties = securityProperties;
this.jwtService = jwtService;
this.samlLogoutHandler = samlLogoutHandler;
}
@Override
@Audited(type = AuditEventType.USER_LOGOUT, level = AuditLevel.BASIC)
@@ -56,13 +61,14 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
throws IOException {
if (!response.isCommitted()) {
if (handleSamlLogout(request, response, authentication)) {
return;
}
if (authentication != null) {
if (authentication instanceof Saml2Authentication samlAuthentication) {
// Handle SAML2 logout redirection
getRedirect_saml2(request, response, samlAuthentication);
} else if (authentication instanceof OAuth2AuthenticationToken oAuthToken) {
if (authentication instanceof OAuth2AuthenticationToken oAuthToken) {
// Handle OAuth2 logout redirection
getRedirect_oauth2(request, response, oAuthToken);
getRedirectOauth2(request, response, oAuthToken);
} else if (authentication instanceof UsernamePasswordAuthenticationToken) {
// Handle Username/Password logout
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
@@ -74,71 +80,152 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
}
} else {
if (jwtService != null) {
String token = jwtService.extractToken(request);
if (token != null && !token.isBlank()) {
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
return;
}
}
// Redirect to login page after logout
String path = checkForErrors(request);
getRedirectStrategy().sendRedirect(request, response, path);
// Redirect to login page after logout (handles error parameters if present)
String queryParams = checkForErrors(request);
getRedirectStrategy().sendRedirect(request, response, "/login?" + queryParams);
}
}
}
// Redirect for SAML2 authentication logout
private void getRedirect_saml2(
HttpServletRequest request,
HttpServletResponse response,
Saml2Authentication samlAuthentication)
/**
* Handles SAML logout - either via IdP Single Logout (SLO) or local logout.
*
* @return true if this was a SAML user and logout was handled, false otherwise
*/
private boolean handleSamlLogout(
HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
// Logout locally if this is a SAMLResponse from to /logout instead of /logout/saml2/slo
String samlResponse = request.getParameter("SAMLResponse");
if (samlResponse != null && !samlResponse.isBlank()) {
if (samlResponse.contains("/saml2/slo")) {
log.info(
"Received SAML LogoutResponse at /logout endpoint, completing logout locally");
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
return true;
}
}
SAML2 samlConf = securityProperties.getSaml2();
String registrationId = samlConf.getRegistrationId();
if (securityProperties.getSaml2().getEnableSingleLogout()) {
log.info("SP-initiated SLO detected, logging out via IdP");
CustomSaml2AuthenticatedPrincipal principal =
(CustomSaml2AuthenticatedPrincipal) samlAuthentication.getPrincipal();
if (authentication instanceof Saml2Authentication samlAuthentication) {
if (samlLogoutHandler != null) {
try {
samlLogoutHandler.onLogoutSuccess(request, response, samlAuthentication);
} catch (Exception e) {
log.error("SP-initiated SLO failed, falling back to local logout", e);
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
}
} else {
log.warn(
"SAML SLO enabled but handler not configured, performing local logout only");
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
}
String nameIdValue = principal.name();
return true;
} else {
// Reconstruct Saml2Authentication from JWT claims for SLO
Optional<Saml2Authentication> reconstructedAuth =
reconstructSaml2AuthenticationFromJwt(request);
if (reconstructedAuth.isPresent()) {
Saml2Authentication samlAuth = reconstructedAuth.get();
if (samlLogoutHandler != null) {
try {
samlLogoutHandler.onLogoutSuccess(request, response, samlAuth);
} catch (Exception e) {
log.error("SP-initiated SLO failed, falling back to local logout", e);
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
}
} else {
log.warn(
"SAML SLO enabled but handler not configured, performing local logout only");
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
}
return true;
}
}
}
return false;
}
/**
* Reconstructs a Saml2Authentication from JWT claims for SAML Single Logout. This allows SLO to
* work even with stateless JWT sessions by extracting the SAML attributes that were stored in
* the JWT during initial authentication.
*/
@SuppressWarnings("unchecked")
private Optional<Saml2Authentication> reconstructSaml2AuthenticationFromJwt(
HttpServletRequest request) {
try {
// Read certificate from the resource
Resource certificateResource = samlConf.getSpCert();
X509Certificate certificate = CertificateUtils.readCertificate(certificateResource);
String token = jwtService.extractToken(request);
if (token == null || token.isBlank()) {
return Optional.empty();
}
List<X509Certificate> certificates = new ArrayList<>();
certificates.add(certificate);
Map<String, Object> claims = jwtService.extractClaims(token);
Object authType = claims.get("authType");
// Construct URLs required for SAML configuration
SamlClient samlClient = getSamlClient(registrationId, samlConf, certificates);
if (authType == null || !"SAML2".equalsIgnoreCase(authType.toString())) {
return Optional.empty();
}
// Read private key for service provider
Resource privateKeyResource = samlConf.getPrivateKey();
RSAPrivateKey privateKey = CertificateUtils.readPrivateKey(privateKeyResource);
// Extract SAML claims from JWT
String username = (String) claims.get("sub");
String nameId = (String) claims.get("samlNameId");
String registrationId = (String) claims.get("samlRegistrationId");
Object sessionIndexesObj = claims.get("samlSessionIndexes");
// Set service provider keys for the SamlClient
samlClient.setSPKeys(certificate, privateKey);
if (nameId == null || registrationId == null) {
log.debug(
"Missing required SAML claims for SLO reconstruction: nameId={}, registrationId={}",
nameId,
registrationId);
return Optional.empty();
}
// Build relay state to return user to login page after IdP logout
String relayState =
UrlUtils.getOrigin(request) + request.getContextPath() + LOGOUT_PATH;
List<String> sessionIndexes = Collections.emptyList();
if (sessionIndexesObj instanceof List<?>) {
sessionIndexes =
((List<?>) sessionIndexesObj).stream().map(Object::toString).toList();
}
// Redirect to identity provider for logout with relay state
samlClient.redirectToIdentityProvider(response, relayState, nameIdValue);
} catch (Exception e) {
log.error(
"Error retrieving logout URL from Provider {} for user {}",
samlConf.getProvider(),
nameIdValue,
e);
getRedirectStrategy().sendRedirect(request, response, LOGOUT_PATH);
// Create principal with all SAML attributes needed for SLO
CustomSaml2AuthenticatedPrincipal principal =
new CustomSaml2AuthenticatedPrincipal(
username,
Collections.emptyMap(), // Attributes not needed for logout
nameId,
sessionIndexes,
registrationId);
// Create Saml2Authentication with the reconstructed principal
// The saml2Response parameter is not used by the logout handler, but constructor
// requires non-empty value, so we provide a placeholder
Saml2Authentication samlAuth =
new Saml2Authentication(
principal,
"<!-- reconstructed for logout -->",
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
log.debug(
"Reconstructed Saml2Authentication from JWT for user {} with registrationId {}",
username,
registrationId);
return Optional.of(samlAuth);
} catch (Exception ex) {
log.error("Unable to reconstruct Saml2Authentication from JWT", ex);
return Optional.empty();
}
}
// Redirect for OAuth2 authentication logout
private void getRedirect_oauth2(
private void getRedirectOauth2(
HttpServletRequest request,
HttpServletResponse response,
OAuth2AuthenticationToken oAuthToken)
@@ -169,7 +256,7 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
logoutUrl +=
"/protocol/openid-connect/logout"
+ "?client_id="
+ oauth.getClientId()
+ keycloak.getClientId()
+ "&post_logout_redirect_uri="
+ response.encodeRedirectURL(redirectUrl);
log.info("Redirecting to Keycloak logout URL: {}", logoutUrl);
@@ -196,30 +283,6 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
}
}
private SamlClient getSamlClient(
String registrationId, SAML2 samlConf, List<X509Certificate> certificates)
throws SamlException {
String serverUrl = appConfig.getBackendUrl() + ":" + appConfig.getServerPort();
String relyingPartyIdentifier =
serverUrl + "/saml2/service-provider-metadata/" + registrationId;
String assertionConsumerServiceUrl = serverUrl + "/login/saml2/sso/" + registrationId;
String idpSLOUrl = samlConf.getIdpSingleLogoutUrl();
String idpIssuer = samlConf.getIdpIssuer();
// Create SamlClient instance for SAML logout
return new SamlClient(
relyingPartyIdentifier,
assertionConsumerServiceUrl,
idpSLOUrl,
idpIssuer,
certificates,
SamlClient.SamlIdpBinding.POST);
}
/**
* Handles different error scenarios during logout. Will return a <code>String</code> containing
* the error request parameter.
@@ -8,11 +8,13 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
@@ -22,8 +24,12 @@ import org.springframework.security.oauth2.client.registration.ClientRegistratio
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutRequestResolver;
import org.springframework.security.saml2.provider.service.web.authentication.logout.Saml2RelyingPartyInitiatedLogoutSuccessHandler;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.savedrequest.NullRequestCache;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
@@ -33,7 +39,6 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.configuration.AppConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.RequestUriUtils;
import stirling.software.proprietary.security.CustomAuthenticationFailureHandler;
@@ -56,7 +61,6 @@ import stirling.software.proprietary.security.service.CustomUserDetailsService;
import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@Slf4j
@Configuration
@@ -72,12 +76,10 @@ public class SecurityConfiguration {
private final ApplicationProperties applicationProperties;
private final ApplicationProperties.Security securityProperties;
private final AppConfig appConfig;
private final UserAuthenticationFilter userAuthenticationFilter;
private final JwtServiceInterface jwtService;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final LoginAttemptService loginAttemptService;
private final SessionPersistentRegistry sessionRegistry;
private final PersistentLoginRepository persistentLoginRepository;
private final GrantedAuthoritiesMapper oAuth2userAuthoritiesMapper;
private final RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations;
@@ -92,14 +94,12 @@ public class SecurityConfiguration {
@Lazy UserService userService,
@Qualifier("loginEnabled") boolean loginEnabledValue,
@Qualifier("runningProOrHigher") boolean runningProOrHigher,
AppConfig appConfig,
ApplicationProperties applicationProperties,
ApplicationProperties.Security securityProperties,
UserAuthenticationFilter userAuthenticationFilter,
JwtServiceInterface jwtService,
JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint,
LoginAttemptService loginAttemptService,
SessionPersistentRegistry sessionRegistry,
@Autowired(required = false) GrantedAuthoritiesMapper oAuth2userAuthoritiesMapper,
@Autowired(required = false)
RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations,
@@ -112,14 +112,12 @@ public class SecurityConfiguration {
this.userService = userService;
this.loginEnabledValue = loginEnabledValue;
this.runningProOrHigher = runningProOrHigher;
this.appConfig = appConfig;
this.applicationProperties = applicationProperties;
this.securityProperties = securityProperties;
this.userAuthenticationFilter = userAuthenticationFilter;
this.jwtService = jwtService;
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
this.loginAttemptService = loginAttemptService;
this.sessionRegistry = sessionRegistry;
this.persistentLoginRepository = persistentLoginRepository;
this.oAuth2userAuthoritiesMapper = oAuth2userAuthoritiesMapper;
this.saml2RelyingPartyRegistrations = saml2RelyingPartyRegistrations;
@@ -196,7 +194,7 @@ public class SecurityConfiguration {
http.cors(cors -> cors.configurationSource(corsSource));
} else {
// Explicitly disable CORS when no origins are configured
http.cors(cors -> cors.disable());
http.cors(AbstractHttpConfigurer::disable);
}
http.csrf(CsrfConfigurer::disable);
@@ -227,10 +225,10 @@ public class SecurityConfiguration {
if (loginEnabledValue) {
http.addFilterBefore(
userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(rateLimitingFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UserAuthenticationFilter.class);
http.addFilterBefore(rateLimitingFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, LogoutFilter.class)
.addFilterAfter(
userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
http.sessionManagement(
sessionManagement ->
@@ -250,17 +248,38 @@ public class SecurityConfiguration {
return requestURI.startsWith(contextPath + "/api/");
}));
// Create SAML logout handler if SAML SLO is enabled
final LogoutSuccessHandler samlLogoutHandler;
if (securityProperties.isSaml2Active()
&& Boolean.TRUE.equals(securityProperties.getSaml2().getEnableSingleLogout())
&& saml2RelyingPartyRegistrations != null) {
log.info("Creating SAML2 SLO handler for SP-initiated logout");
OpenSaml4LogoutRequestResolver logoutRequestResolver =
new OpenSaml4LogoutRequestResolver(saml2RelyingPartyRegistrations);
samlLogoutHandler =
new Saml2RelyingPartyInitiatedLogoutSuccessHandler(logoutRequestResolver);
} else {
samlLogoutHandler = null;
}
http.logout(
logout ->
// Require POST to prevent logout CSRF attacks
logout.logoutRequestMatcher(
PathPatternRequestMatcher.withDefaults()
.matcher("/logout"))
.matcher(HttpMethod.POST, "/logout"))
.logoutSuccessHandler(
new CustomLogoutSuccessHandler(
securityProperties, appConfig, jwtService))
securityProperties,
jwtService,
samlLogoutHandler))
.clearAuthentication(true)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID", "remember-me", "stirling_jwt"));
.deleteCookies(
"JSESSIONID",
"remember-me",
"stirling_jwt",
"stirling_logout_token"));
http.rememberMe(
rememberMeConfigurer -> // Use the configurator directly
rememberMeConfigurer
@@ -384,9 +403,18 @@ public class SecurityConfiguration {
}
})
.saml2Metadata(metadata -> {});
// Configure SAML2 Single Logout if enabled
// This sets up endpoints for:
// - IdP-initiated logout: IdP sends LogoutRequest to /logout/saml2/slo
// - SP-initiated logout response: IdP sends LogoutResponse to /logout/saml2/slo
if (Boolean.TRUE.equals(securityProperties.getSaml2().getEnableSingleLogout())) {
log.debug("SAML2 Single Logout (SLO) is enabled");
http.saml2Logout(logout -> logout.logoutUrl("/logout/saml2/slo"));
}
}
} else {
log.debug("Login is not enabled.");
log.info("Login is not enabled.");
http.authorizeHttpRequests(authz -> authz.anyRequest().permitAll());
}
return http.build();
@@ -231,29 +231,6 @@ public class AuthController {
}
}
/**
* Logout endpoint
*
* @param response HTTP response
* @return Success message
*/
@PreAuthorize("!hasAuthority('ROLE_DEMO_USER')")
@PostMapping("/logout")
public ResponseEntity<?> logout(HttpServletResponse response) {
try {
SecurityContextHolder.clearContext();
log.debug("User logged out successfully");
return ResponseEntity.ok(Map.of("message", "Logged out successfully"));
} catch (Exception e) {
log.error("Logout error", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Internal server error"));
}
}
/**
* Refresh token
*
@@ -61,6 +61,11 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
String requestURI = request.getRequestURI();
String contextPath = request.getContextPath();
if (isPublicAuthEndpoint(requestURI, contextPath)) {
filterChain.doFilter(request, response);
return;
}
if (isStaticResource(contextPath, requestURI)) {
filterChain.doFilter(request, response);
return;
@@ -174,7 +179,11 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
userDetails, null, userDetails.getAuthorities());
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
log.debug("Setting authentication for user: {}", username);
SecurityContextHolder.getContext().setAuthentication(authToken);
log.debug(
"Authentication set successfully: {}",
SecurityContextHolder.getContext().getAuthentication());
} else {
throw new UsernameNotFoundException("User not found: " + username);
}
@@ -0,0 +1,64 @@
package stirling.software.proprietary.security.filter;
import java.io.IOException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
/**
* Filter that redirects browser requests to /login to the frontend URL when configured. This is
* needed for development mode where frontend runs on a different port, and for SAML logout which
* redirects to /login?logout after SLO completes.
*/
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class LoginRedirectFilter extends OncePerRequestFilter {
private final ApplicationProperties applicationProperties;
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String path = request.getRequestURI();
String frontendUrl = applicationProperties.getSystem().getFrontendUrl();
// Only process /login requests when frontendUrl is configured
if (path.equals("/login") && frontendUrl != null && !frontendUrl.isBlank()) {
// Check if this is a browser request (Accept: text/html) vs API request
// (Accept: application/json)
String acceptHeader = request.getHeader("Accept");
boolean isBrowserRequest =
acceptHeader != null
&& acceptHeader.contains("text/html")
&& !acceptHeader.contains("application/json");
if (isBrowserRequest) {
// Preserve query parameters (e.g., ?logout=true, ?error=xxx)
String queryString = request.getQueryString();
String redirectUrl =
frontendUrl + "/login" + (queryString != null ? "?" + queryString : "");
log.debug("Redirecting browser request to frontend: {}", redirectUrl);
response.sendRedirect(redirectUrl);
return;
}
}
filterChain.doFilter(request, response);
}
}
@@ -4,6 +4,7 @@ import static stirling.software.common.util.RequestUriUtils.isPublicAuthEndpoint
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -32,6 +33,7 @@ import stirling.software.common.util.RequestUriUtils;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
@@ -43,16 +45,19 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
private final UserService userService;
private final SessionPersistentRegistry sessionPersistentRegistry;
private final boolean loginEnabledValue;
private final JwtServiceInterface jwtService;
public UserAuthenticationFilter(
@Lazy ApplicationProperties.Security securityProp,
@Lazy UserService userService,
SessionPersistentRegistry sessionPersistentRegistry,
@Qualifier("loginEnabled") boolean loginEnabledValue) {
@Qualifier("loginEnabled") boolean loginEnabledValue,
@Lazy JwtServiceInterface jwtService) {
this.securityProp = securityProp;
this.userService = userService;
this.sessionPersistentRegistry = sessionPersistentRegistry;
this.loginEnabledValue = loginEnabledValue;
this.jwtService = jwtService;
}
@Override
@@ -135,7 +140,7 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
}
// Check if the authenticated user is disabled and invalidate their session if so
if (authentication != null && authentication.isAuthenticated()) {
if (authentication.isAuthenticated()) {
UserLoginType loginMethod = UserLoginType.UNKNOWN;
@@ -146,7 +151,14 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
String username = null;
if (principal instanceof UserDetails detailsUser) {
username = detailsUser.getUsername();
loginMethod = UserLoginType.USERDETAILS;
loginMethod = resolveLoginTypeFromJwt(request);
if (loginMethod == UserLoginType.SAML2USER) {
SAML2 saml2 = securityProp.getSaml2();
blockRegistration = saml2 != null && saml2.getBlockRegistration();
} else if (loginMethod == UserLoginType.OAUTH2USER) {
OAUTH2 oAuth = securityProp.getOauth2();
blockRegistration = oAuth != null && oAuth.getBlockRegistration();
}
} else if (principal instanceof OAuth2User oAuth2User) {
username = oAuth2User.getName();
loginMethod = UserLoginType.OAUTH2USER;
@@ -241,6 +253,30 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response);
}
private UserLoginType resolveLoginTypeFromJwt(HttpServletRequest request) {
if (jwtService == null) {
return UserLoginType.USERDETAILS;
}
try {
String token = jwtService.extractToken(request);
if (token != null && !token.isBlank()) {
Map<String, Object> claims = jwtService.extractClaims(token);
Object authType = claims.get("authType");
if (authType != null) {
String type = authType.toString().toUpperCase();
if ("SAML2".equals(type)) {
return UserLoginType.SAML2USER;
} else if ("OAUTH2".equals(type)) {
return UserLoginType.OAUTH2USER;
}
}
}
} catch (Exception e) {
log.debug("Unable to resolve login type from JWT claims", e);
}
return UserLoginType.USERDETAILS;
}
private enum UserLoginType {
USERDETAILS("UserDetails"),
OAUTH2USER("OAuth2User"),
@@ -87,7 +87,6 @@ public class User implements UserDetails, Serializable {
@ElementCollection
@MapKeyColumn(name = "setting_key")
@Lob
@Column(name = "setting_value", columnDefinition = "text")
@CollectionTable(name = "user_settings", joinColumns = @JoinColumn(name = "user_id"))
@JsonIgnore
@@ -53,9 +53,6 @@ public class OAuth2Configuration {
ApplicationProperties applicationProperties, @Lazy UserService userService) {
this.userService = userService;
this.applicationProperties = applicationProperties;
log.info(
"OAuth2Configuration initialized - OAuth2 enabled: {}",
applicationProperties.getSecurity().getOauth2().getEnabled());
}
@Bean
@@ -222,8 +219,6 @@ public class OAuth2Configuration {
name,
oauth.getIssuer(),
REDIRECT_URI_PATH + name);
} else {
log.warn("OIDC OAuth2 provider validation failed - provider will not be registered");
}
return isValid
@@ -12,9 +12,22 @@ public record CustomSaml2AuthenticatedPrincipal(
String name,
Map<String, List<Object>> attributes,
String nameId,
List<String> sessionIndexes)
List<String> sessionIndexes,
String relyingPartyRegistrationId)
implements Saml2AuthenticatedPrincipal, Serializable {
/**
* Constructor without relyingPartyRegistrationId for backwards compatibility. Sets
* relyingPartyRegistrationId to null.
*/
public CustomSaml2AuthenticatedPrincipal(
String name,
Map<String, List<Object>> attributes,
String nameId,
List<String> sessionIndexes) {
this(name, attributes, nameId, sessionIndexes, null);
}
@Override
public String getName() {
return this.name;
@@ -24,4 +37,14 @@ public record CustomSaml2AuthenticatedPrincipal(
public Map<String, List<Object>> getAttributes() {
return this.attributes;
}
@Override
public List<String> getSessionIndexes() {
return this.sessionIndexes;
}
@Override
public String getRelyingPartyRegistrationId() {
return this.relyingPartyRegistrationId;
}
}
@@ -7,6 +7,8 @@ import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -33,6 +35,7 @@ import stirling.software.proprietary.audit.AuditEventType;
import stirling.software.proprietary.audit.AuditLevel;
import stirling.software.proprietary.audit.Audited;
import stirling.software.proprietary.security.model.AuthenticationType;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.UserService;
@@ -70,8 +73,7 @@ public class CustomSaml2AuthenticationSuccessHandler
// Check if user is eligible for SAML (grandfathered or system has ENTERPRISE license)
if (userExists) {
stirling.software.proprietary.security.model.User user =
userService.findByUsernameIgnoreCase(username).orElse(null);
User user = userService.findByUsernameIgnoreCase(username).orElse(null);
if (user != null && !licenseSettingsService.isSamlEligible(user)) {
// User is not grandfathered and no ENTERPRISE license - block SAML login
@@ -172,7 +174,11 @@ public class CustomSaml2AuthenticationSuccessHandler
// Extract SSO provider information from SAML2 assertion
String ssoProviderId = saml2Principal.nameId();
String ssoProvider = "saml2"; // fixme
String ssoProvider =
(saml2Properties.getIdpIssuer() != null
&& !saml2Properties.getIdpIssuer().isBlank())
? saml2Properties.getIdpIssuer()
: saml2Properties.getRegistrationId();
log.debug(
"Processing SSO post-login for user: {} (Provider: {}, ProviderId: {})",
@@ -188,12 +194,21 @@ public class CustomSaml2AuthenticationSuccessHandler
SAML2);
log.debug("Successfully processed authentication for user: {}", username);
// Generate JWT if v2 is enabled
if (jwtService.isJwtEnabled()) {
String jwt =
jwtService.generateToken(
authentication,
Map.of("authType", AuthenticationType.SAML2));
Map<String, Object> claims = new HashMap<>();
claims.put("authType", AuthenticationType.SAML2);
claims.put("samlNameId", saml2Principal.nameId());
List<String> sessionIndexes = saml2Principal.sessionIndexes();
if (sessionIndexes != null && !sessionIndexes.isEmpty()) {
claims.put("samlSessionIndexes", sessionIndexes);
}
if (ssoProvider != null) {
claims.put("samlProvider", ssoProvider);
}
if (saml2Properties.getRegistrationId() != null) {
claims.put("samlRegistrationId", saml2Properties.getRegistrationId());
}
String jwt = jwtService.generateToken(authentication, claims);
// Build context-aware redirect URL based on the original request
String redirectUrl =
@@ -94,7 +94,7 @@ public class JwtSaml2AuthenticationRequestRepository
if (token != null) {
tokenStore.remove(authnRequestId);
log.debug("Retrieved SAMLRequest token for RelayState ID: {}", authnRequestId);
log.info("Retrieved SAMLRequest token for RelayState ID: {}", authnRequestId);
return token;
} else {
log.warn("No SAMLRequest token found for RelayState ID: {}", authnRequestId);
@@ -1,9 +1,22 @@
package stirling.software.proprietary.security.saml2;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.opensaml.saml.saml2.core.AuthnRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -19,6 +32,10 @@ import org.springframework.security.saml2.provider.service.registration.RelyingP
import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding;
import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository;
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import jakarta.servlet.http.HttpServletRequest;
@@ -27,6 +44,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.ApplicationProperties.Security.SAML2;
import stirling.software.common.util.GeneralUtils;
import stirling.software.proprietary.security.service.JwtServiceInterface;
@Configuration
@@ -35,45 +53,34 @@ import stirling.software.proprietary.security.service.JwtServiceInterface;
@RequiredArgsConstructor
public class Saml2Configuration {
private static final String SAML_METADATA_NS = "urn:oasis:names:tc:SAML:2.0:metadata";
private static final String XML_DSIG_NS = "http://www.w3.org/2000/09/xmldsig#";
private final ApplicationProperties applicationProperties;
@Bean
@ConditionalOnProperty(name = "security.saml2.enabled", havingValue = "true")
public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception {
public RelyingPartyRegistrationRepository relyingPartyRegistrations() {
SAML2 samlConf = applicationProperties.getSecurity().getSaml2();
Optional<IdpMetadataInfo> metadataInfo = loadIdpMetadata(samlConf);
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);
}
// Load IdP certificate either from metadata or fallback resource
X509Certificate idpCert =
metadataInfo
.map(IdpMetadataInfo::signingCertificate)
.orElseGet(() -> loadIdpCertificateFromResource(samlConf));
Saml2X509Credential verificationCredential = Saml2X509Credential.verification(idpCert);
// Load SP private key and certificate
Resource privateKeyResource = samlConf.getPrivateKey();
Resource certificateResource = samlConf.getSpCert();
Resource privateKeyResource = samlConf.getSp().getPrivateKeyResource();
Resource certificateResource = samlConf.getSp().getCertResource();
log.info("Loading SP private key from: {}", privateKeyResource.getDescription());
log.debug("Loading SP private key from: {}", privateKeyResource.getDescription());
if (!privateKeyResource.exists()) {
log.error("SAML2 SP private key not found at: {}", privateKeyResource.getDescription());
throw new IllegalStateException(
@@ -81,7 +88,7 @@ public class Saml2Configuration {
+ privateKeyResource.getDescription());
}
log.info("Loading SP certificate from: {}", certificateResource.getDescription());
log.debug("Loading SP certificate from: {}", certificateResource.getDescription());
if (!certificateResource.exists()) {
log.error(
"SAML2 SP certificate not found at: {}", certificateResource.getDescription());
@@ -102,6 +109,43 @@ public class Saml2Configuration {
log.error("Failed to load SAML2 SP credentials: {}", e.getMessage(), e);
throw new IllegalStateException("Failed to load SAML2 SP credentials", e);
}
// Apply metadata overrides - metadata takes precedence over manual config
metadataInfo.ifPresent(info -> applyMetadataOverrides(samlConf, info));
// Get IdP configuration - prefer values from metadata, fall back to manual config
String idpEntityId =
metadataInfo
.map(IdpMetadataInfo::entityId)
.filter(id -> id != null && !id.isBlank())
.orElseGet(() -> samlConf.getProvider().getEntityId());
String idpSingleLoginUrl =
metadataInfo
.map(IdpMetadataInfo::singleSignOnServiceUrl)
.filter(url -> url != null && !url.isBlank())
.orElseGet(() -> samlConf.getProvider().getSingleLoginUrl());
String idpSingleLogoutUrl =
metadataInfo
.map(IdpMetadataInfo::singleLogoutServiceUrl)
.filter(url -> url != null && !url.isBlank())
.orElseGet(() -> samlConf.getProvider().getSingleLogoutUrl());
// Validate required IdP configuration
if (idpEntityId == null || idpEntityId.isBlank()) {
throw new IllegalStateException(
"SAML2 IdP Entity ID is required. Set security.saml2.entityId or provide security.saml2.metadataUri");
}
if (idpSingleLoginUrl == null || idpSingleLoginUrl.isBlank()) {
throw new IllegalStateException(
"SAML2 IdP Single Sign-On URL is required. Set security.saml2.provider.singleLoginUrl or provide security.saml2.metadataUri");
}
log.info(
"SAML2 IdP configuration: entityId={}, ssoUrl={}, sloUrl={}",
idpEntityId,
idpSingleLoginUrl,
idpSingleLogoutUrl);
// Get backend URL from configuration (for SAML endpoints)
String backendUrl = applicationProperties.getSystem().getBackendUrl();
@@ -116,40 +160,38 @@ public class Saml2Configuration {
String entityId =
backendUrl + "/saml2/service-provider-metadata/" + samlConf.getRegistrationId();
String acsLocation = backendUrl + "/login/saml2/sso/{registrationId}";
String sloResponseLocation = backendUrl + "/login";
// SP's Single Logout Service endpoint (where SP receives logout requests/responses from
// IdP)
String spSloLocation = backendUrl + "/logout/saml2/slo";
RelyingPartyRegistration rp =
RelyingPartyRegistration.withRegistrationId(samlConf.getRegistrationId())
.signingX509Credentials(c -> c.add(signingCredential))
.entityId(entityId)
.singleLogoutServiceBinding(Saml2MessageBinding.POST)
.singleLogoutServiceLocation(samlConf.getIdpSingleLogoutUrl())
.singleLogoutServiceResponseLocation(sloResponseLocation)
.singleLogoutServiceLocation(spSloLocation)
.singleLogoutServiceResponseLocation(spSloLocation)
.assertionConsumerServiceBinding(Saml2MessageBinding.POST)
.assertionConsumerServiceLocation(acsLocation)
.authnRequestsSigned(true)
.assertingPartyMetadata(
metadata ->
metadata.entityId(samlConf.getIdpIssuer())
metadata.entityId(idpEntityId)
.verificationX509Credentials(
c -> c.add(verificationCredential))
.singleSignOnServiceBinding(
Saml2MessageBinding.POST)
.singleSignOnServiceLocation(
samlConf.getIdpSingleLoginUrl())
.singleSignOnServiceLocation(idpSingleLoginUrl)
.singleLogoutServiceBinding(
Saml2MessageBinding.POST)
.singleLogoutServiceLocation(
samlConf.getIdpSingleLogoutUrl())
.singleLogoutServiceResponseLocation(
sloResponseLocation)
.singleLogoutServiceLocation(idpSingleLogoutUrl)
.wantAuthnRequestsSigned(true))
.build();
log.info(
"SAML2 configuration initialized successfully. Registration ID: {}, IdP: {}",
samlConf.getRegistrationId(),
samlConf.getIdpIssuer());
idpEntityId);
return new InMemoryRelyingPartyRegistrationRepository(rp);
}
@@ -206,6 +248,212 @@ public class Saml2Configuration {
return resolver;
}
private X509Certificate loadIdpCertificateFromResource(SAML2 samlConf) {
try {
Resource idpCertResource = samlConf.getProvider().getCertResource();
if (idpCertResource == null) {
throw new IllegalStateException("SAML2 IdP certificate resource is not defined");
}
log.info("Loading IdP certificate from: {}", idpCertResource.getDescription());
if (!idpCertResource.exists()) {
throw new IllegalStateException(
"SAML2 IdP certificate file does not exist: "
+ idpCertResource.getDescription());
}
X509Certificate certificate = CertificateUtils.readCertificate(idpCertResource);
log.info(
"Successfully loaded IdP certificate. Subject: {}",
certificate.getSubjectX500Principal().getName());
return certificate;
} catch (Exception e) {
log.error("Failed to load SAML2 IdP certificate: {}", e.getMessage(), e);
throw new IllegalStateException("Failed to load SAML2 IdP certificate", e);
}
}
private void applyMetadataOverrides(SAML2 samlConf, IdpMetadataInfo metadataInfo) {
log.info(
"Applying IdP metadata overrides for registration: {}",
samlConf.getRegistrationId());
SAML2.Provider provider = samlConf.getProvider();
overrideIfPresent(metadataInfo.entityId(), provider::setEntityId);
overrideIfPresent(metadataInfo.singleSignOnServiceUrl(), provider::setSingleLoginUrl);
overrideIfPresent(metadataInfo.singleLogoutServiceUrl(), provider::setSingleLogoutUrl);
// Persist discovered metadata values to settings.yml
persistMetadataToSettings(metadataInfo);
}
/**
* Persists IdP metadata discovered values to settings.yml. This ensures the discovered
* configuration is saved for future reference and survives restarts even if the metadata
* endpoint becomes unavailable.
*/
private void persistMetadataToSettings(IdpMetadataInfo metadataInfo) {
log.info(
"Migrating discovered IdP metadata to SAML configuration. Existing configuration will be overridden.");
try {
boolean anyPersisted = false;
if (hasText(metadataInfo.entityId())) {
GeneralUtils.saveKeyToSettings(
"security.saml2.provider.entityId", metadataInfo.entityId());
log.info(" -> Persisted provider.entityId: {}", metadataInfo.entityId());
anyPersisted = true;
}
if (hasText(metadataInfo.singleSignOnServiceUrl())) {
GeneralUtils.saveKeyToSettings(
"security.saml2.provider.singleLoginUrl",
metadataInfo.singleSignOnServiceUrl());
log.info(
" -> Persisted provider.singleLoginUrl: {}",
metadataInfo.singleSignOnServiceUrl());
anyPersisted = true;
}
if (hasText(metadataInfo.singleLogoutServiceUrl())) {
GeneralUtils.saveKeyToSettings(
"security.saml2.provider.singleLogoutUrl",
metadataInfo.singleLogoutServiceUrl());
log.info(
" -> Persisted provider.singleLogoutUrl: {}",
metadataInfo.singleLogoutServiceUrl());
anyPersisted = true;
}
if (anyPersisted) {
log.info(
"IdP metadata successfully persisted to settings.yml. These values will be used as fallback if metadataUri becomes unavailable.");
}
} catch (Exception e) {
log.warn(
"Failed to persist IdP metadata to settings.yml: {}. SAML will still work but discovered values won't be saved.",
e.getMessage());
}
}
private Optional<IdpMetadataInfo> loadIdpMetadata(SAML2 samlConf) {
String metadataLocation = samlConf.getEffectiveMetadataUri();
if (metadataLocation == null || metadataLocation.isBlank()) {
return Optional.empty();
}
try (InputStream metadataStream = samlConf.getMetadataUriAsStream()) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
// XXE prevention - disable all external entities and DTD processing
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(metadataStream);
Element entityDescriptor = doc.getDocumentElement();
if (entityDescriptor == null) {
log.warn("No EntityDescriptor found in SAML metadata: {}", metadataLocation);
return Optional.empty();
}
String entityId = entityDescriptor.getAttribute("entityID");
NodeList idpDescriptors =
entityDescriptor.getElementsByTagNameNS(SAML_METADATA_NS, "IDPSSODescriptor");
if (idpDescriptors.getLength() == 0) {
log.warn("No IDPSSODescriptor found in SAML metadata: {}", metadataLocation);
return Optional.empty();
}
Element idpDescriptor = (Element) idpDescriptors.item(0);
String ssoUrl = extractServiceLocation(idpDescriptor, "SingleSignOnService");
String sloUrl = extractServiceLocation(idpDescriptor, "SingleLogoutService");
X509Certificate signingCert = extractSigningCertificate(idpDescriptor);
log.info("Loaded IdP metadata from: {}", metadataLocation);
return Optional.of(new IdpMetadataInfo(entityId, ssoUrl, sloUrl, signingCert));
} catch (IOException
| ParserConfigurationException
| SAXException
| CertificateException e) {
log.warn("Failed to parse SAML metadata from {}: {}", metadataLocation, e.getMessage());
return Optional.empty();
}
}
private String extractServiceLocation(Element descriptor, String tagName) {
NodeList services = descriptor.getElementsByTagNameNS(SAML_METADATA_NS, tagName);
String fallback = null;
for (int i = 0; i < services.getLength(); i++) {
Element service = (Element) services.item(i);
String location = service.getAttribute("Location");
String binding = service.getAttribute("Binding");
if (!hasText(location)) {
continue;
}
if (Saml2MessageBinding.POST.getUrn().equals(binding)) {
return location;
}
if (fallback == null) {
fallback = location;
}
}
return fallback;
}
private X509Certificate extractSigningCertificate(Element descriptor)
throws CertificateException {
NodeList keyDescriptors =
descriptor.getElementsByTagNameNS(SAML_METADATA_NS, "KeyDescriptor");
for (int i = 0; i < keyDescriptors.getLength(); i++) {
Element keyDescriptor = (Element) keyDescriptors.item(i);
String use = keyDescriptor.getAttribute("use");
if (hasText(use) && !"signing".equalsIgnoreCase(use)) {
continue;
}
NodeList certificateNodes =
keyDescriptor.getElementsByTagNameNS(XML_DSIG_NS, "X509Certificate");
if (certificateNodes.getLength() == 0) {
continue;
}
String certificateValue = certificateNodes.item(0).getTextContent();
if (!hasText(certificateValue)) {
continue;
}
byte[] decoded =
Base64.getMimeDecoder().decode(certificateValue.replaceAll("\\s+", ""));
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
return (X509Certificate)
certificateFactory.generateCertificate(new ByteArrayInputStream(decoded));
}
return null;
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
private void overrideIfPresent(String value, Consumer<String> setter) {
if (hasText(value)) {
setter.accept(value.trim());
}
}
private record IdpMetadataInfo(
String entityId,
String singleSignOnServiceUrl,
String singleLogoutServiceUrl,
X509Certificate signingCertificate) {}
private static void logAuthnRequestDetails(AuthnRequest authnRequest) {
String message =
"""
@@ -258,6 +258,24 @@ public class JwtService implements JwtServiceInterface {
return token;
}
// Check for logout cookie (set by frontend before redirecting to /logout for SAML SLO)
if (request.getCookies() != null) {
for (jakarta.servlet.http.Cookie cookie : request.getCookies()) {
if ("stirling_logout_token".equals(cookie.getName())) {
String value = cookie.getValue();
if (value != null && !value.isBlank()) {
try {
return java.net.URLDecoder.decode(
value, java.nio.charset.StandardCharsets.UTF_8);
} catch (Exception e) {
log.debug("Failed to decode logout token cookie", e);
return value;
}
}
}
}
}
return null;
}
@@ -6,9 +6,9 @@ import static org.mockito.Mockito.when;
import java.io.IOException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
@@ -26,17 +26,24 @@ class CustomLogoutSuccessHandlerTest {
@Mock private JwtServiceInterface jwtService;
@InjectMocks private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@Mock private ApplicationProperties.Security.SAML2 saml2;
private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@BeforeEach
void setUp() {
customLogoutSuccessHandler = new CustomLogoutSuccessHandler(securityProperties, jwtService);
}
@Test
void testSuccessfulLogout() throws IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
String token = "token";
String logoutPath = "/login?logout=true";
when(response.isCommitted()).thenReturn(false);
when(jwtService.extractToken(request)).thenReturn(token);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getContextPath()).thenReturn("");
when(response.encodeRedirectURL(logoutPath)).thenReturn(logoutPath);
@@ -50,10 +57,10 @@ class CustomLogoutSuccessHandlerTest {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
String logoutPath = "/login?logout=true";
String token = "token";
when(response.isCommitted()).thenReturn(false);
when(jwtService.extractToken(request)).thenReturn(token);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getContextPath()).thenReturn("");
when(response.encodeRedirectURL(logoutPath)).thenReturn(logoutPath);
@@ -71,6 +78,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getScheme()).thenReturn("http");
@@ -96,6 +106,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
@@ -128,6 +141,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter(error)).thenReturn("true");
when(request.getScheme()).thenReturn("http");
when(request.getServerName()).thenReturn("localhost");
@@ -152,6 +168,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn("!!!" + error + "!!!");
when(request.getScheme()).thenReturn("http");
@@ -177,10 +196,12 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter(error)).thenReturn("true");
when(request.getContextPath()).thenReturn(url);
when(request.getScheme()).thenReturn("http");
when(request.getServerName()).thenReturn("localhost");
when(request.getServerPort()).thenReturn(8080);
@@ -204,6 +225,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
@@ -236,6 +260,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
@@ -269,6 +296,9 @@ class CustomLogoutSuccessHandlerTest {
mock(ApplicationProperties.Security.OAUTH2.class);
when(response.isCommitted()).thenReturn(false);
when(request.getParameter("SAMLResponse")).thenReturn(null);
when(securityProperties.getSaml2()).thenReturn(saml2);
when(saml2.getEnableSingleLogout()).thenReturn(false);
when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
when(request.getParameter("errorOAuth")).thenReturn(null);
when(request.getParameter("oAuth2AutoCreateDisabled")).thenReturn(null);
+1 -1
View File
@@ -67,7 +67,7 @@ springBoot {
allprojects {
group = 'stirling.software'
version = '2.4.1'
version = '2.4.2'
configurations.configureEach {
exclude group: 'commons-logging', module: 'commons-logging'
+59
View File
@@ -0,0 +1,59 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0.69 5.4 400 390.62">
<g clip-path="url(#clip0_10641_164)">
<path d="M0.685165 65.8523C0.685165 14.7648 67.4855 -13.2029 111.616 19.4083L207.551 90.2535L288.514 44.373C331.305 21.0394 399.874 37.7748 400.685 101.559L400.685 336.622C400.685 387.71 335.845 414.343 291.715 381.732L194.031 309.34L112.973 355.23C69.7783 378.784 0.752625 360.714 0.752625 298.637C0.752654 224.124 0.685165 252.734 0.685165 65.8523Z" fill="url(#paint0_linear_10641_164)"/>
<path d="M0.685165 65.8523C0.685165 14.7648 67.4855 -13.2029 111.616 19.4083L207.551 90.2535L288.514 44.373C331.305 21.0394 399.874 37.7748 400.685 101.559L400.685 336.622C400.685 387.71 335.845 414.343 291.715 381.732L194.031 309.34L112.973 355.23C69.7783 378.784 0.752625 360.714 0.752625 298.637C0.752654 224.124 0.685165 252.734 0.685165 65.8523Z" fill="url(#paint1_radial_10641_164)"/>
<path d="M0.685165 65.8523C0.685165 14.7648 67.4855 -13.2029 111.616 19.4083L207.551 90.2535L288.514 44.373C331.305 21.0394 399.874 37.7748 400.685 101.559L400.685 336.622C400.685 387.71 335.845 414.343 291.715 381.732L194.031 309.34L112.973 355.23C69.7783 378.784 0.752625 360.714 0.752625 298.637C0.752654 224.124 0.685165 252.734 0.685165 65.8523Z" fill="url(#paint2_radial_10641_164)"/>
<path d="M111.616 19.4083C67.4855 -13.2029 0.685165 14.7648 0.685165 65.8523V295.742C0.685165 290.153 3.5327 279.026 3.5327 279.026C16.6954 236.001 72.6487 219.869 111.36 248.223L291.715 381.732C335.845 414.343 400.685 387.71 400.685 336.622V101.559C400.685 145.201 343.643 189.011 289.755 151.051L111.616 19.4083Z" fill="url(#paint3_radial_10641_164)"/>
<path d="M111.616 19.4083C67.4855 -13.2029 0.685165 14.7648 0.685165 65.8523V295.742C0.685165 290.153 3.5327 279.026 3.5327 279.026C16.6954 236.001 72.6487 219.869 111.36 248.223L291.715 381.732C335.845 414.343 400.685 387.71 400.685 336.622V101.559C400.685 145.201 343.643 189.011 289.755 151.051L111.616 19.4083Z" fill="url(#paint4_radial_10641_164)" fill-opacity="0.25"/>
<path d="M111.616 19.4083C67.4855 -13.2029 0.685165 14.7648 0.685165 65.8523V295.742C0.685165 290.153 3.5327 279.026 3.5327 279.026C16.6954 236.001 72.6487 219.869 111.36 248.223L291.715 381.732C335.845 414.343 400.685 387.71 400.685 336.622V101.559C400.685 145.201 343.643 189.011 289.755 151.051L111.616 19.4083Z" fill="url(#paint5_radial_10641_164)" fill-opacity="0.55"/>
<path d="M111.616 149.691C67.4855 117.08 0.685165 145.048 0.685165 196.135L0.685179 65.8523C0.685183 14.7648 67.4855 -13.2029 111.616 19.4083C170.996 63.2888 230.374 107.171 289.755 151.051C343.643 189.011 400.685 145.201 400.685 101.559V234.89C400.685 285.978 333.885 313.946 289.755 281.334C230.374 237.454 170.996 193.572 111.616 149.691Z" fill="url(#paint6_linear_10641_164)"/>
<path d="M111.616 149.691C67.4855 117.08 0.685165 145.048 0.685165 196.135L0.685179 65.8523C0.685183 14.7648 67.4855 -13.2029 111.616 19.4083C170.996 63.2888 230.374 107.171 289.755 151.051C343.643 189.011 400.685 145.201 400.685 101.559V234.89C400.685 285.978 333.885 313.946 289.755 281.334C230.374 237.454 170.996 193.572 111.616 149.691Z" fill="url(#paint7_radial_10641_164)" fill-opacity="0.35"/>
</g>
<defs>
<linearGradient id="paint0_linear_10641_164" x1="171.501" y1="396.026" x2="314.256" y2="90.5646" gradientUnits="userSpaceOnUse">
<stop offset="0.02" stop-color="#1169DA"/>
<stop offset="0.434784" stop-color="#0151BD"/>
<stop offset="0.614436" stop-color="#014DB7"/>
<stop offset="1" stop-color="#126AD9"/>
</linearGradient>
<radialGradient id="paint1_radial_10641_164" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(358.656 -48.704) rotate(110.224) scale(292.248 218.917)">
<stop offset="0.422966" stop-color="#004AFF" stop-opacity="0.1"/>
<stop offset="0.728672" stop-color="#014DB9"/>
<stop offset="0.836135" stop-color="#014DB9" stop-opacity="0.9"/>
<stop offset="0.955" stop-color="#014DB9" stop-opacity="0"/>
</radialGradient>
<radialGradient id="paint2_radial_10641_164" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(54.0821 384.087) rotate(-73.6432) scale(232.668 283.419)">
<stop offset="0.0908532" stop-color="#004AFF" stop-opacity="0.1"/>
<stop offset="0.56036" stop-color="#014DB9"/>
<stop offset="0.749466" stop-color="#014DB9" stop-opacity="0.99"/>
<stop offset="1" stop-color="#014DB9" stop-opacity="0"/>
</radialGradient>
<radialGradient id="paint3_radial_10641_164" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(439.444 5.40101) rotate(134.068) scale(563.957 434.374)">
<stop offset="0.249322" stop-color="#23C0FE"/>
<stop offset="0.717207" stop-color="#23C0FE"/>
<stop offset="0.995168" stop-color="#1C91FF"/>
</radialGradient>
<radialGradient id="paint4_radial_10641_164" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(119.961 37.1103) rotate(45.9092) scale(403.457 95.9789)">
<stop offset="0.165" stop-color="#096DD6" stop-opacity="0"/>
<stop offset="0.484233" stop-color="#096DD6"/>
<stop offset="0.900505" stop-color="#0876DE" stop-opacity="0.813868"/>
<stop offset="1" stop-color="#029AFF" stop-opacity="0"/>
</radialGradient>
<radialGradient id="paint5_radial_10641_164" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(385.776 245.022) rotate(91.6099) scale(64.799 58.3555)">
<stop stop-color="#0068B3"/>
<stop offset="0.93" stop-color="#006CB8" stop-opacity="0"/>
</radialGradient>
<linearGradient id="paint6_linear_10641_164" x1="114.72" y1="97.5227" x2="182.067" y2="383.699" gradientUnits="userSpaceOnUse">
<stop stop-color="#92EEFE"/>
<stop offset="0.564559" stop-color="#35DDFF"/>
<stop offset="1" stop-color="#08B1F9"/>
</linearGradient>
<radialGradient id="paint7_radial_10641_164" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(67.7807 5.4011) rotate(69.461) scale(99.6637 80.4988)">
<stop stop-color="#CCF9FF" stop-opacity="0.93"/>
<stop offset="1" stop-color="#35DDFF"/>
</radialGradient>
<clipPath id="clip0_10641_164">
<rect width="400" height="400" fill="white" transform="translate(0.685181 0.713501)"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 6.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="0 0 512 512"><circle cx="256" cy="256" r="256" fill="#fff"/><path d="M268.6 102.4c64.4 0 116.8 52.4 116.8 116.7 0 25.3-8 49.4-23 69.6-14.8 19.9-35 34.3-58.4 41.7l-6.5 2-15.5-76.2 4.3-2c14-6.7 23-21.1 23-36.6 0-22.4-18.2-40.6-40.6-40.6S228 195.2 228 217.6c0 15.5 9 29.8 23 36.6l4.2 2-25 153.4h-69.5V102.4z" style="fill:#191919"/></svg>

After

Width:  |  Height:  |  Size: 404 B

+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="none">
<g fill="#000000">
<path d="M7.754 2l.463.41c.343.304.687.607 1.026.915C11.44 5.32 13.3 7.565 14.7 10.149c.072.132.137.268.202.403l.098.203-.108.057-.081-.115-.21-.299-.147-.214c-1.019-1.479-2.04-2.96-3.442-4.145a6.563 6.563 0 00-1.393-.904c-1.014-.485-1.916-.291-2.69.505-.736.757-1.118 1.697-1.463 2.653-.045.123-.092.245-.139.367l-.082.215-.172-.055c.1-.348.192-.698.284-1.049.21-.795.42-1.59.712-2.356.31-.816.702-1.603 1.093-2.39.169-.341.338-.682.5-1.025h.092z"/>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -3560,6 +3560,39 @@ imageSize = "Image Size"
margin = "Margin"
positionAndFormatting = "Position & Formatting"
quickPosition = "Select a position on the page to place the stamp."
preview = "Preview:"
useTemplate = "Use Template"
selectTemplate = "Select a template..."
stampTextDescription = "Use dynamic variables below. Use @@ for literal @. Use \\n for new lines."
dynamicVariables = "Dynamic Variables"
clickToExpand = "Click to expand"
variablesHelp = "Click on any variable to insert it into your stamp text. Use @@ for literal @."
dateTimeVars = "Date & Time"
dateDesc = "Current date"
timeDesc = "Current time"
datetimeDesc = "Date and time combined"
customDateDesc = "Custom format"
yearMonthDayDesc = "Individual date parts"
pageVars = "Page Information"
pageNumberDesc = "Current page number"
totalPagesDesc = "Total number of pages"
fileVars = "File Information"
filenameDesc = "Filename without extension"
filenameFullDesc = "Filename with extension"
metadataVars = "Document Metadata"
metadataDesc = "From PDF document properties"
otherVars = "Other"
uuidDesc = "Short unique identifier (8 chars)"
examples = "Examples"
multiLine = "multi-line"
[AddStampRequest.template]
pageNumberFooter = "Page Number Footer"
dateHeader = "Date Header"
europeanDate = "European Date"
timestamp = "Timestamp"
draftWatermark = "Draft Watermark"
custom = "Custom"
[AddStampRequest.error]
failed = "An error occurred while adding stamp to the PDF."
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Stirling-PDF",
"version": "2.4.1",
"version": "2.4.2",
"identifier": "stirling.pdf.dev",
"build": {
"frontendDist": "../dist",
@@ -486,12 +486,6 @@ export const SAML2_PROVIDER: Provider = {
description: 'Enable SAML2 authentication (Enterprise only)',
defaultValue: false,
},
{
key: 'provider',
type: 'text',
label: 'Provider Name',
description: 'The name of your SAML2 provider',
},
{
key: 'registrationId',
type: 'text',
@@ -500,51 +494,66 @@ export const SAML2_PROVIDER: Provider = {
defaultValue: 'stirling',
},
{
key: 'idpMetadataUri',
key: 'metadataUri',
type: 'text',
label: 'IDP Metadata URI',
description: 'The URI for your provider\'s metadata',
label: 'Metadata URI',
description: 'Your IdP\'s metadata URI (recommended - auto-discovers IdP config)',
placeholder: 'https://dev-XXXXXXXX.okta.com/app/externalKey/sso/saml/metadata',
},
{
key: 'idpSingleLoginUrl',
key: 'enableSingleLogout',
type: 'switch',
label: 'Enable Single Logout',
description: 'Enable SP-initiated Single Logout (SLO)',
defaultValue: false,
},
// IdP Provider settings (manual config - only needed if metadataUri not available)
{
key: 'provider.name',
type: 'text',
label: 'IDP Single Login URL',
description: 'The URL for initiating SSO',
placeholder: 'https://dev-XXXXXXXX.okta.com/app/dev-XXXXXXXX_stirlingpdf_1/externalKey/sso/saml',
label: 'Provider Name',
description: 'Display name for your IdP (optional, for reference only)',
},
{
key: 'idpSingleLogoutUrl',
key: 'provider.singleLoginUrl',
type: 'text',
label: 'IDP Single Logout URL',
description: 'The URL for initiating SLO',
placeholder: 'https://dev-XXXXXXXX.okta.com/app/dev-XXXXXXXX_stirlingpdf_1/externalKey/slo/saml',
label: 'SSO URL',
description: 'IdP Single Sign-On URL (auto-discovered from metadata if set)',
placeholder: 'https://dev-XXXXXXXX.okta.com/app/.../sso/saml',
},
{
key: 'idpIssuer',
key: 'provider.singleLogoutUrl',
type: 'text',
label: 'IDP Issuer',
description: 'The ID of your provider',
label: 'SLO URL',
description: 'IdP Single Logout URL (auto-discovered from metadata if set)',
placeholder: 'https://dev-XXXXXXXX.okta.com/app/.../slo/saml',
},
{
key: 'idpCert',
key: 'provider.entityId',
type: 'text',
label: 'IDP Certificate',
description: 'The certificate path (e.g., classpath:okta.cert)',
label: 'IdP Entity ID',
description: 'IdP Entity ID (auto-discovered from metadata if set)',
},
{
key: 'provider.cert',
type: 'text',
label: 'IdP Certificate',
description: 'IdP signing certificate path (auto-discovered from metadata if set)',
placeholder: 'classpath:okta.cert',
},
// SP credentials
{
key: 'privateKey',
key: 'sp.privateKey',
type: 'text',
label: 'Private Key',
description: 'Your private key path',
label: 'SP Private Key',
description: 'Your Service Provider private key path',
placeholder: 'classpath:saml-private-key.key',
},
{
key: 'spCert',
key: 'sp.cert',
type: 'text',
label: 'SP Certificate',
description: 'Your signing certificate path',
description: 'Your Service Provider signing certificate path',
placeholder: 'classpath:saml-public-cert.crt',
},
{
@@ -99,7 +99,7 @@ const StampPositionFormattingSettings = ({ parameters, onParameterChange, disabl
<Group className={styles.sliderGroup} align="center">
<NumberInput
value={parameters.fontSize}
onChange={(v) => onParameterChange('fontSize', typeof v === 'number' ? v : 1)}
onChange={(v) => onParameterChange('fontSize', typeof v === 'number' && v > 0 ? v : 1)}
min={1}
max={400}
step={1}
@@ -114,6 +114,7 @@ const StampPositionFormattingSettings = ({ parameters, onParameterChange, disabl
max={400}
step={1}
className={styles.slider}
disabled={disabled}
/>
</Group>
</Stack>
@@ -1,18 +1,169 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Stack, Textarea, TextInput, Select, Button, Text, Divider } from "@mantine/core";
import { Stack, Textarea, TextInput, Select, Button, Text, Divider, Accordion, Code, Group, Badge, Box, Paper } from "@mantine/core";
import { AddStampParameters } from "@app/components/tools/addStamp/useAddStampParameters";
import ButtonSelector from "@app/components/shared/ButtonSelector";
import styles from "@app/components/tools/addStamp/StampPreview.module.css";
import { getDefaultFontSizeForAlphabet } from "@app/components/tools/addStamp/StampPreviewUtils";
import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";
const STAMP_TEMPLATES = [
{
id: 'page-numbers',
name: 'Page Numbers',
text: 'Page @page_number of @total_pages',
position: 2, // bottom center
},
{
id: 'draft',
name: 'Draft Watermark',
text: 'DRAFT - @date',
position: 5, // center
},
{
id: 'doc-info',
name: 'Document Info',
text: '@filename\nCreated: @date{dd MMM yyyy}',
position: 7, // top left
},
{
id: 'legal-footer',
name: 'Legal Footer',
text: '© @year - All Rights Reserved\n@filename - Page @page_number',
position: 2, // bottom center
},
{
id: 'european-date',
name: 'European Date (DD/MM/YYYY)',
text: '@date{dd/MM/yyyy}',
position: 9, // top right
},
{
id: 'timestamp',
name: 'Timestamp',
text: '@date{dd/MM/yyyy HH:mm}',
position: 9, // top right
},
];
const resolveVariablesForPreview = (text: string, filename?: string): string => {
const now = new Date();
const pad = (n: number) => String(n).padStart(2, '0');
const ESCAPED_AT_PLACEHOLDER = '\uE000ESCAPED_AT\uE000';
let result = text.replace(/@@/g, ESCAPED_AT_PLACEHOLDER);
const actualFilename = filename || 'sample-document.pdf';
const filenameWithoutExt = actualFilename.includes('.')
? actualFilename.substring(0, actualFilename.lastIndexOf('.'))
: actualFilename;
const sampleData: Record<string, string> = {
'@datetime': `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
'@date': `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
'@time': `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
'@year': String(now.getFullYear()),
'@month': pad(now.getMonth() + 1),
'@day': pad(now.getDate()),
// Page info - cannot be previewed, show placeholder
'@page_number': '?',
'@page': '?',
'@total_pages': '?',
'@page_count': '?',
// Filename - use actual file if provided
'@filename': filenameWithoutExt,
'@filename_full': actualFilename,
// Metadata - cannot be read from PDF in frontend, show placeholder
'@author': '?',
'@title': '?',
'@subject': '?',
// UUID - will be random each time
'@uuid': '????????',
};
result = result.replace(/@date\{([^}]+)\}/g, (match, format) => {
try {
return format
.replace(/yyyy/g, String(now.getFullYear()))
.replace(/yy/g, String(now.getFullYear()).slice(-2))
.replace(/MMMM/g, now.toLocaleString('default', { month: 'long' }))
.replace(/MMM/g, now.toLocaleString('default', { month: 'short' }))
.replace(/MM/g, pad(now.getMonth() + 1))
.replace(/dd/g, pad(now.getDate()))
.replace(/HH/g, pad(now.getHours()))
.replace(/hh/g, pad(now.getHours() % 12 || 12))
.replace(/mm/g, pad(now.getMinutes()))
.replace(/ss/g, pad(now.getSeconds()));
} catch {
return match;
}
});
Object.entries(sampleData).forEach(([key, value]) => {
result = result.split(key).join(value);
});
result = result.replace(new RegExp(ESCAPED_AT_PLACEHOLDER, 'g'), '@');
result = result.replace(/\\n/g, '\n');
return result;
};
interface ClickableCodeProps {
children: React.ReactNode;
onClick: () => void;
block?: boolean;
}
const ClickableCode = ({ children, onClick, block = false }: ClickableCodeProps) => (
<Code
tabIndex={0}
role="button"
style={{
cursor: 'pointer',
display: block ? 'block' : undefined,
}}
onClick={onClick}
onKeyDown={(e: React.KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onClick();
}
}}
>
{children}
</Code>
);
const StampTextPreview = ({ stampText, filename }: { stampText: string; filename?: string }) => {
const { t } = useTranslation();
const resolvedText = useMemo(() => {
if (!stampText.trim()) return '';
return resolveVariablesForPreview(stampText, filename);
}, [stampText, filename]);
if (!stampText.trim()) return null;
return (
<Paper p="xs" withBorder bg="var(--mantine-color-default)">
<Text size="xs" c="dimmed" mb={4}>{t('AddStampRequest.preview', 'Preview:')}</Text>
<Text size="sm" style={{ whiteSpace: 'pre-wrap', fontFamily: 'monospace', wordBreak: 'break-word' }}>
{resolvedText}
</Text>
</Paper>
);
};
interface StampSetupSettingsProps {
parameters: AddStampParameters;
onParameterChange: <K extends keyof AddStampParameters>(key: K, value: AddStampParameters[K]) => void;
disabled?: boolean;
filename?: string;
}
const StampSetupSettings = ({ parameters, onParameterChange, disabled = false }: StampSetupSettingsProps) => {
const StampSetupSettings = ({ parameters, onParameterChange, disabled = false, filename }: StampSetupSettingsProps) => {
const { t } = useTranslation();
return (
@@ -41,14 +192,172 @@ const StampSetupSettings = ({ parameters, onParameterChange, disabled = false }:
{parameters.stampType === 'text' && (
<>
{/* Template Selector - always shows placeholder, doesn't persist selection */}
<Select
label={t('AddStampRequest.useTemplate', 'Use Template')}
placeholder={t('AddStampRequest.selectTemplate', 'Select a template...')}
value={null}
data={STAMP_TEMPLATES.map(template => ({
value: template.id,
label: t(`AddStampRequest.template.${template.id}`, template.name)
}))}
onChange={(value) => {
const template = STAMP_TEMPLATES.find(t => t.id === value);
if (template) {
onParameterChange('stampText', template.text);
onParameterChange('position', template.position as any);
}
}}
clearable
disabled={disabled}
comboboxProps={{ withinPortal: true, zIndex: Z_INDEX_AUTOMATE_DROPDOWN }}
/>
<Textarea
label={t('AddStampRequest.stampText', 'Stamp Text')}
description={t('AddStampRequest.stampTextDescription', 'Use dynamic variables below. Use @@ for literal @. Use \\n for new lines.')}
value={parameters.stampText}
onChange={(e) => onParameterChange('stampText', e.currentTarget.value)}
autosize
minRows={2}
disabled={disabled}
/>
{/* Live Preview */}
<StampTextPreview stampText={parameters.stampText} filename={filename} />
<Accordion variant="contained" radius="sm">
<Accordion.Item value="variables">
<Accordion.Control>
<Group gap="xs">
<Text size="sm" fw={500}>{t('AddStampRequest.dynamicVariables', 'Dynamic Variables')}</Text>
<Badge size="xs" variant="light" color="blue">{t('AddStampRequest.clickToExpand', 'Click to expand')}</Badge>
</Group>
</Accordion.Control>
<Accordion.Panel>
<Stack gap="xs">
<Text size="xs" c="dimmed" mb="xs">
{t('AddStampRequest.variablesHelp', 'Click on any variable to insert it into your stamp text. Use @@ for literal @.')}
</Text>
<Box>
<Text size="xs" fw={600} mb={4}>{t('AddStampRequest.dateTimeVars', 'Date & Time')}</Text>
<Group gap="xs">
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@date')}>
@date
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.dateDesc', 'Current date')} (YYYY-MM-DD)</Text>
</Group>
<Group gap="xs" mt={4}>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@time')}>
@time
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.timeDesc', 'Current time')} (HH:mm:ss)</Text>
</Group>
<Group gap="xs" mt={4}>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@datetime')}>
@datetime
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.datetimeDesc', 'Date and time combined')}</Text>
</Group>
<Group gap="xs" mt={4}>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@date{dd/MM/yyyy}')}>
@date&#123;format&#125;
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.customDateDesc', 'Custom format')}</Text>
</Group>
<Group gap="xs" mt={4}>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@year')}>
@year
</ClickableCode>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@month')}>
@month
</ClickableCode>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@day')}>
@day
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.yearMonthDayDesc', 'Individual date parts')}</Text>
</Group>
</Box>
<Divider my="xs" />
<Box>
<Text size="xs" fw={600} mb={4}>{t('AddStampRequest.pageVars', 'Page Information')}</Text>
<Group gap="xs">
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@page_number')}>
@page_number
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.pageNumberDesc', 'Current page number')}</Text>
</Group>
<Group gap="xs" mt={4}>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@total_pages')}>
@total_pages
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.totalPagesDesc', 'Total number of pages')}</Text>
</Group>
</Box>
<Divider my="xs" />
<Box>
<Text size="xs" fw={600} mb={4}>{t('AddStampRequest.fileVars', 'File Information')}</Text>
<Group gap="xs">
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@filename')}>
@filename
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.filenameDesc', 'Filename without extension')}</Text>
</Group>
<Group gap="xs" mt={4}>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@filename_full')}>
@filename_full
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.filenameFullDesc', 'Filename with extension')}</Text>
</Group>
</Box>
<Divider my="xs" />
<Box>
<Text size="xs" fw={600} mb={4}>{t('AddStampRequest.metadataVars', 'Document Metadata')}</Text>
<Group gap="xs">
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@author')}>
@author
</ClickableCode>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@title')}>
@title
</ClickableCode>
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@subject')}>
@subject
</ClickableCode>
</Group>
<Text size="xs" c="dimmed" mt={4}>— {t('AddStampRequest.metadataDesc', 'From PDF document properties')}</Text>
</Box>
<Divider my="xs" />
<Box>
<Text size="xs" fw={600} mb={4}>{t('AddStampRequest.otherVars', 'Other')}</Text>
<Group gap="xs">
<ClickableCode onClick={() => onParameterChange('stampText', parameters.stampText + '@uuid')}>
@uuid
</ClickableCode>
<Text size="xs" c="dimmed">— {t('AddStampRequest.uuidDesc', 'Short unique identifier (8 chars)')}</Text>
</Group>
</Box>
<Divider my="xs" />
<Box>
<Text size="xs" fw={600} mb={4}>{t('AddStampRequest.examples', 'Examples')}</Text>
<Stack gap={4}>
<ClickableCode block onClick={() => onParameterChange('stampText', 'Page @page_number of @total_pages')}>
Page @page_number of @total_pages
</ClickableCode>
<ClickableCode block onClick={() => onParameterChange('stampText', 'Created: @date{dd/MM/yyyy HH:mm}')}>
Created: @date&#123;dd/MM/yyyy HH:mm&#125;
</ClickableCode>
<ClickableCode block onClick={() => onParameterChange('stampText', '© @year @author')}>
© @year @author
</ClickableCode>
<ClickableCode block onClick={() => onParameterChange('stampText', '@filename\\n@date')}>
@filename\n@date ({t('AddStampRequest.multiLine', 'multi-line')})
</ClickableCode>
</Stack>
</Box>
</Stack>
</Accordion.Panel>
</Accordion.Item>
</Accordion>
<Select
label={t('AddStampRequest.alphabet', 'Alphabet')}
value={parameters.alphabet}
@@ -22,7 +22,7 @@ export const defaultParameters: AddStampParameters = {
stampType: 'text',
stampText: '',
alphabet: 'roman',
fontSize: 80,
fontSize: 40,
rotation: 0,
opacity: 50,
position: 5,
@@ -180,6 +180,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
subcategoryId: SubcategoryId.GENERAL,
maxFiles: -1,
endpoints: ["multi-tool"],
synonyms: getSynonyms(t, "multiTool"),
supportsAutomate: false,
automationSettings: null
@@ -218,6 +219,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
description: t("home.sign.desc", "Adds signature to PDF by drawing, text or image"),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.SIGNING,
endpoints: ["sign"],
operationConfig: signOperationConfig,
automationSettings: SignSettings, // TODO:: not all settings shown, suggested next tools shown
synonyms: getSynonyms(t, "sign"),
@@ -230,6 +232,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
description: t('home.addText.desc', 'Add custom text anywhere in your PDF'),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.GENERAL,
endpoints: ["sign"],
operationConfig: signOperationConfig,
automationSettings: null,
synonyms: getSynonyms(t, 'addText'),
@@ -242,6 +245,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
description: t('home.addImage.desc', 'Add images anywhere in your PDF'),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.GENERAL,
endpoints: ["add-image"],
operationConfig: signOperationConfig,
automationSettings: null,
synonyms: getSynonyms(t, 'addImage'),
@@ -255,6 +259,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.GENERAL,
workbench: 'viewer',
endpoints: ["view-pdf"],
operationConfig: signOperationConfig,
automationSettings: null,
synonyms: getSynonyms(t, 'annotate'),
@@ -393,6 +398,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
),
categoryId: ToolCategoryId.STANDARD_TOOLS,
subcategoryId: SubcategoryId.DOCUMENT_REVIEW,
endpoints: ["view-pdf"],
synonyms: getSynonyms(t, "read"),
supportsAutomate: false,
automationSettings: null
@@ -710,6 +716,8 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
description: t("home.adjustContrast.desc", "Adjust colors and contrast of PDF documents"),
categoryId: ToolCategoryId.ADVANCED_TOOLS,
subcategoryId: SubcategoryId.ADVANCED_FORMATTING,
maxFiles: -1,
endpoints: ["adjust-contrast"],
operationConfig: adjustContrastOperationConfig,
automationSettings: AdjustContrastSingleStepSettings,
synonyms: getSynonyms(t, "adjustContrast"),
@@ -850,6 +858,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
categoryId: ToolCategoryId.RECOMMENDED_TOOLS,
subcategoryId: SubcategoryId.GENERAL,
maxFiles: 2,
endpoints: ["compare"],
operationConfig: undefined,
automationSettings: null,
synonyms: getSynonyms(t, "compare"),
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
appVersion: '2.4.1',
appVersion: '2.4.2',
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
serverPort: 8080,
@@ -104,8 +104,8 @@ describe('Convert Tool Integration Tests', () => {
beforeEach(() => {
vi.clearAllMocks();
// Setup default apiClient mock
mockedApiClient.post = vi.fn();
// Reset the post mock - use type assertion for compatibility with both axios and TauriHttpClient
(mockedApiClient.post as ReturnType<typeof vi.fn>).mockReset();
});
afterEach(() => {
+1
View File
@@ -80,6 +80,7 @@ const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
parameters={params.parameters}
onParameterChange={params.updateParameter}
disabled={endpointLoading}
filename={selectedFiles[0]?.name}
/>
),
});
+18 -9
View File
@@ -1,4 +1,5 @@
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
import CardSelector from "@app/components/shared/CardSelector";
import SplitSettings from "@app/components/tools/split/SplitSettings";
@@ -8,7 +9,8 @@ import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";
import { useSplitMethodTips } from "@app/components/tooltips/useSplitMethodTips";
import { useSplitSettingsTips } from "@app/components/tooltips/useSplitSettingsTips";
import { BaseToolProps, ToolComponent } from "@app/types/tool";
import { type SplitMethod, METHOD_OPTIONS, type MethodOption } from "@app/constants/splitConstants";
import { type SplitMethod, METHOD_OPTIONS, type MethodOption, ENDPOINTS } from "@app/constants/splitConstants";
import { useMultipleEndpointsEnabled } from "@app/hooks/useEndpointConfig";
const Split = (props: BaseToolProps) => {
const { t } = useTranslation();
@@ -20,15 +22,23 @@ const Split = (props: BaseToolProps) => {
props
);
// Check which split endpoints are available
const allSplitEndpoints = useMemo(() => Object.values(ENDPOINTS), []);
const { endpointStatus } = useMultipleEndpointsEnabled(allSplitEndpoints);
// Filter METHOD_OPTIONS to only show methods with enabled endpoints
const availableMethodOptions = useMemo(() => {
return METHOD_OPTIONS.filter(option => {
const endpoint = ENDPOINTS[option.value];
// If endpoint status is not loaded yet, show all options (optimistic)
// If endpoint is explicitly disabled (false), hide the option
return endpointStatus[endpoint] !== false;
});
}, [endpointStatus]);
const methodTips = useSplitMethodTips();
const settingsTips = useSplitSettingsTips(base.params.parameters.method);
// Get tooltip content for a specific method
const getMethodTooltip = (option: MethodOption) => {
const tooltipContent = useSplitSettingsTips(option.value);
return tooltipContent?.tips || [];
};
// Get the method name for the settings step title
const getSettingsTitle = () => {
if (!base.params.parameters.method) return t("split.steps.settings", "Settings");
@@ -54,10 +64,9 @@ const Split = (props: BaseToolProps) => {
tooltip: methodTips,
content: (
<CardSelector<SplitMethod, MethodOption>
options={METHOD_OPTIONS}
options={availableMethodOptions}
onSelect={(method) => base.params.updateParameter('method', method)}
disabled={base.endpointLoading}
getTooltipContent={getMethodTooltip}
/>
),
},
@@ -6,7 +6,7 @@ import { SetupWizard } from '@app/components/SetupWizard';
import { useFirstLaunchCheck } from '@app/hooks/useFirstLaunchCheck';
import { useBackendInitializer } from '@app/hooks/useBackendInitializer';
import { DESKTOP_DEFAULT_APP_CONFIG } from '@app/config/defaultAppConfig';
import { connectionModeService } from '@desktop/services/connectionModeService';
import { connectionModeService } from '@app/services/connectionModeService';
import { tauriBackendService } from '@app/services/tauriBackendService';
import { authService } from '@app/services/authService';
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { authService, UserInfo } from '@app/services/authService';
import { buildOAuthCallbackHtml } from '@app/utils/oauthCallbackHtml';
import { BASE_PATH } from '@app/constants/app';
import { STIRLING_SAAS_URL } from '@desktop/constants/connection';
import { STIRLING_SAAS_URL } from '@app/constants/connection';
import '@app/routes/authShared/auth.css';
type KnownProviderId = 'google' | 'github' | 'keycloak' | 'azure' | 'apple' | 'oidc';
@@ -8,7 +8,7 @@ import { SelfHostedLoginScreen } from '@app/components/SetupWizard/SelfHostedLog
import { ServerConfig, connectionModeService } from '@app/services/connectionModeService';
import { AuthServiceError, authService, UserInfo } from '@app/services/authService';
import { tauriBackendService } from '@app/services/tauriBackendService';
import { STIRLING_SAAS_URL } from '@desktop/constants/connection';
import { STIRLING_SAAS_URL } from '@app/constants/connection';
import { listen } from '@tauri-apps/api/event';
import { useEffect } from 'react';
import '@app/routes/authShared/auth.css';
@@ -1,6 +1,6 @@
/**
* Desktop Override: Onboarding Orchestrator Hook
*
*
* Simply wraps the core hook with the desktop-specific default runtime state
* which has isDesktopApp set to true.
*/
@@ -9,7 +9,7 @@ import {
useOnboardingOrchestrator as useCoreOnboardingOrchestrator,
type UseOnboardingOrchestratorResult,
} from '@core/components/onboarding/orchestrator/useOnboardingOrchestrator';
import { DEFAULT_RUNTIME_STATE } from '@desktop/components/onboarding/orchestrator/onboardingConfig';
import { DEFAULT_RUNTIME_STATE } from '@app/components/onboarding/orchestrator/onboardingConfig';
export type {
OnboardingOrchestratorState,
@@ -5,7 +5,7 @@ import apiClient from '@app/services/apiClient';
import { tauriBackendService } from '@app/services/tauriBackendService';
import { isBackendNotReadyError } from '@app/constants/backendErrors';
import type { EndpointAvailabilityDetails } from '@app/types/endpointAvailability';
import { connectionModeService } from '@desktop/services/connectionModeService';
import { connectionModeService } from '@app/services/connectionModeService';
import type { AppConfig } from '@app/contexts/AppConfigContext';
+6 -1
View File
@@ -134,10 +134,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Listen for jwt-available event (triggered by desktop auth or other sources)
const handleJwtAvailable = () => {
console.debug('[Auth] JWT available event received, refreshing session');
console.log('[Auth] JWT available event received, refreshing session');
// Set loading true while we re-validate
setLoading(true);
void initializeAuth();
};
// Log that we're setting up the listener
console.debug('[Auth] Setting up jwt-available event listener');
window.addEventListener('jwt-available', handleJwtAvailable);
// Subscribe to auth state changes
@@ -251,40 +251,63 @@ describe('SpringAuthClient', () => {
});
describe('signOut', () => {
let mockForm: { method: string; action: string; style: { display: string }; submit: ReturnType<typeof vi.fn> };
let appendChildSpy: any;
beforeEach(() => {
// Mock form creation and submission
mockForm = {
method: '',
action: '',
style: { display: '' },
submit: vi.fn(),
};
vi.spyOn(document, 'createElement').mockReturnValue(mockForm as unknown as HTMLElement);
appendChildSpy = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should successfully sign out and clear JWT', async () => {
const mockToken = 'jwt-to-clear';
localStorage.setItem('stirling_jwt', mockToken);
vi.mocked(apiClient.post).mockResolvedValueOnce({
status: 200,
data: {},
} as any);
const result = await springAuth.signOut();
expect(apiClient.post).toHaveBeenCalledWith(
'/api/v1/auth/logout',
null,
expect.objectContaining({ withCredentials: true })
);
// JWT should be cleared from localStorage
expect(localStorage.getItem('stirling_jwt')).toBeNull();
// Should submit POST form to /logout for Spring Security logout handler
expect(mockForm.method).toBe('POST');
expect(mockForm.action).toBe('/logout');
expect(mockForm.submit).toHaveBeenCalled();
// Should return no error on successful signOut
expect(result.error).toBeNull();
});
it('should clear JWT even if logout request fails', async () => {
it('should create hidden form and submit POST to /logout', async () => {
const mockToken = 'jwt-to-clear';
localStorage.setItem('stirling_jwt', mockToken);
vi.mocked(apiClient.post).mockRejectedValueOnce({
isAxiosError: true,
response: { status: 500 },
message: 'Server error',
});
await springAuth.signOut();
// Verify form was created with correct attributes
expect(document.createElement).toHaveBeenCalledWith('form');
expect(mockForm.style.display).toBe('none');
expect(appendChildSpy).toHaveBeenCalled();
});
it('should handle signOut when no JWT is present', async () => {
localStorage.removeItem('stirling_jwt');
const result = await springAuth.signOut();
expect(localStorage.getItem('stirling_jwt')).toBeNull();
expect(result.error).toBeTruthy();
// Should still submit POST form to /logout
expect(mockForm.method).toBe('POST');
expect(mockForm.action).toBe('/logout');
expect(mockForm.submit).toHaveBeenCalled();
expect(result.error).toBeNull();
});
});
@@ -309,18 +309,25 @@ class SpringAuthClient {
/**
* Sign out user (invalidate session)
*
* For SAML/OAuth users, this navigates to /logout which triggers
* Spring Security's logout handler and initiates SSO logout.
* The JWT is passed via a short-lived cookie so the backend can
* extract the SAML NameID for single logout (SLO).
*/
async signOut(): Promise<{ error: AuthError | null }> {
try {
const response = await apiClient.post('/api/v1/auth/logout', null, {
headers: {
'X-XSRF-TOKEN': this.getCsrfToken() || '',
},
withCredentials: true,
});
// Get the JWT before removing it - we need to pass it to the backend
// so it can extract the SAML NameID for single logout (SLO)
const token = localStorage.getItem('stirling_jwt');
if (response.status === 200) {
// console.debug('[SpringAuth] signOut: Success');
// Store JWT in a short-lived cookie for the logout request
// This avoids exposing the token in URL params while ensuring
// it's sent with the redirect request
if (token) {
// Cookie expires in 30 seconds - just long enough for the logout redirect
// Secure: only sent over HTTPS; Path=/logout: scoped to logout endpoint only
document.cookie = `stirling_logout_token=${encodeURIComponent(token)}; path=/logout; max-age=30; SameSite=Lax; Secure`;
}
// Clean up local storage
@@ -355,13 +362,24 @@ class SpringAuthClient {
console.warn('[SpringAuth] Failed to run platform auth cleanup', cleanupError);
}
// Notify listeners
// Notify listeners before redirect
this.notifyListeners('SIGNED_OUT', null);
// Submit a POST form to /logout to trigger Spring Security's logout handler
// Using POST prevents logout CSRF attacks (GET-based logout can be triggered by any site)
console.log('[SpringAuth] Submitting POST to /logout for session invalidation');
const form = document.createElement('form');
form.method = 'POST';
form.action = `${BASE_PATH}/logout`;
form.style.display = 'none';
document.body.appendChild(form);
form.submit();
// This won't be reached if redirect happens, but return for type safety
return { error: null };
} catch (error: unknown) {
console.error('[SpringAuth] signOut error:', error);
// Still remove token even if backend call fails
// Still remove token even if the call fails
localStorage.removeItem('stirling_jwt');
try {
await clearPlatformAuthAfterSignOut();
@@ -1,20 +1,16 @@
import { Text, Button } from '@mantine/core';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@app/auth/UseSession';
import { useNavigate } from 'react-router-dom';
export function OverviewHeader() {
const { t } = useTranslation();
const { signOut, user } = useAuth();
const navigate = useNavigate();
const handleLogout = async () => {
try {
await signOut();
navigate('/login');
} catch (error) {
console.error('Logout error:', error);
}
console.log('[OverviewHeader] Logout button clicked, calling signOut()');
// signOut() handles navigation to /logout for SAML/OAuth SLO
// Do NOT navigate after signOut - it will redirect the page
await signOut();
};
return (
@@ -7,14 +7,12 @@ import { useAuth } from '@app/auth/UseSession';
import { accountService } from '@app/services/accountService';
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
import { QRCodeSVG } from 'qrcode.react';
import { useAccountLogout } from '@app/extensions/accountLogout';
import { BASE_PATH } from '@app/constants/app';
import { MfaSetupResponse } from '@app/responses/Mfa/MfaResponse';
const AccountSection: React.FC = () => {
const { t } = useTranslation();
const { user, signOut } = useAuth();
const accountLogout = useAccountLogout();
const [passwordModalOpen, setPasswordModalOpen] = useState(false);
const [usernameModalOpen, setUsernameModalOpen] = useState(false);
@@ -53,13 +51,12 @@ const AccountSection: React.FC = () => {
const userIdentifier = useMemo(() => user?.email || user?.username || '', [user?.email, user?.username]);
const redirectToLogin = useCallback(() => {
window.location.assign('/login');
}, []);
const handleLogout = useCallback(async () => {
await accountLogout({ signOut, redirectToLogin });
}, [accountLogout, redirectToLogin, signOut]);
console.log('[AccountSection] Logout button clicked, calling signOut()');
// signOut() handles navigation to /logout for SAML/OAuth SLO
// Do NOT navigate after signOut - it will redirect the page
await signOut();
}, [signOut]);
const handlePasswordSubmit = async (event: React.FormEvent) => {
event.preventDefault();
@@ -209,9 +209,20 @@ export default function AdminConnectionsSection() {
return !!(providerSettings?.clientId);
};
// Helper to get nested value from object using dot notation
const getNestedValue = (obj: Record<string, any>, path: string): any => {
return path.split('.').reduce((acc, part) => acc?.[part], obj);
};
const getProviderSettings = (provider: Provider): Record<string, any> => {
if (provider.id === 'saml2') {
return settings?.saml2 || {};
const saml2 = settings?.saml2 || {};
// Flatten nested structure to match field keys with dot notation
const result: Record<string, any> = {};
provider.fields.forEach((field) => {
result[field.key] = getNestedValue(saml2, field.key);
});
return result;
}
if (provider.id === 'smtp') {
@@ -297,8 +308,9 @@ export default function AdminConnectionsSection() {
const deltaSettings: Record<string, any> = {};
if (provider.id === 'saml2') {
// SAML2 settings
// SAML2 settings - keys may use dot notation (e.g., 'provider.name')
Object.keys(providerSettings).forEach((key) => {
// Key already has dot notation for nested paths, just prepend security.saml2.
deltaSettings[`security.saml2.${key}`] = providerSettings[key];
});
} else if (provider.id === 'oauth2-generic') {
@@ -65,51 +65,103 @@ export default function AdminEndpointsSection() {
);
}
// Common endpoint examples
// Complete list of all endpoints from frontend tool registry (alphabetical)
const commonEndpoints = [
'img-to-pdf',
'pdf-to-img',
'merge-pdfs',
'split-pdf',
'rotate-pdf',
'compress-pdf',
'extract-images',
'extract-image-scans',
'add-watermark',
'remove-watermark',
'add-password',
'remove-password',
'change-permissions',
'ocr-pdf',
'pdf-to-pdfa',
'html-to-pdf',
'url-to-pdf',
'markdown-to-pdf',
'get-info-on-pdf',
'extract-pdf-metadata',
'pdf-to-single-page',
'crop',
'auto-split-pdf',
'sanitize-pdf',
'add-attachments',
'add-image',
'add-page-numbers',
'add-password',
'add-stamp',
'add-watermark',
'adjust-contrast',
'auto-redact',
'auto-rename',
'scale-pages',
'repair',
'auto-split-pdf',
'booklet-imposition',
'cert-sign',
'compare',
'compress-pdf',
'crop',
'edit-table-of-contents',
'eml-to-pdf',
'extract-image-scans',
'extract-images',
'file-to-pdf',
'flatten',
'get-info-on-pdf',
'handleData',
'html-to-pdf',
'img-to-pdf',
'markdown-to-pdf',
'merge-pdfs',
'multi-page-layout',
'multi-tool',
'ocr-pdf',
'overlay-pdf',
'pdf-to-csv',
'pdf-to-epub',
'pdf-to-html',
'pdf-to-img',
'pdf-to-markdown',
'pdf-to-pdfa',
'pdf-to-presentation',
'pdf-to-single-page',
'pdf-to-text',
'pdf-to-word',
'pdf-to-xml',
'rearrange-pages',
'remove-annotations',
'remove-blanks',
'compare-pdfs'
'remove-cert-sign',
'remove-image-pdf',
'remove-pages',
'remove-password',
'repair',
'replace-invert-pdf',
'rotate-pdf',
'sanitize-pdf',
'scale-pages',
'scanner-effect',
'show-javascript',
'sign',
'split-by-size-or-count',
'split-pages',
'split-pdf-by-chapters',
'split-pdf-by-sections',
'text-editor-pdf',
'unlock-pdf-forms',
'update-metadata',
'validate-signature',
'view-pdf',
];
// Common endpoint groups
// Complete list of functional and tool groups from EndpointConfiguration.java
const commonGroups = [
'Conversion',
// Functional Groups
'PageOps',
'Convert',
'Security',
'Other',
'Organize',
'LibreOffice',
'Advance',
// Tool Groups
'CLI',
'Python',
'OpenCV'
'OpenCV',
'LibreOffice',
'Unoconvert',
'Java',
'Javascript',
'qpdf',
'Ghostscript',
'ImageMagick',
'tesseract',
'OCRmyPDF',
'Weasyprint',
'Pdftohtml',
'Calibre',
'FFmpeg',
'veraPDF',
'rar',
];
return (
@@ -1,15 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, waitFor } from '@testing-library/react';
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { render, cleanup, screen } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import AuthCallback from '@app/routes/AuthCallback';
import { springAuth } from '@app/auth/springAuthClient';
// Mock springAuth
vi.mock('@app/auth/springAuthClient', () => ({
springAuth: {
getSession: vi.fn(),
},
}));
// Mock useNavigate
const mockNavigate = vi.fn();
@@ -21,38 +13,38 @@ vi.mock('react-router-dom', async () => {
};
});
// Mock useAuth hook
const mockUseAuth = vi.fn();
vi.mock('@app/auth/UseSession', () => ({
useAuth: () => mockUseAuth(),
}));
describe('AuthCallback', () => {
beforeEach(() => {
vi.useFakeTimers();
localStorage.clear();
sessionStorage.clear();
vi.clearAllMocks();
// Reset window.location.hash
window.location.hash = '';
// Default mock: no session, not loading
mockUseAuth.mockReturnValue({ session: null, loading: false });
});
it('should extract JWT from URL hash and validate it', async () => {
afterEach(() => {
cleanup();
vi.runOnlyPendingTimers();
vi.useRealTimers();
});
it('should extract JWT from URL hash and store it', async () => {
const mockToken = 'oauth-jwt-token';
const mockUser = {
id: '123',
email: 'oauth@example.com',
username: 'oauthuser',
role: 'USER',
};
// Set URL hash with access token
window.location.hash = `#access_token=${mockToken}`;
// Mock successful session validation
vi.mocked(springAuth.getSession).mockResolvedValueOnce({
data: {
session: {
user: mockUser,
access_token: mockToken,
expires_in: 3600,
expires_at: Date.now() + 3600000,
},
},
error: null,
});
// Mock useAuth returning loading state (validation in progress)
mockUseAuth.mockReturnValue({ session: null, loading: true });
const dispatchEventSpy = vi.spyOn(window, 'dispatchEvent');
@@ -62,21 +54,16 @@ describe('AuthCallback', () => {
</BrowserRouter>
);
await waitFor(() => {
// Verify JWT was stored
expect(localStorage.getItem('stirling_jwt')).toBe(mockToken);
// Advance timers to trigger the delayed tokenStored update (50ms delay)
await vi.advanceTimersByTimeAsync(100);
// Verify jwt-available event was dispatched
expect(dispatchEventSpy).toHaveBeenCalledWith(
expect.objectContaining({ type: 'jwt-available' })
);
// Verify JWT was stored
expect(localStorage.getItem('stirling_jwt')).toBe(mockToken);
// Verify getSession was called to validate token
expect(springAuth.getSession).toHaveBeenCalled();
// Verify navigation to home
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
});
// Verify jwt-available event was dispatched
expect(dispatchEventSpy).toHaveBeenCalledWith(
expect.objectContaining({ type: 'jwt-available' })
);
});
it('should redirect to login when no access token in hash', async () => {
@@ -89,89 +76,29 @@ describe('AuthCallback', () => {
</BrowserRouter>
);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/login', {
replace: true,
state: { error: 'OAuth login failed - no token received.' },
});
expect(localStorage.getItem('stirling_jwt')).toBeNull();
// Advance timers to trigger the delayed navigation (2000ms delay in component)
await vi.advanceTimersByTimeAsync(2500);
expect(mockNavigate).toHaveBeenCalledWith('/login', {
replace: true,
state: { error: 'OAuth login failed - no token received.' },
});
expect(localStorage.getItem('stirling_jwt')).toBeNull();
});
it('should redirect to login when token validation fails', async () => {
const invalidToken = 'invalid-oauth-token';
window.location.hash = `#access_token=${invalidToken}`;
// Mock failed session validation
vi.mocked(springAuth.getSession).mockResolvedValueOnce({
data: { session: null },
error: { message: 'Invalid token' },
});
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>
);
await waitFor(() => {
// JWT should be stored initially
expect(localStorage.getItem('stirling_jwt')).toBeNull(); // Cleared after validation failure
// Verify redirect to login
expect(mockNavigate).toHaveBeenCalledWith('/login', {
replace: true,
state: { error: 'OAuth login failed - invalid token.' },
});
});
});
it('should handle errors gracefully', async () => {
const mockToken = 'error-token';
window.location.hash = `#access_token=${mockToken}`;
// Mock getSession throwing error
vi.mocked(springAuth.getSession).mockRejectedValueOnce(
new Error('Network error')
);
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>
);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/login', {
replace: true,
state: { error: 'OAuth login failed. Please try again.' },
});
});
});
it('should display loading state while processing', () => {
it('should display loading state initially', () => {
window.location.hash = '#access_token=processing-token';
vi.mocked(springAuth.getSession).mockImplementationOnce(
() =>
new Promise((resolve) =>
setTimeout(
() =>
resolve({
data: { session: null },
error: { message: 'Token expired' },
}),
100
)
)
);
// Mock useAuth returning loading state
mockUseAuth.mockReturnValue({ session: null, loading: true });
const { getByText } = render(
render(
<BrowserRouter>
<AuthCallback />
</BrowserRouter>
);
expect(getByText('Completing authentication')).toBeInTheDocument();
// Should show loading message
expect(screen.getByText('Completing authentication')).toBeInTheDocument();
});
});
+150 -52
View File
@@ -1,77 +1,175 @@
import { useEffect } from 'react';
import { useEffect, useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { springAuth } from '@app/auth/springAuthClient';
import { handleAuthCallbackSuccess } from '@app/extensions/authCallback';
import styles from '@app/routes/AuthCallback.module.css';
import { useAuth } from '@app/auth/UseSession';
// Use sessionStorage to track callback handling across React StrictMode double-renders
// Timestamp-based to allow retry after 10 seconds (e.g., if user tries again)
const AUTH_CALLBACK_TIMESTAMP_KEY = 'stirling_auth_callback_ts';
/**
* OAuth Callback Handler
* OAuth/SAML Callback Handler
*
* This component is rendered after OAuth providers (GitHub, Google, etc.) redirect back.
* This component is rendered after OAuth/SAML providers redirect back.
* The JWT is passed in the URL fragment (#access_token=...) by the Spring backend.
* We extract it, store in localStorage, and redirect to the home page.
*
* Flow:
* 1. Extract JWT from URL hash
* 2. Store in localStorage
* 3. Fire jwt-available event (AuthProvider will validate)
* 4. Wait for AuthProvider to confirm session
* 5. Navigate to home only after session is confirmed
*/
export default function AuthCallback() {
const navigate = useNavigate();
const { session, loading: authLoading } = useAuth();
const [status, setStatus] = useState<'extracting' | 'validating' | 'error'>('extracting');
const [_errorMessage, setErrorMessage] = useState<string | null>(null);
const [tokenStored, setTokenStored] = useState(false);
const processingRef = useRef(false);
// Step 1: Extract and store the token
useEffect(() => {
const handleCallback = async () => {
try {
console.log('[AuthCallback] Handling OAuth callback...');
// Check if we've already handled this callback recently (within 10 seconds)
const handledTimestamp = sessionStorage.getItem(AUTH_CALLBACK_TIMESTAMP_KEY);
const now = Date.now();
if (handledTimestamp && (now - parseInt(handledTimestamp, 10)) < 10000) {
console.debug('[AuthCallback] Already handled recently, checking session state');
setTokenStored(true);
setStatus('validating');
return;
}
// Extract JWT from URL fragment (#access_token=...)
const hash = window.location.hash.substring(1); // Remove '#'
const params = new URLSearchParams(hash);
const token = params.get('access_token');
// Use ref to prevent concurrent processing
if (processingRef.current) {
console.debug('[AuthCallback] Already processing, skipping');
return;
}
processingRef.current = true;
if (!token) {
console.error('[AuthCallback] No access_token in URL fragment');
navigate('/login', {
replace: true,
state: { error: 'OAuth login failed - no token received.' }
});
return;
}
console.log('[AuthCallback] Handling OAuth/SAML callback...');
console.debug('[AuthCallback] Current URL:', window.location.href);
console.debug('[AuthCallback] Hash:', window.location.hash);
// Store JWT in localStorage
localStorage.setItem('stirling_jwt', token);
console.log('[AuthCallback] JWT stored in localStorage');
// Extract JWT from URL fragment (#access_token=...)
const hash = window.location.hash.substring(1); // Remove '#'
const params = new URLSearchParams(hash);
const token = params.get('access_token');
// Dispatch custom event for other components to react to JWT availability
window.dispatchEvent(new CustomEvent('jwt-available'));
if (!token) {
console.error('[AuthCallback] No access_token in URL fragment');
console.debug('[AuthCallback] Full hash was:', hash);
setStatus('error');
setErrorMessage('Authentication failed - no token received from server.');
// Validate the token and load user info
// This calls /api/v1/auth/me with the JWT to get user details
const { data, error } = await springAuth.getSession();
if (error || !data.session) {
console.error('[AuthCallback] Failed to validate token:', error);
localStorage.removeItem('stirling_jwt');
navigate('/login', {
replace: true,
state: { error: 'OAuth login failed - invalid token.' }
});
return;
}
await handleAuthCallbackSuccess(token);
console.log('[AuthCallback] Token validated, redirecting to home');
// Clear the hash from URL and redirect to home page
navigate('/', { replace: true });
} catch (error) {
console.error('[AuthCallback] Error:', error);
setTimeout(() => {
navigate('/login', {
replace: true,
state: { error: 'OAuth login failed. Please try again.' }
state: { error: 'OAuth login failed - no token received.' }
});
}
};
}, 2000);
return;
}
handleCallback();
// Mark as handled BEFORE storing token
sessionStorage.setItem(AUTH_CALLBACK_TIMESTAMP_KEY, now.toString());
// Store JWT in localStorage
localStorage.setItem('stirling_jwt', token);
console.log('[AuthCallback] JWT stored in localStorage');
// Clear the hash from URL to prevent re-processing on page refresh
if (window.history.replaceState) {
window.history.replaceState(null, '', window.location.pathname);
}
// Update status
setStatus('validating');
// Dispatch jwt-available event - AuthProvider will validate the token
console.log('[AuthCallback] Firing jwt-available event for AuthProvider to validate');
window.dispatchEvent(new CustomEvent('jwt-available'));
// Small delay to allow AuthProvider to receive the event and start loading
// before we set tokenStored (which triggers the session watching effect)
setTimeout(() => {
console.log('[AuthCallback] Setting tokenStored=true to start watching session');
setTokenStored(true);
}, 50);
return () => {
processingRef.current = false;
};
}, [navigate]);
// Step 2: Wait for AuthProvider to validate and provide session
useEffect(() => {
if (!tokenStored) {
return; // Token not stored yet, wait
}
console.debug('[AuthCallback] Checking auth state:', {
authLoading,
hasSession: !!session,
tokenStored
});
// Still loading - wait for AuthProvider to finish validation
if (authLoading) {
return;
}
// AuthProvider finished loading
if (session) {
// Session validated successfully!
console.log('[AuthCallback] Session confirmed, user:', session.user?.email);
console.log('[AuthCallback] Redirecting to home...');
navigate('/', { replace: true });
} else {
// No session after AuthProvider finished - token was invalid
console.error('[AuthCallback] No session after validation - token may be invalid');
// Check if JWT is still in localStorage (AuthProvider removes it on 401)
const jwtStillExists = !!localStorage.getItem('stirling_jwt');
if (!jwtStillExists) {
setStatus('error');
setErrorMessage('Authentication failed - invalid or expired token.');
setTimeout(() => {
navigate('/login', {
replace: true,
state: { error: 'Authentication failed - please try again.' }
});
}, 2000);
}
// If JWT still exists but no session, AuthProvider might still be initializing
// Wait a bit more before giving up
}
}, [tokenStored, authLoading, session, navigate]);
// Timeout: If we've been validating for too long, show error
useEffect(() => {
if (status !== 'validating' || !tokenStored) {
return;
}
const timeoutId = setTimeout(() => {
if (!session) {
setStatus('error');
setErrorMessage('Authentication timed out. Please try again.');
setTimeout(() => {
navigate('/login', {
replace: true,
state: { error: 'Authentication timed out. Please try again.' }
});
}, 2000);
}
}, 10000); // 10 second timeout
return () => clearTimeout(timeoutId);
}, [status, tokenStored, session, navigate]);
return (
<div className={styles.page}>
<div className={styles.card}>
+41 -46
View File
@@ -61,6 +61,15 @@ vi.mock('@app/services/apiClient', () => ({
},
}));
// Helper to create mock API responses with TauriHttpResponse structure
const createMockResponse = <T,>(data: T) => ({
data,
status: 200,
statusText: 'OK',
headers: {},
config: {},
});
const mockNavigate = vi.fn();
const mockBackendProbeState = {
status: 'up' as const,
@@ -112,12 +121,10 @@ describe('Login', () => {
});
// Mock apiClient for login UI data
vi.mocked(apiClient.get).mockResolvedValue({
data: {
enableLogin: true,
providerList: {},
},
});
vi.mocked(apiClient.get).mockResolvedValue(createMockResponse({
enableLogin: true,
providerList: {},
}));
});
it('should render login form', async () => {
@@ -264,14 +271,12 @@ describe('Login', () => {
const user = userEvent.setup();
// Mock provider list with authentik
vi.mocked(apiClient.get).mockResolvedValue({
data: {
enableLogin: true,
providerList: {
'/oauth2/authorization/authentik': 'Authentik',
},
vi.mocked(apiClient.get).mockResolvedValue(createMockResponse({
enableLogin: true,
providerList: {
'/oauth2/authorization/authentik': 'Authentik',
},
});
}));
vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
error: null,
@@ -307,14 +312,12 @@ describe('Login', () => {
const user = userEvent.setup();
// Mock provider list with custom provider 'mycompany'
vi.mocked(apiClient.get).mockResolvedValue({
data: {
enableLogin: true,
providerList: {
'/oauth2/authorization/mycompany': 'My Company SSO',
},
vi.mocked(apiClient.get).mockResolvedValue(createMockResponse({
enableLogin: true,
providerList: {
'/oauth2/authorization/mycompany': 'My Company SSO',
},
});
}));
vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
error: null,
@@ -351,14 +354,12 @@ describe('Login', () => {
const user = userEvent.setup();
// Mock provider list with 'oidc'
vi.mocked(apiClient.get).mockResolvedValue({
data: {
enableLogin: true,
providerList: {
'/oauth2/authorization/oidc': 'OIDC',
},
vi.mocked(apiClient.get).mockResolvedValue(createMockResponse({
enableLogin: true,
providerList: {
'/oauth2/authorization/oidc': 'OIDC',
},
});
}));
vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
error: null,
@@ -510,12 +511,10 @@ describe('Login', () => {
it('should redirect to home when login disabled', async () => {
mockBackendProbeState.loginDisabled = true;
mockProbe.mockResolvedValueOnce({ status: 'up', loginDisabled: true, loading: false });
vi.mocked(apiClient.get).mockResolvedValueOnce({
data: {
enableLogin: false,
providerList: {},
},
});
vi.mocked(apiClient.get).mockResolvedValueOnce(createMockResponse({
enableLogin: false,
providerList: {},
}));
render(
<TestWrapper>
@@ -531,14 +530,12 @@ describe('Login', () => {
});
it('should handle OAuth provider click', async () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
data: {
enableLogin: true,
providerList: {
'/oauth2/authorization/github': 'GitHub',
},
vi.mocked(apiClient.get).mockResolvedValueOnce(createMockResponse({
enableLogin: true,
providerList: {
'/oauth2/authorization/github': 'GitHub',
},
});
}));
vi.mocked(springAuth.signInWithOAuth).mockResolvedValueOnce({
error: null,
@@ -565,12 +562,10 @@ describe('Login', () => {
});
it('should show email form by default when no SSO providers', async () => {
vi.mocked(apiClient.get).mockResolvedValueOnce({
data: {
enableLogin: true,
providerList: {}, // No providers
},
});
vi.mocked(apiClient.get).mockResolvedValueOnce(createMockResponse({
enableLogin: true,
providerList: {}, // No providers
}));
render(
<TestWrapper>
+34 -12
View File
@@ -35,7 +35,8 @@ export default function Login() {
const [password, setPassword] = useState('');
const [mfaCode, setMfaCode] = useState('');
const [requiresMfa, setRequiresMfa] = useState(false);
const [enabledProviders, setEnabledProviders] = useState<OAuthProvider[]>([]);
const [oauthProviders, setOauthProviders] = useState<OAuthProvider[]>([]);
const [samlProviders, setSamlProviders] = useState<OAuthProvider[]>([]);
const [hasSSOProviders, setHasSSOProviders] = useState(false);
const [_enableLogin, setEnableLogin] = useState<boolean | null>(null);
const [loginMethod, setLoginMethod] = useState<string>('all');
@@ -117,7 +118,11 @@ export default function Login() {
// We'll use these full paths so the auth client knows where to redirect
const providerPaths = Object.keys(data.providerList || {});
setEnabledProviders(providerPaths);
const oauth = providerPaths.filter(path => path.includes('/oauth2/'));
const saml = providerPaths.filter(path => path.includes('/saml2/'));
setOauthProviders(oauth);
setSamlProviders(saml);
setLoginMethod(data.loginMethod || 'all');
} catch (err) {
console.error('[Login] Failed to fetch enabled providers:', err);
@@ -134,7 +139,7 @@ export default function Login() {
// In debug mode, check if any providers exist in the config
const hasProviders = DEBUG_SHOW_ALL_PROVIDERS
? Object.keys(oauthProviderConfig).length > 0
: enabledProviders.length > 0;
: (oauthProviders.length > 0 || samlProviders.length > 0);
setHasSSOProviders(hasProviders);
// Check if username/password authentication is allowed
@@ -147,7 +152,7 @@ export default function Login() {
// Hide email form if username/password auth is not allowed
setShowEmailForm(false);
}
}, [enabledProviders, loginMethod]);
}, [oauthProviders, samlProviders, loginMethod]);
// Handle query params (email prefill, success messages, and session expiry)
useEffect(() => {
@@ -340,15 +345,32 @@ export default function Login() {
<ErrorMessage error={error} />
{/* OAuth first */}
<OAuthButtons
onProviderClick={signInWithProvider}
isSubmitting={isSigningIn}
layout="vertical"
enabledProviders={enabledProviders}
/>
{/* OAuth section */}
{oauthProviders.length > 0 && (
<OAuthButtons
onProviderClick={signInWithProvider}
isSubmitting={isSigningIn}
layout="vertical"
enabledProviders={oauthProviders}
/>
)}
{/* Divider between OAuth and Email - only show if SSO is available and username/password is allowed */}
{/* SAML section - show with divider if there are also OAuth providers */}
{samlProviders.length > 0 && (
<>
{oauthProviders.length > 0 && (
<DividerWithText text="SAML" respondsToDarkMode={false} opacity={0.4} />
)}
<OAuthButtons
onProviderClick={signInWithProvider}
isSubmitting={isSigningIn}
layout="vertical"
enabledProviders={samlProviders}
/>
</>
)}
{/* Divider between SSO and Email - only show if SSO is available and username/password is allowed */}
{hasSSOProviders && (loginMethod === 'all' || loginMethod === 'normal') && (
<DividerWithText text={t('signup.or', 'or')} respondsToDarkMode={false} opacity={0.4} />
)}
@@ -142,7 +142,14 @@
.oauth-container-vertical {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem; /* 12px */
width: 100%;
}
.oauth-container-vertical > div {
width: 100%;
max-width: 320rem; /* 320px - consistent width for all buttons */
}
.oauth-button-icon {
@@ -185,22 +192,24 @@
width: 100%;
display: flex;
align-items: center;
justify-content: flex-start;
padding: 0.75rem 1rem; /* 12px 16px */
border: 1px solid #d1d5db;
justify-content: center; /* Center icon and text */
padding: 0.875rem 1.25rem !important; /* 14px 20px - increased for better visibility */
min-height: 3rem !important; /* 48px - ensure readable height */
height: auto !important; /* Override Mantine default height */
border: 1px solid #d1d5db !important;
border-radius: 0.75rem; /* 12px */
background-color: var(--auth-card-bg-light-only);
background-color: var(--auth-card-bg-light-only) !important;
font-size: 1rem; /* 16px */
font-weight: 500;
color: var(--auth-text-primary-light-only);
color: var(--auth-text-primary-light-only) !important;
cursor: pointer;
gap: 0.75rem; /* 12px */
gap: 1rem !important; /* 16px - increased spacing between icon and text */
font-family: inherit;
transition: background-color 0.2s ease;
}
.oauth-button-vertical:hover:not(:disabled) {
background-color: #f3f4f6;
background-color: #f3f4f6 !important;
}
.oauth-button-vertical:disabled {
@@ -243,12 +252,16 @@
}
.oauth-icon-tiny {
width: 1.25rem; /* 20px */
height: 1.25rem; /* 20px */
width: 1.5rem; /* 24px - increased for better visibility */
height: 1.5rem; /* 24px */
display: block;
flex-shrink: 0;
}
.oauth-button-vertical span {
margin-left: 0.5rem; /* 8px - additional spacing between icon and text */
}
/* Login Header Styles */
.login-header {
margin-bottom: 1rem; /* 16px */
@@ -17,11 +17,15 @@ export const oauthProviderConfig: Record<string, { label: string; file: string }
keycloak: { label: 'Keycloak', file: 'keycloak.svg' },
cloudron: { label: 'Cloudron', file: 'cloudron.svg' },
authentik: { label: 'Authentik', file: 'authentik.svg' },
oidc: { label: 'OIDC', file: 'oidc.svg' }
intune: { label: 'Intune', file: 'intune.svg' },
pocketId: { label: 'Pocket ID', file: 'pocketid.svg' },
oidc: { label: 'OIDC', file: 'oidc.svg' },
saml: { label: 'SAML', file: 'saml.svg' },
};
// Generic fallback for unknown providers
const GENERIC_PROVIDER_ICON = 'oidc.svg';
// Generic fallback icons for unknown providers
const GENERIC_OAUTH_ICON = 'oidc.svg';
const GENERIC_SAML_ICON = 'saml.svg';
interface OAuthButtonsProps {
onProviderClick: (provider: OAuthProvider) => void
@@ -42,6 +46,7 @@ export default function OAuthButtons({ onProviderClick, isSubmitting, layout = '
const providers = providersToShow.map(pathOrId => {
// Extract provider ID from full path (e.g., '/saml2/authenticate/stirling' -> 'stirling')
const providerId = pathOrId.split('/').pop() || pathOrId;
const isSamlProvider = pathOrId.includes('/saml2/');
if (providerId in oauthProviderConfig) {
// Known provider - use predefined icon and label
@@ -51,12 +56,12 @@ export default function OAuthButtons({ onProviderClick, isSubmitting, layout = '
...oauthProviderConfig[providerId]
};
}
// Unknown provider - use generic icon and capitalize ID for label
// Unknown provider - use appropriate generic icon based on auth type
return {
id: pathOrId, // Keep full path for redirect
providerId, // Store extracted ID for display lookup
label: providerId.charAt(0).toUpperCase() + providerId.slice(1),
file: GENERIC_PROVIDER_ICON
file: isSamlProvider ? GENERIC_SAML_ICON : GENERIC_OAUTH_ICON
};
});
@@ -31,10 +31,14 @@ export function setupApiInterceptors(client: AxiosInstance): void {
(config) => {
const jwtToken = getJwtTokenFromStorage();
const xsrfToken = getXsrfToken();
const url = config.url || 'unknown';
if (jwtToken && !config.headers.Authorization) {
config.headers.Authorization = `Bearer ${jwtToken}`;
console.debug('[API Client] Added JWT token from localStorage to Authorization header');
console.debug('[API Client] Added JWT to request:', url);
} else if (!jwtToken) {
// Log when JWT is missing - helps debug auth issues
console.debug('[API Client] No JWT in localStorage for request:', url);
}
if (xsrfToken && !config.headers['X-XSRF-TOKEN']) {
@@ -48,7 +48,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
appVersion: '2.4.1',
appVersion: '2.4.2',
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
enableDesktopInstallSlide: true,
+5 -4
View File
@@ -7,9 +7,10 @@
]
}
},
"exclude": [
"src/proprietary",
"src/desktop",
"node_modules"
"include": [
"src/*.js",
"src/*.ts",
"src/*.tsx",
"src/core"
]
}
+15
View File
@@ -0,0 +1,15 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"paths": {
"@app/*": [
"src/core/*"
]
}
},
"exclude": [
"src/proprietary",
"src/desktop",
"node_modules"
]
}
+6 -7
View File
@@ -7,16 +7,15 @@
"src/proprietary/*",
"src/core/*"
],
"@desktop/*": ["src/desktop/*"],
"@proprietary/*": ["src/proprietary/*"],
"@core/*": ["src/core/*"]
}
},
"exclude": [
"src/core/**/*.test.ts*",
"src/core/**/*.spec.ts*",
"src/proprietary/**/*.test.ts*",
"src/proprietary/**/*.spec.ts*",
"node_modules"
"include": [
"src/*.js",
"src/*.ts",
"src/*.tsx",
"src/core/setupTests.ts",
"src/desktop"
]
}
+21
View File
@@ -0,0 +1,21 @@
{
"extends": "./tsconfig.proprietary.vite.json",
"compilerOptions": {
"paths": {
"@app/*": [
"src/desktop/*",
"src/proprietary/*",
"src/core/*"
],
"@proprietary/*": ["src/proprietary/*"],
"@core/*": ["src/core/*"]
}
},
"exclude": [
"src/core/**/*.test.ts*",
"src/core/**/*.spec.ts*",
"src/proprietary/**/*.test.ts*",
"src/proprietary/**/*.spec.ts*",
"node_modules"
]
}
-1
View File
@@ -36,7 +36,6 @@
"src/proprietary/*",
"src/core/*"
],
"@desktop/*": ["src/desktop/*"],
"@proprietary/*": ["src/proprietary/*"],
"@core/*": ["src/core/*"]
},
+6 -5
View File
@@ -9,10 +9,11 @@
"@core/*": ["src/core/*"]
}
},
"exclude": [
"src/core/**/*.test.ts*",
"src/core/**/*.spec.ts*",
"src/desktop",
"node_modules"
"include": [
"src/*.js",
"src/*.ts",
"src/*.tsx",
"src/core/setupTests.ts",
"src/proprietary"
]
}
+18
View File
@@ -0,0 +1,18 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"paths": {
"@app/*": [
"src/proprietary/*",
"src/core/*"
],
"@core/*": ["src/core/*"]
}
},
"exclude": [
"src/core/**/*.test.ts*",
"src/core/**/*.spec.ts*",
"src/desktop",
"node_modules"
]
}
+14 -2
View File
@@ -11,8 +11,8 @@ export default defineConfig(({ mode }) => {
process.env.STIRLING_DESKTOP === 'true' ||
process.env.VITE_DESKTOP === 'true';
const baseProject = isProprietary ? './tsconfig.proprietary.json' : './tsconfig.core.json';
const desktopProject = isProprietary ? './tsconfig.desktop.json' : baseProject;
const baseProject = isProprietary ? './tsconfig.proprietary.vite.json' : './tsconfig.core.vite.json';
const desktopProject = isProprietary ? './tsconfig.desktop.vite.json' : baseProject;
const tsconfigProject = isDesktopMode ? desktopProject : baseProject;
return {
@@ -78,6 +78,18 @@ export default defineConfig(({ mode }) => {
secure: false,
xfwd: true,
},
'/logout': {
target: 'http://localhost:8080',
changeOrigin: true,
secure: false,
xfwd: true,
},
'/logout/saml2': {
target: 'http://localhost:8080',
changeOrigin: true,
secure: false,
xfwd: true,
},
'/swagger-ui': {
target: 'http://localhost:8080',
changeOrigin: true,
+3 -3
View File
@@ -37,7 +37,7 @@ export default defineConfig({
plugins: [
react(),
tsconfigPaths({
projects: ['./tsconfig.core.json'],
projects: ['./tsconfig.core.vite.json'],
}),
],
esbuild: {
@@ -55,7 +55,7 @@ export default defineConfig({
plugins: [
react(),
tsconfigPaths({
projects: ['./tsconfig.proprietary.json'],
projects: ['./tsconfig.proprietary.vite.json'],
}),
],
esbuild: {
@@ -73,7 +73,7 @@ export default defineConfig({
plugins: [
react(),
tsconfigPaths({
projects: ['./tsconfig.desktop.json'],
projects: ['./tsconfig.desktop.vite.json'],
}),
],
esbuild: {
+42 -8
View File
@@ -496,16 +496,50 @@ def wrap_cff_as_otf(input_path, output_path, tounicode_path=None):
def main():
if len(sys.argv) < 3:
print(
"Usage: convert_cff_to_ttf.py <input.cff> <output.otf> [tounicode.cmap]",
file=sys.stderr,
)
import argparse
# Create argument parser that supports both named and positional arguments
parser = argparse.ArgumentParser(
description="Convert CFF font data to OpenType-CFF format",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Named arguments (used by Java code):
convert_cff_to_ttf.py --input font.cff --output font.otf --to-unicode mapping.tounicode
# Positional arguments (backward compatibility):
convert_cff_to_ttf.py font.cff font.otf mapping.tounicode
""",
)
# Add named arguments
parser.add_argument("--input", dest="input_file", help="Input CFF file path")
parser.add_argument("--output", dest="output_file", help="Output OTF file path")
parser.add_argument(
"--to-unicode", dest="tounicode_file", help="ToUnicode mapping file path"
)
# Add positional arguments for backward compatibility
parser.add_argument("input_pos", nargs="?", help="Input CFF file (positional)")
parser.add_argument("output_pos", nargs="?", help="Output OTF file (positional)")
parser.add_argument("tounicode_pos", nargs="?", help="ToUnicode file (positional)")
args = parser.parse_args()
# Determine which arguments to use (named take precedence over positional)
input_path = args.input_file or args.input_pos
output_path = args.output_file or args.output_pos
tounicode_path = args.tounicode_file or args.tounicode_pos
# Validate required arguments
if not input_path or not output_path:
parser.print_help(file=sys.stderr)
print("\nERROR: Both input and output files are required", file=sys.stderr)
sys.exit(1)
input_path = Path(sys.argv[1])
output_path = Path(sys.argv[2])
tounicode_path = Path(sys.argv[3]) if len(sys.argv) > 3 else None
input_path = Path(input_path)
output_path = Path(output_path)
tounicode_path = Path(tounicode_path) if tounicode_path else None
if not input_path.exists():
print(f"ERROR: Input file not found: {input_path}", file=sys.stderr)